diff --git a/CHANGELOG.md b/CHANGELOG.md index e5cc57a8b..ff32a5ad8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -28,6 +28,7 @@ All notable changes to Bambuddy will be documented in this file. - **The Windows installer build is split in two so a signing request can wait for a human (SignPath Foundation)** — Release tags are Authenticode-signed through the SignPath Foundation OSS programme, and the production certificate does not sign on demand the way the self-signed test certificate does: every request has to be approved by hand in the SignPath UI, because the Foundation verifies what is being signed and which build it came from. The submitting action waits for that approval with a default timeout of 600 seconds, which is ample when the test policy approves automatically in seconds and far too short once the wait is a person noticing a tag went out. A tag pushed at night would have failed the run ten minutes later with the installer already compiled and thrown away. The compile now ends in its own job that uploads the unsigned artifact and stops; a second job downloads it, signs it, and does the release-facing work, with the wait raised to an hour. Because the artifact is uploaded before the wait begins and is addressed by id, a missed approval window is recovered by re-running the second job alone rather than rebuilding the installer — which is the reason to separate them rather than simply raise the timeout in place. The second job runs for unsigned builds too, so the daily prereleases that are deliberately left unsigned to preserve the signing quota keep going out through exactly one set of alias, artifact and release steps. The property that matters is unchanged and now recorded next to the steps that depend on it: none of the alias, upload or release-attach steps carry `always()`, so GitHub skips all three when signing fails or times out, and an unsigned `.exe` cannot reach a release. Nothing about the signed output changes, and the restructure behaves identically under the test policy — the request simply completes immediately instead of waiting — so it can be proven green before the production certificate arrives. ### Fixed +- **Custom filament profiles arrived in the slicer as Generic, or as the Bambu profile they were built on (#3003, reported by @marivo)** — a custom profile reaches an AMS slot as itself through exactly one field, the slot's filament id, and every source Bambuddy can get that id from was reading it from the wrong place or not at all. Bambu Cloud reports it in either of two spots depending on the preset and only one was read, so presets of the other shape fell back to the id of the Bambu filament they inherit from — which is what the slicer then showed. Orca Cloud profiles were never looked up at all: their ids are UUIDs the printer cannot store, so the code went straight to a generic without ever asking whether the profile had a usable id of its own, which it normally does. And the Configure AMS Slot dialog, when it could not find a real id, sent the preset's own identifier instead — that field holds eight characters, less than half an identifier, so it was stored truncated and acknowledged as a success, leaving the slot pointing at nothing and the printer's calibration table, keyed by the same field, without a slot to key. All four sources are now tried in order — Orca Cloud, Bambu Cloud, imported local profiles, then a generic for the material — and nothing the printer cannot store is sent. A profile that genuinely has no filament id of its own still cannot be told apart from the one it inherits from; there is nowhere else in what a printer publishes to put it. - **Hovering a muted control in the light theme made its label vanish (#1909, reported by @AntonPalmqvist)** — the tab strip on the Print Queue page was where it got noticed: point at **Batches** and the word turned white on a near-white background. It was never about that tab. The light theme keeps `text-white` readable by remapping it to the theme's foreground colour, but that remapping only ever matched the plain utility, not the `hover:` variant Tailwind compiles to a different selector — so roughly 400 controls across the app that dim their label at rest and brighten it on hover were brightening it to literal white, whatever the theme. They now follow the theme like everything else. Dark themes are unaffected, their foreground colour already being white, and the handful of buttons that turn a solid accent colour on hover read better for it rather than worse. - **Every camera stopped working on 1.2.5.4 (#3001, reported by @Jieper001, confirmed by @JmanB52D and @hikingthunder)** — live view, snapshots, timelapse frames and the camera diagnostic all failed at once on every RTSP model — X1, H2 and P2 — with the in-app diagnostic reporting `capture_exception` at 0 ms while network reachability passed at 1 ms. That 0 ms is the whole story: the failure happened before a socket was opened. The RTSPS proxy added in 1.2.5.4 finished by hanging its set of in-flight connection handlers on the server object as an attribute. `asyncio.start_server` returns an `asyncio.base_events.Server`, which has a `__dict__` and accepts that; under uvloop it returns a `uvloop.loop.Server`, a Cython cdef class with no `__dict__`, which raises `AttributeError` outright. Every launch path this repo ships — the Dockerfile, `install/install.sh`, `deploy/bambuddy.service`, the Windows service and the SpoolBuddy installer — pins `--loop asyncio`, added for #1896, so none of them selects uvloop and none of them could hit this. What broke is the installs running a unit file we did not write. The Proxmox VE Helper-Scripts LXC composes its own `ExecStart` with no loop pinned, and `requirements.txt` pins `uvicorn[standard]`, which installs uvloop on Linux, so uvicorn's default `--loop auto` selects it — that is the reporter's install and the two that confirmed it. Native installs created before the #1896 pin landed on 2026-07-05 are in the same position for a different reason: `install/update.sh` never rewrites the unit file, so a service written before that date has never been given the flag by any update since. Those installs are also still exposed to #1896 itself, where a truncated Virtual Printer FTP upload corrupts a `.gcode.3mf` silently; the camera outage is simply the visible half. Hence a fix in the code rather than another flag in a unit file: the proxy now works on either loop instead of depending on the launch command to steer around it. The handler set now lives in a module-level registry keyed weakly by server, which both loops accept; keying it weakly rather than by `id(server)` means a proxy abandoned without a close takes its entry with it, instead of leaking one forever and eventually handing a new server a dead one's handlers once CPython recycles the address. A1 and P1 use the chamber-image protocol and return before the proxy is built, so they were never affected, and external RTSPS cameras caught the error and fell back to a direct connection, so they kept working without the TLS workaround. The reason the test suite could not see any of this is that `conftest` builds its event loop from the default policy, so every async test in the repo runs on the selector loop — the one loop where the assignment was legal. The regression is now pinned twice: once by a test that drives the real function on a real uvloop loop, and once by a test that gives it a `__slots__` server, so the contract holds even where uvloop is not installed. The two external-camera teardowns were also switched to `close_tls_proxy`, which #2968 introduced and left them out of, so they no longer leave handlers running past the server that owned them. - **Some archived 3MFs lost their G-code when re-imported into the File Manager (#2993, reported via the in-app form)** — they never lost it. The download serves the stored file byte for byte, and the G-code was still in the zip; what differed was who was asked. On the archive side the answer came from the file itself — the green GCODE badge reads the layer count and print time that were parsed out of the plate G-code — while the library decided from the filename alone, so a sliced 3MF stored as `Foo.3mf` rather than `Foo.gcode.3mf` carried the badge and still came back as a source-only project with no Print button. That splits on how the print reached the printer, not on anything about the file — a slicer's LAN send names it `.gcode.3mf`, while a per-plate export or a cloud-dispatched print arrives as plain `.3mf` — which is why it looked random. Both sides now ask the same question of the zip itself, and every route into the library (upload, ZIP import, MakerWorld, external-folder scan) classifies on content rather than on the name. Files already in your library are re-checked once on the next start. The backend was always willing to print these, so this was only ever the interface refusing to offer something that would have worked; a genuine model file is unaffected, and one that now shows **Print** correctly stops offering **Slice**. diff --git a/backend/app/api/routes/printers.py b/backend/app/api/routes/printers.py index 102287496..d0e1d553d 100644 --- a/backend/app/api/routes/printers.py +++ b/backend/app/api/routes/printers.py @@ -87,9 +87,10 @@ from backend.app.services.printer_media import ( remove_printer_files_zip, start_printer_files_job, ) +from backend.app.services.slicer_filament_resolver import _ORCA_PROFILE_ID from backend.app.services.slot_nozzle import resolve_slot_nozzle from backend.app.utils.filament_ids import filament_id_to_setting_id -from backend.app.utils.filament_types import printer_filament_type +from backend.app.utils.filament_types import is_material_name, printer_filament_type from backend.app.utils.fts_routing import slot_extruder from backend.app.utils.http import build_content_disposition, download_error_response, safe_download_filename from backend.app.utils.kprofile_lookup import build_slot_k_resolver @@ -2849,10 +2850,49 @@ async def configure_ams_slot( if not client: raise HTTPException(status_code=400, detail="Printer not connected") + # Discard a tray_info_idx the printer cannot store (#3003). + # + # The field is 8 characters wide. A local preset id ("P" + 7 hex) is + # exactly 8, which is presumably why nobody noticed -- but a cloud + # *setting* id is 18, and the firmware keeps the first 8 and reports + # success. Measured on @marivo's A1 in the #3003 bundle: + # + # sent tray_info_idx=PFUS9ddc938fe3ab8f + # printer Assignment NOT confirmed: tray shows PFUS9DDC + # + # `PFUS9ddc` resolves to nothing anywhere, so the slot came out of the + # Configure modal as "Generic " in the slicer -- strictly worse + # than the base filament it would have got from the fallback below, and it + # also breaks the calibration table, which is keyed by this field. + # + # Blanking it here is what hands the slot to the reuse / generic branch. + # The preset reference is not lost: it stays in setting_id, the field that + # does accept a PFUS. Same four rejected shapes, and the same reasoning, as + # `slicer_filament_resolver`'s closing guard -- which the assignment path + # has run since #1815 while Configure had none. The Orca profile UUID is on + # the list for the same reason as the rest: the modal no longer sends one, + # but this route is public API and 36 characters is the worst of the four + # against an 8-character field. + if tray_info_idx and ( + tray_info_idx.startswith("PFUS") + or tray_info_idx.startswith("PFCN") + or _ORCA_PROFILE_ID.fullmatch(tray_info_idx) + or is_material_name(tray_info_idx) + ): + logger.info( + "[configure_ams_slot] tray_info_idx %r is not storable as a filament id — " + "falling back to slot reuse / generic (kept as setting_id %r)", + tray_info_idx, + setting_id or tray_info_idx, + ) + if not setting_id and (tray_info_idx.startswith("PFUS") or tray_info_idx.startswith("PFCN")): + setting_id = tray_info_idx + tray_info_idx = "" + # Resolve tray_info_idx for the MQTT command. # Priority: - # 1. Use the provided tray_info_idx if set (including cloud-synced - # custom presets like PFUS* / P*). + # 1. Use the provided tray_info_idx if set, once the guard above has had + # its say (so: a GF* official or P* local id, never a PFUS/PFCN one). # 2. Reuse the slot's existing tray_info_idx if it's a specific # (non-generic) preset for the same material. # 3. Fall back to a generic Bambu filament ID. diff --git a/backend/app/services/slicer_filament_resolver.py b/backend/app/services/slicer_filament_resolver.py index 9060a5de4..254f4ba18 100644 --- a/backend/app/services/slicer_filament_resolver.py +++ b/backend/app/services/slicer_filament_resolver.py @@ -35,10 +35,12 @@ from __future__ import annotations import json import logging +import re from sqlalchemy import select from sqlalchemy.ext.asyncio import AsyncSession +from backend.app.core.permissions import Permission from backend.app.models.user import User from backend.app.utils.filament_ids import ( GENERIC_FILAMENT_IDS, @@ -49,6 +51,65 @@ from backend.app.utils.filament_types import is_material_name logger = logging.getLogger(__name__) +# Orca Cloud profile ids are UUIDs, the one preset reference in this codebase +# with no letter prefix to key off. A spool stores the bare id (the spool form +# persists ``preset.setting_id`` verbatim), so shape is all there is to go on. +_ORCA_PROFILE_ID = re.compile(r"[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}") + + +async def _orca_filament_id( + db: AsyncSession, + current_user: User | None, + profile_id: str, +) -> tuple[str, str | None, str | None]: + """Look up an Orca Cloud profile's own filament_id. + + Returns ``(filament_id, name, filament_type)`` -- all empty/None when the + profile cannot be fetched or carries no id of its own, which leaves the + caller on its generic fallback. + + Best-effort by construction: this runs inside spool assignment, not a user + request, so a missing pairing, a revoked token or a lapsed permission must + degrade to the fallback rather than fail the assignment. That is also why + ``clear_on_auth_failure=False`` -- Orca reports every refresh rejection with + one composite reason, so a background caller cannot tell a real revocation + from a lost rotation race and must not wipe a working pairing on it. The + route path hits the same failure in front of a user and clears there. + """ + if current_user is not None and not current_user.has_permission(Permission.ORCA_CLOUD_AUTH.value): + logger.debug("Orca filament lookup skipped for %r: caller lacks orca_cloud:auth", profile_id) + return ("", None, None) + + svc = None + try: + from backend.app.api.routes.orca_cloud import _build_authenticated_service + + svc = await _build_authenticated_service(db, current_user, clear_on_auth_failure=False) + profile = await svc.get_profile(profile_id) + except Exception as e: + logger.debug("Orca filament lookup failed for %r: %s", profile_id, e) + return ("", None, None) + finally: + # A raise in `finally` escapes the `except` above, so guard it: closing + # an httpx client must never be what fails a spool assignment. + if svc is not None: + try: + await svc.close() + except Exception as e: # noqa: BLE001 - close() is best-effort + logger.debug("Orca client close failed after lookup of %r: %s", profile_id, e) + + content = profile.get("content") if isinstance(profile, dict) else None + if not isinstance(content, dict): + return ("", None, None) + raw_fid = content.get("filament_id") + filament_id = raw_fid.strip() if isinstance(raw_fid, str) else "" + name = profile.get("name") if isinstance(profile, dict) else None + return ( + filament_id, + name if isinstance(name, str) and name else None, + _preset_filament_type(content.get("filament_type")), + ) + def _preset_filament_type(raw: object) -> str | None: """Read a slicer preset's ``filament_type`` field. @@ -129,7 +190,26 @@ async def resolve_slicer_filament( # All three need a cloud-detail lookup to extract the underlying # filament_id; without it the raw cloud id ends up in tray_info_idx # and the printer's calibration table can't resolve it. - if base_sf.startswith("GFS") or base_sf.startswith("PFUS") or base_sf.startswith("PFCN"): + # Source order is Orca Cloud, Bambu Cloud, local import, generic fallback. + # Orca goes first because its ids are the only ones identified by shape + # rather than prefix -- and because, before #3003, a UUID fell through every + # branch below into ``normalize_slicer_filament``, which passes anything it + # does not recognise straight through. A 36-character UUID then went into + # tray_info_idx, an 8-character field, and the slot ended up pointing at the + # first 8 characters of a UUID: the same failure the PFUS guard at the + # bottom of this function exists for. + if _ORCA_PROFILE_ID.fullmatch(base_sf): + tray_info_idx, orca_name, orca_type = await _orca_filament_id(db, current_user, base_sf) + if orca_type: + type_override = orca_type + if orca_name: + sub_brand_override = orca_name.split("@")[0].strip() + # setting_id is left empty here: the UUID is what the slicer cannot + # resolve, and unlike a PFUS there is no cloud id form it accepts + # instead. All three callers then derive one from the filament_id + # (`filament_id_to_setting_id`), which is what keeps the slot from + # going out half configured -- the same path a local import takes. + elif base_sf.startswith("GFS") or base_sf.startswith("PFUS") or base_sf.startswith("PFCN"): setting_id = base_sf try: from backend.app.api.routes.cloud import build_authenticated_cloud @@ -147,8 +227,21 @@ async def resolve_slicer_filament( type_override = _preset_filament_type( (cloud_setting if isinstance(cloud_setting, dict) else detail).get("filament_type") ) - if detail.get("filament_id"): - tray_info_idx = detail["filament_id"] + # A custom preset's OWN filament_id is the only thing that + # gets it into an AMS slot as itself: the printer stores + # that id, the slicer matches its presets against it, and + # the 8-character field fits it exactly ("P" + 7 hex). + # Bambu Cloud puts it in either of two places -- on the + # envelope, or inside the preset JSON under `setting` -- + # the same spread `filament_type` above already handles. + # Reading only the envelope is how a custom preset fell + # through to the base_id branch below and reached the + # slicer as the Bambu profile it inherits from (#3003). + own_filament_id = detail.get("filament_id") or ( + cloud_setting.get("filament_id") if isinstance(cloud_setting, dict) else None + ) + if own_filament_id: + tray_info_idx = own_filament_id cloud_name = detail.get("name", "") if cloud_name: sub_brand_override = cloud_name.replace(r"@.*$", "").split("@")[0].strip() @@ -245,10 +338,16 @@ async def resolve_slicer_filament( # the original assign. # 3. PFCN-prefix cloud shared / partner presets (e.g. Polymaker's # "(Custom)" H2D variants, #1648) — same shape problem as PFUS. + # 4. Orca Cloud profile UUIDs, when the branch above could not reach the + # profile to trade one for its filament_id (#3003). Worst of the four + # at 36 characters against an 8-character field. # Valid tray_info_idx values: "GF" + letter + digits (Bambu official) or # "P" followed by hex (user/local presets, NOT "PFUS" or "PFCN"). if tray_info_idx and ( - is_material_name(tray_info_idx) or tray_info_idx.startswith("PFUS") or tray_info_idx.startswith("PFCN") + is_material_name(tray_info_idx) + or tray_info_idx.startswith("PFUS") + or tray_info_idx.startswith("PFCN") + or _ORCA_PROFILE_ID.fullmatch(tray_info_idx) ): tray_info_idx = "" # Preserve setting_id when it's still a valid slicer reference diff --git a/backend/tests/integration/test_printers_api.py b/backend/tests/integration/test_printers_api.py index df2512fa9..f7957d472 100644 --- a/backend/tests/integration/test_printers_api.py +++ b/backend/tests/integration/test_printers_api.py @@ -1708,8 +1708,19 @@ class TestConfigureAMSSlotAPI: @pytest.mark.asyncio @pytest.mark.integration - async def test_configure_pfus_sent_directly(self, async_client: AsyncClient, printer_factory): - """PFUS* cloud-synced custom preset IDs are sent to the printer.""" + async def test_configure_pfus_never_reaches_tray_info_idx(self, async_client: AsyncClient, printer_factory): + """A PFUS* cloud setting_id is refused as tray_info_idx (#3003). + + The printer's tray_info_idx field is 8 characters. An 18-character PFUS + is stored truncated and acknowledged as a success -- measured on the A1 + in the #3003 bundle, which sent PFUS9ddc938fe3ab8f and read back + PFUS9DDC. That leaves the slot holding an id nothing resolves, so the + slicer shows "Generic" and the calibration table loses the slot too. + A generic for the material is strictly better, and the preset reference + survives in setting_id, which does accept a PFUS. + + Reverses the contract #1053 pinned; see the route's own comment. + """ printer = await printer_factory(name="H2D") mock_client = MagicMock() @@ -1738,12 +1749,20 @@ class TestConfigureAMSSlotAPI: assert response.status_code == 200 call_kwargs = mock_client.ams_set_filament_setting.call_args - assert call_kwargs.kwargs["tray_info_idx"] == "PFUS9ac902733670a9" + # No tray to reuse -> generic for the material, never the raw PFUS. + assert call_kwargs.kwargs["tray_info_idx"] == "GFL99" + # The preset reference is not lost: it moves to the field that holds it. + assert call_kwargs.kwargs["setting_id"] == "PFUS9ac902733670a9" @pytest.mark.asyncio @pytest.mark.integration - async def test_configure_pfus_takes_priority_over_slot(self, async_client: AsyncClient, printer_factory): - """Provided PFUS* preset takes priority over slot's existing preset.""" + async def test_configure_pfus_falls_back_to_slot_preset(self, async_client: AsyncClient, printer_factory): + """With a PFUS refused, the slot's own resolvable preset is reused (#3003). + + The slot already carries P4d64437 -- a local preset id, 8 characters, so + the printer can actually store it -- for the same material. That beats a + generic, and it is what the slot's calibration is keyed by. + """ printer = await printer_factory(name="H2D") mock_client = MagicMock() @@ -1789,13 +1808,19 @@ class TestConfigureAMSSlotAPI: assert response.status_code == 200 call_kwargs = mock_client.ams_set_filament_setting.call_args - # Provided preset wins over slot's existing one - assert call_kwargs.kwargs["tray_info_idx"] == "PFUS9ac902733670a9" + # Slot's own storable preset wins over both the PFUS and a generic. + assert call_kwargs.kwargs["tray_info_idx"] == "P4d64437" + assert call_kwargs.kwargs["setting_id"] == "PFUS9ac902733670a9" @pytest.mark.asyncio @pytest.mark.integration - async def test_configure_pfus_used_regardless_of_slot_material(self, async_client: AsyncClient, printer_factory): - """Provided PFUS* preset is used even when slot has a different material.""" + async def test_configure_pfus_generic_when_slot_material_differs(self, async_client: AsyncClient, printer_factory): + """A slot holding a different material is not reused (#3003). + + Slot has generic PETG, the user is configuring PLA. Neither the refused + PFUS nor the mismatched slot can supply a filament id, so the generic + for the requested material does. + """ printer = await printer_factory(name="H2D") mock_client = MagicMock() @@ -1834,8 +1859,8 @@ class TestConfigureAMSSlotAPI: assert response.status_code == 200 call_kwargs = mock_client.ams_set_filament_setting.call_args - # Provided preset wins — slot's material is irrelevant - assert call_kwargs.kwargs["tray_info_idx"] == "PFUS9ac902733670a9" + assert call_kwargs.kwargs["tray_info_idx"] == "GFL99" + assert call_kwargs.kwargs["setting_id"] == "PFUS9ac902733670a9" @pytest.mark.asyncio @pytest.mark.integration @@ -1873,13 +1898,19 @@ class TestConfigureAMSSlotAPI: @pytest.mark.asyncio @pytest.mark.integration - async def test_configure_pfus_preserves_setting_id_pair(self, async_client: AsyncClient, printer_factory): - """Both tray_info_idx=PFUS* and setting_id=PFUS* are forwarded untouched. + async def test_configure_pfus_pair_splits_into_generic_and_setting_id( + self, async_client: AsyncClient, printer_factory + ): + """A PFUS sent in BOTH fields is kept only in setting_id (#3003). - Pins the end-to-end contract the frontend #1053 fix relies on: when the - user configures a slot with a custom cloud preset whose cloud detail - has filament_id=null, the frontend sends the setting_id in BOTH fields - and the backend must not collapse either to a generic GF* ID. + This is the shape the frontend produced when a custom cloud preset's + detail had filament_id=null, and what #1053 pinned. The A1 measurement + in #3003 showed where it ends up: the printer truncates tray_info_idx + to 8 characters, so the slot resolves to nothing and the slicer falls + back to "Generic" anyway -- the very outcome #1053 set out to avoid, + plus a broken calibration key. Sending the generic deliberately gets + the same slicer result honestly and keeps the slot calibratable, and + setting_id still carries the user's preset. """ printer = await printer_factory(name="H2D") @@ -1910,10 +1941,47 @@ class TestConfigureAMSSlotAPI: assert response.status_code == 200 call_kwargs = mock_client.ams_set_filament_setting.call_args - assert call_kwargs.kwargs["tray_info_idx"] == "PFUSa8fb76f9733e3c" + assert call_kwargs.kwargs["tray_info_idx"] == "GFB99" assert call_kwargs.kwargs["setting_id"] == "PFUSa8fb76f9733e3c" - # Explicitly assert no generic-collapse happened for this HT slot. - assert call_kwargs.kwargs["tray_info_idx"] != "GFB99" + + @pytest.mark.asyncio + @pytest.mark.integration + async def test_configure_pfcn_refused_as_tray_info_idx(self, async_client: AsyncClient, printer_factory): + """PFCN* shared / partner presets are refused the same way (#3003, #1648). + + Same 18-character shape as a PFUS, same truncation. Polymaker's + "(Custom)" H2D variants are the ones that reach this in the wild. + """ + printer = await printer_factory(name="H2D") + + mock_client = MagicMock() + mock_client.ams_set_filament_setting.return_value = True + mock_client.extrusion_cali_sel.return_value = True + mock_client.request_status_update.return_value = True + + mock_status = MagicMock() + mock_status.raw_data = {"ams": {"ams": []}} + + with patch("backend.app.api.routes.printers.printer_manager") as mock_pm: + mock_pm.get_client.return_value = mock_client + mock_pm.get_status.return_value = mock_status + + response = await async_client.post( + f"/api/v1/printers/{printer.id}/slots/0/1/configure", + params={ + "tray_info_idx": "PFCN2a91c7d0e4b118", + "tray_type": "PETG", + "tray_sub_brands": "Polymaker PETG (Custom)", + "tray_color": "0000FFFF", + "nozzle_temp_min": 220, + "nozzle_temp_max": 260, + }, + ) + + assert response.status_code == 200 + call_kwargs = mock_client.ams_set_filament_setting.call_args + assert call_kwargs.kwargs["tray_info_idx"] == "GFG99" + assert call_kwargs.kwargs["setting_id"] == "PFCN2a91c7d0e4b118" class TestSkipObjectsAPI: diff --git a/backend/tests/unit/services/test_slicer_filament_resolver.py b/backend/tests/unit/services/test_slicer_filament_resolver.py index c9417e0cb..cd454ad54 100644 --- a/backend/tests/unit/services/test_slicer_filament_resolver.py +++ b/backend/tests/unit/services/test_slicer_filament_resolver.py @@ -260,3 +260,226 @@ class TestThePresetsOwnType: material="PETG", ) assert type_override is None + + +class TestACustomPresetsOwnFilamentId: + """Where the id that carries a custom preset into an AMS slot comes from. + + The slot holds one filament reference and the printer truncates it to 8 + characters, so a custom preset reaches the slicer as itself only when its + own filament_id ("P" + 7 hex) goes into ``tray_info_idx``. 92 trays across + eight models in the support archive do exactly that, so the mechanism + works -- what #3003 found is that we only ever read one of the two places + Bambu Cloud returns that id from. + """ + + @pytest.mark.asyncio + async def test_filament_id_is_read_from_inside_the_preset_json(self): + """The envelope has none, the preset JSON does -- and it wins over base_id. + + Before #3003 this fell through to the base_id branch and the slot came + out as the Bambu profile the custom preset inherits from. + """ + db = MagicMock() + cloud = MagicMock() + cloud.is_authenticated = True + cloud.get_setting_detail = AsyncMock( + return_value={ + "name": "SUNLU PLA Transparent @BBL A1", + "base_id": "GFSNLS03", + "setting": {"filament_id": "P4d64437", "filament_type": ["PLA"]}, + } + ) + cloud.close = AsyncMock() + with patch( + "backend.app.api.routes.cloud.build_authenticated_cloud", + AsyncMock(return_value=cloud), + ): + idx, sid, brand, _type = await resolve_slicer_filament( + db=db, + current_user=None, + slicer_filament="PFUSfb87cd50b76616", + slicer_filament_name=None, + material="PLA", + ) + assert idx == "P4d64437" + assert sid == "PFUSfb87cd50b76616" + assert brand == "SUNLU PLA Transparent" + + @pytest.mark.asyncio + async def test_the_envelope_still_wins_when_it_has_one(self): + """Unchanged behaviour for the presets that already resolved.""" + db = MagicMock() + cloud = MagicMock() + cloud.is_authenticated = True + cloud.get_setting_detail = AsyncMock( + return_value={ + "filament_id": "P285e239", + "name": "Jayo PETG HF @P1S", + "base_id": "GFSG02", + "setting": {"filament_id": "P999aaaa"}, + } + ) + cloud.close = AsyncMock() + with patch( + "backend.app.api.routes.cloud.build_authenticated_cloud", + AsyncMock(return_value=cloud), + ): + idx, _sid, _brand, _type = await resolve_slicer_filament( + db=db, + current_user=None, + slicer_filament="PFUS992454068158eb", + slicer_filament_name=None, + material="PETG", + ) + assert idx == "P285e239" + + @pytest.mark.asyncio + async def test_base_id_is_still_the_fallback_when_neither_place_has_one(self): + """A preset with no filament_id of its own genuinely is its base, and + the base id is storable, so it is the right answer -- just not one to + reach for while the preset's own id is sitting under ``setting``.""" + db = MagicMock() + cloud = MagicMock() + cloud.is_authenticated = True + cloud.get_setting_detail = AsyncMock( + return_value={"name": "My PLA @BBL A1", "base_id": "GFSNLS03", "setting": {}} + ) + cloud.close = AsyncMock() + with patch( + "backend.app.api.routes.cloud.build_authenticated_cloud", + AsyncMock(return_value=cloud), + ): + idx, sid, _brand, _type = await resolve_slicer_filament( + db=db, + current_user=None, + slicer_filament="PFUSfb87cd50b76616", + slicer_filament_name=None, + material="PLA", + ) + assert idx == "GFNLS03" + assert sid == "PFUSfb87cd50b76616" + + +class TestOrcaCloudIsTheFirstSource: + """Source order is Orca Cloud, Bambu Cloud, local import, generic. + + Orca was absent from the resolver entirely: a spool referencing an Orca + profile stores the bare UUID, which matched no branch and fell through + ``normalize_slicer_filament`` -- a function that passes anything it does + not recognise straight through. The UUID reached tray_info_idx, a field + the printer truncates to 8 characters (#3003). + """ + + ORCA_ID = "3f2a9c1e-4b7d-4a02-9f61-8c5e2d1a7b30" + + @staticmethod + def _svc(profile): + svc = MagicMock() + svc.get_profile = AsyncMock(return_value=profile) + svc.close = AsyncMock() + return svc + + @pytest.mark.asyncio + async def test_the_profiles_own_filament_id_is_used(self): + db = MagicMock() + svc = self._svc( + { + "id": self.ORCA_ID, + "name": "Overture Matte PLA @Orca", + "content": {"filament_id": "P56e1be0", "filament_type": ["PLA"]}, + } + ) + with patch( + "backend.app.api.routes.orca_cloud._build_authenticated_service", + AsyncMock(return_value=svc), + ): + idx, sid, brand, type_override = await resolve_slicer_filament( + db=db, + current_user=None, + slicer_filament=self.ORCA_ID, + slicer_filament_name=None, + material="PLA", + ) + assert idx == "P56e1be0" + # The UUID is foreign to the slicer in either field, so nothing carries it. + assert sid == "" + assert brand == "Overture Matte PLA" + assert type_override == "PLA" + svc.close.assert_awaited() + + @pytest.mark.asyncio + async def test_a_profile_with_no_filament_id_leaves_the_caller_its_fallback(self): + db = MagicMock() + svc = self._svc({"id": self.ORCA_ID, "name": "My PLA", "content": {"filament_type": ["PLA"]}}) + with patch( + "backend.app.api.routes.orca_cloud._build_authenticated_service", + AsyncMock(return_value=svc), + ): + idx, sid, _brand, _type = await resolve_slicer_filament( + db=db, + current_user=None, + slicer_filament=self.ORCA_ID, + slicer_filament_name=None, + material="PLA", + ) + assert idx == "" + assert sid == "" + + @pytest.mark.asyncio + async def test_an_unreachable_orca_never_leaks_the_uuid(self): + """No pairing, dead token, Orca down -- all the same answer. The UUID + must not reach tray_info_idx, which is what happened before the branch + existed at all.""" + db = MagicMock() + with patch( + "backend.app.api.routes.orca_cloud._build_authenticated_service", + AsyncMock(side_effect=RuntimeError("Orca Cloud is not connected")), + ): + idx, sid, _brand, _type = await resolve_slicer_filament( + db=db, + current_user=None, + slicer_filament=self.ORCA_ID, + slicer_filament_name=None, + material="PLA", + ) + assert idx == "" + assert sid == "" + + @pytest.mark.asyncio + async def test_a_caller_without_the_permission_skips_the_lookup(self): + db = MagicMock() + user = MagicMock() + user.has_permission = MagicMock(return_value=False) + with patch( + "backend.app.api.routes.orca_cloud._build_authenticated_service", + AsyncMock(side_effect=AssertionError("must not be called")), + ): + idx, _sid, _brand, _type = await resolve_slicer_filament( + db=db, + current_user=user, + slicer_filament=self.ORCA_ID, + slicer_filament_name=None, + material="PLA", + ) + assert idx == "" + + @pytest.mark.asyncio + async def test_a_uuid_is_refused_as_tray_info_idx_by_the_closing_guard(self): + """Belt and braces: a profile whose content names itself by UUID still + does not put one in the field.""" + db = MagicMock() + svc = self._svc({"id": self.ORCA_ID, "name": "Odd", "content": {"filament_id": self.ORCA_ID}}) + with patch( + "backend.app.api.routes.orca_cloud._build_authenticated_service", + AsyncMock(return_value=svc), + ): + idx, sid, _brand, _type = await resolve_slicer_filament( + db=db, + current_user=None, + slicer_filament=self.ORCA_ID, + slicer_filament_name=None, + material="PLA", + ) + assert idx == "" + assert sid == "" diff --git a/frontend/src/__tests__/components/ConfigureAmsSlotModal.test.tsx b/frontend/src/__tests__/components/ConfigureAmsSlotModal.test.tsx index ac896a3c7..c472d91f5 100644 --- a/frontend/src/__tests__/components/ConfigureAmsSlotModal.test.tsx +++ b/frontend/src/__tests__/components/ConfigureAmsSlotModal.test.tsx @@ -24,6 +24,8 @@ vi.mock('../../api/client', () => ({ updateSettings: vi.fn().mockResolvedValue({}), getLocalPresets: vi.fn(), getBuiltinFilaments: vi.fn(), + orcaCloudListProfiles: vi.fn(), + orcaCloudGetProfile: vi.fn(), searchColors: vi.fn(), getColorCatalog: vi.fn(), resetAmsSlot: vi.fn(), @@ -85,6 +87,9 @@ describe('ConfigureAmsSlotModal', () => { (api.configureAmsSlot as ReturnType).mockResolvedValue({ success: true }); (api.saveSlotPreset as ReturnType).mockResolvedValue({ success: true }); (api.getLocalPresets as ReturnType).mockResolvedValue({ filament: [] }); + (api.orcaCloudListProfiles as ReturnType).mockResolvedValue({ + filament: [], printer: [], process: [], + }); (api.getBuiltinFilaments as ReturnType).mockResolvedValue([]); (api.searchColors as ReturnType).mockResolvedValue([]); (api.getColorCatalog as ReturnType).mockResolvedValue([]); @@ -206,7 +211,7 @@ describe('ConfigureAmsSlotModal', () => { expect(colorInput).toHaveValue('Red'); }); - it('sends PFUS setting_id as tray_info_idx when cloud detail has filament_id: null (#1053)', async () => { + it('sends no tray_info_idx when cloud detail has filament_id: null (#3003)', async () => { // Cloud returns a user preset that inherits from a generic Bambu base and // has no distinct filament_id of its own — this is how Bambu Cloud responds // for custom presets built on top of "Generic ABS @BBL H2D" etc. @@ -233,9 +238,118 @@ describe('ConfigureAmsSlotModal', () => { }); const payload = (api.configureAmsSlot as ReturnType).mock.calls[0][3]; - // Before the fix, this collapsed to 'GFB99' (Generic ABS's filament_id), - // which made OrcaSlicer/BambuStudio Sync Filaments resolve to "Generic ABS". - expect(payload.tray_info_idx).toBe('PFUScd84f663d2c2ef'); + // #1053 sent the PFUS here instead, to stop the slot collapsing to + // "Generic ABS" in the slicer. The A1 capture in #3003 showed that does not + // work: tray_info_idx is 8 characters on the printer, so an 18-character + // PFUS is stored truncated (PFUScd84 here) and acknowledged as a success. + // The slot then resolves to nothing — "Generic" anyway, plus a calibration + // table keyed by an id that does not exist. Sending nothing lets the + // backend pick a filament id the printer can actually hold; setting_id + // still carries the preset. + expect(payload.tray_info_idx).toBe(''); + expect(payload.setting_id).toBe('PFUScd84f663d2c2ef'); + }); + + it('uses an Orca Cloud profile\'s own filament_id instead of a generic (#3003)', async () => { + // Orca profile ids are UUIDs the printer cannot hold, so this branch used + // to skip the lookup entirely and send a generic — every Orca custom + // filament reached the slicer as "Generic PLA". The profile's slicer JSON + // carries a filament_id of exactly the storable shape; use it. + const ORCA_ID = '3f2a9c1e-4b7d-4a02-9f61-8c5e2d1a7b30'; + (api.orcaCloudListProfiles as ReturnType).mockResolvedValue({ + filament: [{ setting_id: ORCA_ID, name: 'Overture Matte PLA @Orca', type: 'filament', is_custom: true }], + printer: [], + process: [], + }); + (api.orcaCloudGetProfile as ReturnType).mockResolvedValue({ + setting_id: ORCA_ID, + name: 'Overture Matte PLA @Orca', + type: 'filament', + setting: { filament_id: 'P56e1be0', filament_type: ['PLA'] }, + }); + + const slotInfo = { ...defaultProps.slotInfo, savedPresetId: ORCA_ID }; + render(); + + await waitFor(() => { + expect(screen.getByText('Overture Matte PLA @Orca')).toBeInTheDocument(); + }); + + fireEvent.click(screen.getByRole('button', { name: /Configure Slot/i })); + + await waitFor(() => { + expect(api.configureAmsSlot).toHaveBeenCalled(); + }); + + const payload = (api.configureAmsSlot as ReturnType).mock.calls[0][3]; + expect(payload.tray_info_idx).toBe('P56e1be0'); + // The UUID is what the slicer cannot resolve; it goes in neither field. + expect(payload.setting_id).toBe(''); + }); + + it('falls back to a generic when an Orca profile has no filament_id (#3003)', async () => { + const ORCA_ID = '3f2a9c1e-4b7d-4a02-9f61-8c5e2d1a7b30'; + (api.orcaCloudListProfiles as ReturnType).mockResolvedValue({ + filament: [{ setting_id: ORCA_ID, name: 'Homebrew PLA @Orca', type: 'filament', is_custom: true }], + printer: [], + process: [], + }); + (api.orcaCloudGetProfile as ReturnType).mockResolvedValue({ + setting_id: ORCA_ID, + name: 'Homebrew PLA @Orca', + type: 'filament', + setting: {}, + }); + + const slotInfo = { ...defaultProps.slotInfo, savedPresetId: ORCA_ID }; + render(); + + await waitFor(() => { + expect(screen.getByText('Homebrew PLA @Orca')).toBeInTheDocument(); + }); + + fireEvent.click(screen.getByRole('button', { name: /Configure Slot/i })); + + await waitFor(() => { + expect(api.configureAmsSlot).toHaveBeenCalled(); + }); + + const payload = (api.configureAmsSlot as ReturnType).mock.calls[0][3]; + expect(payload.tray_info_idx).toBe('GFL99'); + expect(payload.setting_id).toBe(''); + }); + + it('uses the filament_id nested under setting when the envelope has none (#3003)', async () => { + // Bambu Cloud returns a custom preset's own filament_id on the envelope for + // some presets and inside the preset JSON for others. Only the envelope was + // read, so presets of the second shape reached the slot as their inherited + // base — the "Bambu profile instead of my profile" half of #3003. + (api.getCloudSettingDetail as ReturnType).mockResolvedValue({ + filament_id: null, + base_id: 'GFSB99_07', + name: '# Overture Matte PLA @BBL H2D', + setting: { filament_id: 'P4d64437' }, + }); + + const slotInfo = { + ...defaultProps.slotInfo, + savedPresetId: 'PFUScd84f663d2c2ef', + }; + render(); + + await waitFor(() => { + expect(screen.getByText('# Overture Matte PLA @BBL H2D')).toBeInTheDocument(); + }); + + fireEvent.click(screen.getByRole('button', { name: /Configure Slot/i })); + + await waitFor(() => { + expect(api.configureAmsSlot).toHaveBeenCalled(); + }); + + const payload = (api.configureAmsSlot as ReturnType).mock.calls[0][3]; + // 8 characters, so the printer stores it whole and the slicer matches it. + expect(payload.tray_info_idx).toBe('P4d64437'); expect(payload.setting_id).toBe('PFUScd84f663d2c2ef'); }); @@ -293,9 +407,11 @@ describe('ConfigureAmsSlotModal', () => { expect(api.getCloudSettingDetail).not.toHaveBeenCalled(); }); - it('keeps default PFUS tray_info_idx when cloud detail fetch fails', async () => { - // Network/5xx from /cloud/settings/{id} must not abort the configure flow - // nor leave tray_info_idx empty — we fall back to the setting_id default. + it('sends no tray_info_idx when the cloud detail fetch fails (#3003)', async () => { + // Network/5xx from /cloud/settings/{id} must not abort the configure flow. + // It leaves no filament_id to send, and the PFUS default is not a usable + // stand-in (see the filament_id: null case above), so the field goes out + // empty and the backend resolves it. (api.getCloudSettingDetail as ReturnType).mockRejectedValue( new Error('cloud unreachable') ); @@ -317,7 +433,7 @@ describe('ConfigureAmsSlotModal', () => { }); const payload = (api.configureAmsSlot as ReturnType).mock.calls[0][3]; - expect(payload.tray_info_idx).toBe('PFUScd84f663d2c2ef'); + expect(payload.tray_info_idx).toBe(''); expect(payload.setting_id).toBe('PFUScd84f663d2c2ef'); }); diff --git a/frontend/src/components/ConfigureAmsSlotModal.tsx b/frontend/src/components/ConfigureAmsSlotModal.tsx index beaae917c..379137dd8 100644 --- a/frontend/src/components/ConfigureAmsSlotModal.tsx +++ b/frontend/src/components/ConfigureAmsSlotModal.tsx @@ -469,16 +469,40 @@ export function ConfigureAmsSlotModal({ || ''; settingId = ''; } else if (isOrca) { - // Orca Cloud presets have a UUID setting_id that Bambu printers can't - // resolve; treat them like local imports — derive a generic tray_info - // _idx from the parsed material, leave settingId empty so the slicer - // doesn't get a foreign cloud ID it can't look up. - const material = (MATERIAL_TYPES.includes(parsedMat) ? parsedMat : parsed.material || '').toUpperCase(); - trayInfoIdx = GENERIC_IDS[material] - || GENERIC_IDS[material.replace(/[-\s]?CF$/, '')] - || GENERIC_IDS[material.replace(/\+$/, '')] - || GENERIC_IDS[material.split(/[-\s]/)[0]] - || ''; + // An Orca Cloud profile's setting_id is a UUID the printer cannot hold, + // so this used to skip straight to a generic — which meant every Orca + // custom filament reached the slicer as "Generic ", without + // ever asking whether the profile had a usable id (#3003). + // + // It usually does. The profile's slicer JSON carries its own + // filament_id, the same 8-character "P…" the printer stores for a + // Bambu custom preset, and OrcaProfileDetail deliberately exposes that + // JSON under `setting` in the shape SlicerSettingDetail uses. So the + // lookup is the same one the Bambu Cloud branch does below. + // + // settingId stays empty either way: it is the UUID that is foreign to + // the slicer, not the filament id. + let orcaFilamentId = ''; + try { + const orcaDetail = await api.orcaCloudGetProfile(orcaSettingId); + const fromProfile = orcaDetail.setting?.filament_id; + if (typeof fromProfile === 'string' && fromProfile) { + orcaFilamentId = fromProfile; + } + } catch (e) { + console.warn('Failed to fetch Orca Cloud profile for filament_id:', e); + } + trayInfoIdx = orcaFilamentId; + if (!trayInfoIdx) { + // No id of its own — fall back to the generic for the material, the + // same last resort every other source ends at. + const material = (MATERIAL_TYPES.includes(parsedMat) ? parsedMat : parsed.material || '').toUpperCase(); + trayInfoIdx = GENERIC_IDS[material] + || GENERIC_IDS[material.replace(/[-\s]?CF$/, '')] + || GENERIC_IDS[material.replace(/\+$/, '')] + || GENERIC_IDS[material.split(/[-\s]/)[0]] + || ''; + } settingId = ''; } else if (isBuiltin) { // Built-in presets use the filament_id directly as tray_info_idx @@ -495,13 +519,38 @@ export function ConfigureAmsSlotModal({ if (!selectedPresetId.startsWith('GFS')) { try { const detail = await api.getCloudSettingDetail(selectedPresetId); - if (detail.filament_id) { - trayInfoIdx = detail.filament_id; + // The preset's own filament_id is what puts it in the slot as + // itself — the printer stores that id and the slicer matches its + // presets against it. Bambu Cloud returns it on the envelope for + // some presets and inside the preset JSON under `setting` for + // others; looking only at the envelope is how a custom preset + // silently became its inherited base profile (#3003). + const nested = detail.setting?.filament_id; + const ownFilamentId = detail.filament_id || (typeof nested === 'string' ? nested : ''); + if (ownFilamentId) { + trayInfoIdx = ownFilamentId; } } catch (e) { console.warn('Failed to fetch preset detail for filament_id:', e); } } + + // Last resort: neither place had one, so trayInfoIdx is still the + // cloud setting_id — and sending one is worse than sending nothing + // (#3003). tray_info_idx is 8 characters on the printer; an + // 18-character PFUS is stored truncated and acknowledged as a success, + // so the slot ends up holding an id that resolves nowhere — the slicer + // shows "Generic", and the calibration table, keyed by this field, + // loses the slot too. Blank means the backend picks the slot's + // existing filament id or a generic for the material; settingId still + // carries the preset. + if (/^(PFUS|PFSP|PFCN)/.test(trayInfoIdx)) { + console.warn( + `Cloud preset ${selectedPresetId} carries no filament_id in either place; ` + + 'sending no tray_info_idx so the printer keeps a resolvable one.' + ); + trayInfoIdx = ''; + } } // Default temp range — use local preset core fields if available diff --git a/static/assets/index-DQoG4yeu.js b/static/assets/index-BMnY4ID9.js similarity index 99% rename from static/assets/index-DQoG4yeu.js rename to static/assets/index-BMnY4ID9.js index ef518eddc..d715841a5 100644 --- a/static/assets/index-DQoG4yeu.js +++ b/static/assets/index-BMnY4ID9.js @@ -4180,7 +4180,7 @@ void main() { border-l-[5px] border-l-transparent border-r-[5px] border-r-transparent border-t-[5px] border-t-bambu-dark-tertiary - `})]}),document.body)]})}function DH({isOpen:e,onClose:t,tagUid:n,trayUuid:r,printerId:i,amsId:a,trayId:o}){let{t:s}=U(),c=oo(),{showToast:l}=Bd(),[u,d]=(0,y.useState)(``),f=r||n,{data:p,isLoading:m}=K({queryKey:[`unlinked-spools`],queryFn:Z.getUnlinkedSpools,enabled:e}),h=(0,y.useMemo)(()=>p?p.filter(e=>{if(!u)return!0;let t=u.toLowerCase();return e.filament_name&&e.filament_name.toLowerCase().includes(t)||e.filament_vendor&&e.filament_vendor.toLowerCase().includes(t)||e.filament_material&&e.filament_material.toLowerCase().includes(t)||String(e.id).includes(t)}):[],[p,u]),g=q({mutationFn:e=>Z.linkSpool(e,{spoolTag:f,printerId:i,amsId:a,trayId:o}),onSuccess:()=>{c.invalidateQueries({queryKey:[`unlinked-spools`]}),c.invalidateQueries({queryKey:[`linked-spools`]}),c.invalidateQueries({queryKey:[`spoolman-slot-assignments`]}),l(s(`spoolman.linkSuccess`),`success`),t()},onError:e=>{l(e.message||s(`spoolman.linkFailed`),`error`)}});return e?(0,G.jsxs)(`div`,{className:`fixed inset-0 z-50 flex items-center justify-center`,children:[(0,G.jsx)(`div`,{className:`absolute inset-0 bg-black/60 backdrop-blur-sm`,onClick:t}),(0,G.jsxs)(`div`,{className:`relative bg-bambu-dark-secondary rounded-xl shadow-xl w-full max-w-md mx-4 max-h-[80vh] flex flex-col border border-bambu-dark-tertiary`,children:[(0,G.jsxs)(`div`,{className:`flex items-center justify-between p-4 border-b border-white/10`,children:[(0,G.jsxs)(`div`,{children:[(0,G.jsxs)(`h3`,{className:`text-lg font-semibold text-white flex items-center gap-2`,children:[(0,G.jsx)(Yc,{className:`w-5 h-5 text-bambu-green`}),s(`spoolman.selectSpool`)]}),(0,G.jsxs)(`p`,{className:`text-xs text-bambu-gray mt-1`,children:[`AMS `,a,` T`,o,` · Printer #`,i]})]}),(0,G.jsx)(`button`,{onClick:t,className:`p-1 text-bambu-gray hover:text-white rounded transition-colors`,children:(0,G.jsx)(ed,{className:`w-5 h-5`})})]}),(0,G.jsxs)(`div`,{className:`p-4 border-b border-white/10`,children:[(0,G.jsxs)(`div`,{className:`relative`,children:[(0,G.jsx)(Xl,{className:`absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray`}),(0,G.jsx)(`input`,{type:`text`,value:u,onChange:e=>d(e.target.value),placeholder:s(`inventory.searchSpools`),className:`w-full pl-9 pr-3 py-2 bg-bambu-dark rounded-lg border border-white/10 text-white text-sm placeholder:text-bambu-gray focus:outline-none focus:border-bambu-green`})]}),(r||n)&&(0,G.jsxs)(`p`,{className:`text-xs text-bambu-gray mt-2 font-mono truncate`,title:r||n,children:[`Tag: `,r||n]})]}),(0,G.jsx)(`div`,{className:`flex-1 overflow-y-auto p-2 min-h-0`,children:m?(0,G.jsx)(`div`,{className:`flex justify-center py-8`,children:(0,G.jsx)(Y,{className:`w-6 h-6 animate-spin text-bambu-green`})}):h.length===0?(0,G.jsx)(`p`,{className:`text-center text-bambu-gray py-8 text-sm`,children:s(`inventory.noSpoolsMatch`)}):h.map(e=>(0,G.jsxs)(`button`,{onClick:()=>g.mutate(e.id),disabled:g.isPending||!f,className:`w-full flex items-center gap-3 p-3 rounded-lg hover:bg-white/5 transition-colors text-left`,children:[(0,G.jsx)(`span`,{className:`w-6 h-6 rounded-full border border-black/20 flex-shrink-0`,style:Tf(e.filament_color_hex)}),(0,G.jsxs)(`div`,{className:`flex-1 min-w-0`,children:[(0,G.jsx)(`div`,{className:`text-sm text-white font-medium truncate`,children:e.filament_name||s(`spoolman.spoolId`)}),(0,G.jsxs)(`div`,{className:`text-xs text-bambu-gray truncate`,children:[e.filament_vendor?`${e.filament_vendor} · `:``,e.filament_material||`Unknown`,` · #`,e.id]})]}),(0,G.jsx)(`span`,{className:`text-xs text-bambu-gray`,children:e.remaining_weight==null?`—`:`${Math.round(e.remaining_weight)}g`})]},e.id))}),(0,G.jsx)(`div`,{className:`p-4 border-t border-white/10 flex justify-end`,children:(0,G.jsx)(Q,{variant:`ghost`,onClick:t,children:s(`inventory.cancel`)||`Cancel`})})]})]}):null}function YOe(e,t){if(!t)return!0;let n=t.toLowerCase();return String(e.id).includes(n)||e.material.toLowerCase().includes(n)||(e.brand?.toLowerCase().includes(n)??!1)||(e.color_name?.toLowerCase().includes(n)??!1)||(e.subtype?.toLowerCase().includes(n)??!1)||(e.note?.toLowerCase().includes(n)??!1)||(e.slicer_filament_name?.toLowerCase().includes(n)??!1)||(e.storage_location?.toLowerCase().includes(n)??!1)}function OH(e,t){return t?e.filter(e=>YOe(e,t)):e}function kH({isOpen:e,onClose:t,printerId:n,amsId:r,trayId:i,trayInfo:a,spoolmanEnabled:o}){let{t:s}=U(),c=oo(),{showToast:l}=Bd(),[u,d]=(0,y.useState)(!1),[f,p]=(0,y.useState)(null),[m,h]=(0,y.useState)(null);(0,y.useEffect)(()=>{p(null),h(null)},[u]);let[g,_]=(0,y.useState)(``),[v,b]=(0,y.useState)(null),[x,S]=(0,y.useState)(!1),[C,w]=(0,y.useState)(null);(0,y.useEffect)(()=>{e&&d(!1)},[e]);let{data:T,isLoading:E}=K({queryKey:[`inventory-spools`,`assign-modal`],queryFn:()=>Z.getSpools(!0),enabled:e&&!o}),{data:D}=K({queryKey:[`spool-assignments`],queryFn:()=>Z.getAssignments(),enabled:e}),{data:O}=K({queryKey:[`settings`],queryFn:()=>Z.getSettings(),enabled:e}),{data:k,isLoading:A}=K({queryKey:[`spoolman-inventory-spools`,`assign-modal`],queryFn:()=>Z.getSpoolmanInventorySpools(!1),enabled:e&&!!o}),{data:j}=K({queryKey:[`spoolman-slot-assignments-all`],queryFn:()=>Z.getSpoolmanSlotAssignments(),enabled:e&&!!o}),M=(0,y.useMemo)(()=>j?new Set(j.filter(e=>!(e.printer_id===n&&e.ams_id===r&&e.tray_id===i)).map(e=>e.spoolman_spool_id)):new Set,[j,n,r,i]),N=()=>{Z.refreshPrinterStatus(n).catch(()=>{}),c.invalidateQueries({queryKey:[`printerStatus`,n]})},P=q({mutationFn:e=>Z.assignSpool({spool_id:e,printer_id:n,ams_id:r,tray_id:i}),onSuccess:e=>{c.setQueryData([`spool-assignments`],t=>{let a=(t||[]).filter(e=>!(e.printer_id===n&&e.ams_id===r&&e.tray_id===i));return a.push(e),a}),c.invalidateQueries({queryKey:[`spool-assignments`]}),N(),l(s(e.pending_config?`inventory.assignPendingInsert`:`inventory.assignSuccess`),`success`),S(!1),b(null),w(null),t()},onError:e=>{l(`${s(`inventory.assignFailed`)}: ${e.message}`,`error`)}}),F=q({mutationFn:e=>Z.assignSpoolmanSlot({spoolman_spool_id:e,printer_id:n,ams_id:r,tray_id:i}),onSuccess:()=>{c.invalidateQueries({queryKey:[`spoolman-inventory-spools`]}),c.invalidateQueries({queryKey:[`spoolman-slot-assignments`]}),N(),l(s(`inventory.assignSuccess`),`success`),t()},onError:e=>{l(`${s(`inventory.assignFailed`)}: ${e.message}`,`error`)}}),I=e=>(e??``).trim().toUpperCase(),L=(e,t)=>{let n=I(e),r=I(t);return!n||!r?`none`:n===r?`exact`:r.includes(n)||n.includes(r)?`partial`:`none`},R=e=>e.split(`@`)[0].trim(),z=(e,t)=>{let n=R(I(e)),r=R(I(t));return!n||!r?!1:n===r};if(!e)return null;let B=new Set((D||[]).filter(e=>!(e.printer_id===n&&e.ams_id===r&&e.tray_id===i)).map(e=>e.spool_id)),V=T?.filter(e=>!e.archived_at&&(u||!B.has(e.id))),ee=V;if(!u){let e=R(I(a?.profile)),t=I(a?.material||a?.type);(e||t)&&(ee=ee?.filter(n=>{let r=R(I(n.slicer_filament_name||n.slicer_filament)),i=I(n.material);return e&&r&&r===e?!0:t&&i?i===t||t.includes(i)||i.includes(t):!r&&!i}))}g&&ee&&(ee=OH(ee,g));let te=()=>{if(m!==null){F.mutate(m);return}if(!f)return;let e=T?.find(e=>e.id===f);if(!e){l(s(`inventory.assignFailed`),`error`);return}if(!O?.disable_filament_warnings&&a){let t=a.material||a.type,n=L(e.material,t),r=e.slicer_filament_name||e.slicer_filament,i=a.profile||a.type,o=z(r,i);if(n!==`exact`){let a;a=n===`none`&&!o?`material_profile`:n===`partial`&&!o?`partial_profile`:n===`none`?`material`:`partial`,b(f),w({type:a,spoolMaterial:e.material||``,trayMaterial:t||``,spoolProfile:r||void 0,trayProfile:i||void 0}),S(!0);return}}P.mutate(f)},ne=()=>{v&&(P.mutate(v),S(!1),b(null))};return(0,G.jsxs)(G.Fragment,{children:[(0,G.jsxs)(`div`,{className:`fixed inset-0 z-[100] flex items-start sm:items-center justify-center p-4 overflow-y-auto`,children:[(0,G.jsx)(`div`,{className:`absolute inset-0 bg-black/60 backdrop-blur-sm`,onClick:t}),(0,G.jsxs)(`div`,{className:`relative w-full max-w-2xl bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl max-h-[90vh] overflow-hidden flex flex-col my-auto`,children:[(0,G.jsxs)(`div`,{className:`flex items-center justify-between p-4 border-b border-bambu-dark-tertiary`,children:[(0,G.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,G.jsx)(xl,{className:`w-5 h-5 text-bambu-green`}),(0,G.jsx)(`h2`,{className:`text-lg font-semibold text-white`,children:s(`inventory.assignSpool`)})]}),(0,G.jsx)(`button`,{onClick:t,className:`p-1 text-bambu-gray hover:text-white rounded transition-colors`,children:(0,G.jsx)(ed,{className:`w-5 h-5`})})]}),(0,G.jsxs)(`div`,{className:`p-4 space-y-4 overflow-y-auto`,children:[a&&(0,G.jsxs)(`div`,{className:`p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary`,children:[(0,G.jsxs)(`p`,{className:`text-xs text-bambu-gray mb-1`,children:[s(`inventory.selectSpool`),`:`]}),(0,G.jsxs)(`div`,{className:`flex items-center gap-2`,children:[a.color&&(0,G.jsx)(`span`,{className:`w-4 h-4 rounded-full border border-black/20`,style:Tf(a.color)}),(0,G.jsx)(`span`,{className:`text-white font-medium`,children:a.type||s(`ams.emptySlot`)}),(0,G.jsxs)(`span`,{className:`text-bambu-gray`,children:[`(`,a.location,`)`]})]})]}),(0,G.jsxs)(`div`,{className:`relative`,children:[(0,G.jsx)(Xl,{className:`absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray`}),(0,G.jsx)(`input`,{type:`text`,value:g,onChange:e=>_(e.target.value),placeholder:s(`inventory.searchSpools`),className:`w-full pl-9 pr-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray focus:outline-none focus:border-bambu-green`})]}),(0,G.jsxs)(`div`,{className:`space-y-3`,children:[!o&&(E?(0,G.jsx)(`div`,{className:`flex justify-center py-8`,children:(0,G.jsx)(Y,{className:`w-6 h-6 text-bambu-green animate-spin`})}):ee&&ee.length>0?(0,G.jsx)(`div`,{className:`max-h-96 overflow-y-auto grid grid-cols-2 sm:grid-cols-3 gap-2`,children:ee.map(e=>(0,G.jsxs)(`button`,{onClick:()=>{p(e.id),h(null)},title:e.note||void 0,className:`p-2.5 rounded-lg border text-left transition-colors ${f===e.id?`bg-bambu-green/20 border-bambu-green`:`bg-bambu-dark border-bambu-dark-tertiary hover:border-bambu-gray`}`,children:[(0,G.jsxs)(`p`,{className:`text-white text-sm font-medium truncate`,children:[e.brand?`${e.brand} `:``,e.material,e.subtype?` ${e.subtype}`:``]}),(0,G.jsxs)(`div`,{className:`flex items-center gap-1.5 mt-1`,children:[e.rgba&&(0,G.jsx)(`span`,{className:`w-3 h-3 rounded-full border border-black/20 flex-shrink-0`,style:Tf(e.rgba)}),(0,G.jsx)(`span`,{className:`text-xs text-bambu-gray truncate`,children:e.color_name||``})]}),e.label_weight&&(0,G.jsxs)(`p`,{className:`text-xs text-bambu-gray mt-1`,children:[Math.max(0,Math.round(e.label_weight-e.weight_used)),` / `,e.label_weight,`g`]}),e.note&&(0,G.jsx)(`p`,{className:`text-[10px] text-bambu-gray/70 mt-1 truncate`,title:e.note,children:e.note})]},e.id))}):V&&V.length===0?(0,G.jsxs)(`div`,{className:`text-center py-8 text-bambu-gray`,children:[(0,G.jsx)(`p`,{children:s(`inventory.noAvailableSpools`)}),T&&(0,G.jsxs)(`p`,{className:`text-[10px] mt-2 opacity-60`,children:[T.length,` fetched · `,T.filter(e=>e.archived_at).length,` archived ·`,` `,T.filter(e=>B.has(e.id)).length,` assigned to other slots`]})]}):(0,G.jsxs)(`div`,{className:`text-center py-8 text-bambu-gray`,children:[(0,G.jsx)(`p`,{children:s(`inventory.noSpoolsMatch`)}),V&&(0,G.jsxs)(`p`,{className:`text-[10px] mt-2 opacity-60`,children:[V.length,` unassigned spools — `,V.length-(ee?.length??0),` filtered by tray match. Try "Show all spools".`]})]})),o&&(0,G.jsx)(G.Fragment,{children:A?(0,G.jsx)(`div`,{className:`flex justify-center py-4`,children:(0,G.jsx)(Y,{className:`w-5 h-5 text-bambu-green animate-spin`})}):k&&k.filter(e=>!e.archived_at&&!M.has(e.id)).length>0?(0,G.jsxs)(G.Fragment,{children:[(0,G.jsx)(`p`,{className:`text-xs font-medium text-bambu-gray uppercase tracking-wide pt-1`,children:s(`inventory.spoolmanSpools`)}),(0,G.jsx)(`div`,{className:`max-h-64 overflow-y-auto grid grid-cols-2 sm:grid-cols-3 gap-2`,children:OH(k.filter(e=>!e.archived_at&&!M.has(e.id)),g).map(e=>(0,G.jsxs)(`button`,{onClick:()=>{h(e.id),p(null)},title:e.note||void 0,className:`p-2.5 rounded-lg border text-left transition-colors ${m===e.id?`bg-bambu-green/20 border-bambu-green`:`bg-bambu-dark border-bambu-dark-tertiary hover:border-bambu-gray`}`,children:[(0,G.jsxs)(`p`,{className:`text-white text-sm font-medium truncate`,children:[e.brand?`${e.brand} `:``,e.material,e.subtype?` ${e.subtype}`:``]}),(0,G.jsxs)(`div`,{className:`flex items-center gap-1.5 mt-1`,children:[e.rgba&&(0,G.jsx)(`span`,{className:`w-3 h-3 rounded-full border border-black/20 flex-shrink-0`,style:Tf(e.rgba)}),(0,G.jsx)(`span`,{className:`text-xs text-bambu-gray truncate`,children:e.color_name||``})]}),e.label_weight&&(0,G.jsxs)(`p`,{className:`text-xs text-bambu-gray mt-1`,children:[Math.max(0,Math.round(e.label_weight-e.weight_used)),` / `,e.label_weight,`g`]}),e.note&&(0,G.jsx)(`p`,{className:`text-[10px] text-bambu-gray/70 mt-1 truncate`,title:e.note,children:e.note})]},`spoolman-${e.id}`))})]}):null})]})]}),(0,G.jsxs)(`div`,{className:`flex justify-between items-center p-4 border-t border-bambu-dark-tertiary`,children:[(0,G.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,G.jsx)(`input`,{id:`disable-filtering-toggle`,type:`checkbox`,checked:u,onChange:()=>d(e=>!e),className:`accent-bambu-green w-4 h-4 rounded focus:ring-0 border-bambu-dark-tertiary`}),(0,G.jsx)(`label`,{htmlFor:`disable-filtering-toggle`,className:`text-xs text-bambu-gray select-none cursor-pointer`,children:s(`inventory.showAllSpools`)})]}),(0,G.jsxs)(`div`,{className:`flex gap-2`,children:[(0,G.jsx)(Q,{variant:`secondary`,onClick:t,children:s(`common.cancel`)}),(0,G.jsx)(Q,{onClick:te,disabled:!f&&m===null||P.isPending||F.isPending,children:P.isPending||F.isPending?(0,G.jsxs)(G.Fragment,{children:[(0,G.jsx)(Y,{className:`w-4 h-4 animate-spin`}),s(`inventory.assigning`)]}):(0,G.jsxs)(G.Fragment,{children:[(0,G.jsx)(xl,{className:`w-4 h-4`}),s(`inventory.assignSpool`)]})})]})]}),P.isError&&(0,G.jsx)(`div`,{className:`mx-4 mb-4 p-2 bg-red-100 dark:bg-red-500/20 border border-red-300 dark:border-red-500/50 rounded text-sm text-red-700 dark:text-red-400`,children:P.error.message})]})]}),x&&a&&f&&C&&(()=>{let e=``;return C.type===`material`?e=s(`inventory.assignMismatchMessage`,{spoolMaterial:C.spoolMaterial,trayMaterial:C.trayMaterial,location:a.location}):C.type===`partial`?e=s(`inventory.assignPartialMismatchMessage`,{spoolMaterial:C.spoolMaterial,trayMaterial:C.trayMaterial,location:a.location}):C.type===`material_profile`?e=`${s(`inventory.assignMismatchMessage`,{spoolMaterial:C.spoolMaterial,trayMaterial:C.trayMaterial,location:a.location})}\n\n${s(`inventory.assignProfileMismatchMessage`,{spoolProfile:C.spoolProfile||s(`common.unknown`),trayProfile:C.trayProfile||s(`common.unknown`),location:a.location})}`:C.type===`partial_profile`&&(e=`${s(`inventory.assignPartialMismatchMessage`,{spoolMaterial:C.spoolMaterial,trayMaterial:C.trayMaterial,location:a.location})}\n\n${s(`inventory.assignProfileMismatchMessage`,{spoolProfile:C.spoolProfile||s(`common.unknown`),trayProfile:C.trayProfile||s(`common.unknown`),location:a.location})}`),e=`${e}\n\n${s(`inventory.assignReconfigureNote`)}`,(0,G.jsx)(Qd,{title:s(`inventory.assignMismatchTitle`),message:e,confirmText:s(`inventory.assignMismatchConfirm`),variant:`warning`,overlayZIndex:`z-[110]`,isLoading:P.isPending,onConfirm:ne,onCancel:()=>{P.isPending||(S(!1),b(null),w(null))}})})()]})}var XOe={bambuModelByShortCode:{}},AH={"A1 MINI":[`A1M`],"H2D PRO":[`H2DP`]};function jH(e,t){let n=e.toUpperCase(),r=t.toUpperCase();if(n===r)return!0;let i=AH[r];if(i&&i.includes(n))return!0;let a=AH[n];return!!(a&&a.includes(r))}function ZOe(e){let t={};for(let[n,r]of Object.entries(e))r in t||(t[r]=n.replace(/^Bambu Lab\s+/,``));return t}function MH(e={}){return{bambuModelByShortCode:ZOe(e)}}function NH(e){return e.replace(/\s+/g,``).toLowerCase()}function PH(e){return e.replace(/^#\s*/,``).trim()}var QOe=`0.4`;function FH(e){let t=e.match(/^(.*?)\s+([\d.]+)\s*nozzle\s*$/i);return t?{stripped:t[1].trim(),nozzle:t[2]}:{stripped:e.trim(),nozzle:null}}function $Oe(e){let t=e.indexOf(`@BBL `);if(t<0)return null;let{stripped:n,nozzle:r}=FH(e.slice(t+5).trim());return n?{token:n,nozzle:r}:null}function IH(e){let t=PH(e).match(/^Bambu Lab\s+(.+)$/i);if(!t)return null;let{stripped:n,nozzle:r}=FH(t[1]);return n?{model:n,nozzle:r}:null}function eke(e){return e.replace(/\s*\([^)]*\)\s*$/,``).trim()}var tke=.1,nke=2;function LH(e,t){let n=Number.parseFloat(e),r=Number.parseFloat(t);return Number.isNaN(n)||Number.isNaN(r)?!1:n===r}function rke(e){let t=eke(e),n=$Oe(t);if(n)return n;let r=t.lastIndexOf(`@`);if(r<0)return null;let i=t.slice(r+1).trim(),a=IH(i);if(a)return{token:a.model,nozzle:a.nozzle};let o=i.match(/^([\d.]+)\s*(?:mm)?\s*(?:nozzle)?$/i);if(o){let e=Number.parseFloat(o[1]);if(!Number.isNaN(e)&&e>=tke&&e<=nke)return{token:null,nozzle:o[1]}}return null}function ike(e,t,n){let r=rke(e);if(!r)return`unknown`;let i=IH(t);if(!i)return`unknown`;if(r.token===null)return i.nozzle!==null&&r.nozzle!==null&&!LH(r.nozzle,i.nozzle)?`mismatch`:`unknown`;let a=n[r.token]??r.token;return NH(i.model)!==NH(a)&&!jH(r.token,i.model)||i.nozzle!==null&&!LH(r.nozzle??QOe,i.nozzle)?`mismatch`:`match`}function RH(e,t,n,r){if(!n)return`unknown`;let i=e.compatible_printers;if(i&&i.length>0){let e=PH(n);return i.some(t=>PH(t)===e)?`match`:`mismatch`}return ike(e.name,n,r.bambuModelByShortCode)}function ake(e){let t=e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`).replace(/\s+/g,`\\s+`);return RegExp(`\\b${t}\\b`,`i`)}function zH(e,t){let n=e.indexOf(`@`);if(n>=0){let r=e.slice(n+1).trim(),i=r.match(/^BBL\s+(.+?)(?:\s+[\d.]+\s*nozzle)?$/i);if(i)return i[1].trim();let a=r.match(/^Bambu Lab\s+(.+?)(?:\s+[\d.]+\s*nozzle)?$/i);if(a){let e=a[1].trim(),n=`Bambu Lab ${e}`;if(t[n])return t[n];let r=n.toLowerCase();for(let[e,n]of Object.entries(t))if(e.toLowerCase()===r)return n;return e}}let r=[],i=new Set;for(let[e,n]of Object.entries(t)){let t=e.replace(/^Bambu Lab\s+/,``),a=t.toLowerCase();i.has(a)||(r.push({token:t,short:n}),i.add(a));let o=n.toLowerCase();i.has(o)||(r.push({token:n,short:n}),i.add(o))}r.sort((e,t)=>t.token.length-e.token.length);for(let{token:t,short:n}of r)if(ake(t).test(e))return n;return null}var BH=[`PLA`,`PETG`,`ABS`,`TPU`,`ASA`,`PC`,`PA`,`PVA`,`HIPS`,`PA-CF`,`PETG-CF`,`PLA-CF`],VH=[`Bambu`,`PolyLite`,`PolyTerra`,`eSUN`,`Overture`,`Fiberon`,`SUNLU`,`Inland`,`Hatchbox`,`Generic`],HH=`Basic.Matte.Silk.Silk+.Tough.Tough+.HF.High Flow.Engineering.CF.GF.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`.split(`.`),UH=[{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`},{name:`Clear`,hex:`00000000`}],oke=[{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`}],WH=[...UH,...oke],GH=`bambuddy-recent-colors`,KH=[`0.2`,`0.4`,`0.6`,`0.8`];async function qH(e,t){let n=Lp(t),r=Array.from(new Set([...KH,...n])),i=[];for(let t of r)i.push(await Z.getKProfiles(e,t).catch(()=>null));let a=[];for(let e of i)if(e)for(let t of e.profiles)a.push({cali_idx:t.slot_id,filament_id:t.filament_id,setting_id:t.setting_id||``,name:t.name,k_value:parseFloat(t.k_value)||0,n_coef:parseFloat(t.n_coef)||0,extruder_id:t.extruder_id,nozzle_diameter:t.nozzle_diameter,nozzle_id:t.nozzle_id});return a}var ske=[{code:`GFL00`,name:`Bambu PLA Basic`,displayName:`Bambu PLA Basic`,isCustom:!1,allCodes:[`GFL00`],source:`builtin`},{code:`GFL01`,name:`Bambu PLA Matte`,displayName:`Bambu PLA Matte`,isCustom:!1,allCodes:[`GFL01`],source:`builtin`},{code:`GFL05`,name:`Generic PLA`,displayName:`Generic PLA`,isCustom:!1,allCodes:[`GFL05`],source:`builtin`},{code:`GFG00`,name:`Bambu PETG Basic`,displayName:`Bambu PETG Basic`,isCustom:!1,allCodes:[`GFG00`],source:`builtin`},{code:`GFG05`,name:`Generic PETG`,displayName:`Generic PETG`,isCustom:!1,allCodes:[`GFG05`],source:`builtin`},{code:`GFB00`,name:`Bambu ABS Basic`,displayName:`Bambu ABS Basic`,isCustom:!1,allCodes:[`GFB00`],source:`builtin`},{code:`GFB05`,name:`Generic ABS`,displayName:`Generic ABS`,isCustom:!1,allCodes:[`GFB05`],source:`builtin`},{code:`GFA00`,name:`Bambu ASA Basic`,displayName:`Bambu ASA Basic`,isCustom:!1,allCodes:[`GFA00`],source:`builtin`},{code:`GFU00`,name:`Bambu TPU 95A`,displayName:`Bambu TPU 95A`,isCustom:!1,allCodes:[`GFU00`],source:`builtin`},{code:`GFU05`,name:`Generic TPU`,displayName:`Generic TPU`,isCustom:!1,allCodes:[`GFU05`],source:`builtin`},{code:`GFC00`,name:`Bambu PC Basic`,displayName:`Bambu PC Basic`,isCustom:!1,allCodes:[`GFC00`],source:`builtin`},{code:`GFN00`,name:`Bambu PA Basic`,displayName:`Bambu PA Basic`,isCustom:!1,allCodes:[`GFN00`],source:`builtin`},{code:`GFN05`,name:`Generic PA`,displayName:`Generic PA`,isCustom:!1,allCodes:[`GFN05`],source:`builtin`},{code:`GFS00`,name:`Bambu PLA-CF`,displayName:`Bambu PLA-CF`,isCustom:!1,allCodes:[`GFS00`],source:`builtin`},{code:`GFT00`,name:`Bambu PETG-CF`,displayName:`Bambu PETG-CF`,isCustom:!1,allCodes:[`GFT00`],source:`builtin`},{code:`GFNC0`,name:`Bambu PA-CF`,displayName:`Bambu PA-CF`,isCustom:!1,allCodes:[`GFNC0`],source:`builtin`},{code:`GFV00`,name:`Bambu PVA`,displayName:`Bambu PVA`,isCustom:!1,allCodes:[`GFV00`],source:`builtin`}];function JH(e){let t=e.replace(/@.*$/,``).trim();t=t.replace(/\(Custom\)/i,``).trim(),t=t.replace(/^[#*]+\s*/,``).trim();let 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`.split(`.`),r=``,i=-1;for(let e of n){let n=t.toUpperCase().indexOf(e.toUpperCase());if(n!==-1){r=e,i=n;break}}let a=``;i>0&&(a=t.substring(0,i).trim(),a=a.replace(/[-_\s]+$/,``));let o=``;i!==-1&&r&&(o=t.substring(i+r.length).trim(),o=o.replace(/^[-_\s]+/,``));let s=``;for(let e of HH)if(o.toLowerCase().includes(e.toLowerCase())){s=e;break}if(!s&&a)for(let e of HH){let t=RegExp(`\\s+${e}$`,`i`);if(t.test(a)){s=e,a=a.replace(t,``).trim();break}}return{brand:a,material:r,variant:s}}function YH(e,t){let n=new Set(VH);for(let t of e){let{brand:e}=JH(t.name);e&&e.length>1&&n.add(e)}if(t)for(let e of t)if(e.filament_vendor&&e.filament_vendor.length>1)n.add(e.filament_vendor);else{let{brand:t}=JH(e.name);t&&t.length>1&&n.add(t)}return Array.from(n).sort((e,t)=>e.localeCompare(t))}function cke(e){let t=e.filter(e=>e.preset_type===`filament`);return t.length===0?[]:t.map(e=>{let t=String(e.id),n=e.filament_type||t,r=Array.from(new Set([t,n]));return{code:t,name:e.name,displayName:e.name,isCustom:!1,allCodes:r,source:`local`}}).sort((e,t)=>e.displayName.localeCompare(t.displayName))}function XH(e,t,n,r,i){let a=[],o=[],s=new Set;for(let n of e)if(n.is_custom){let e=n.name.toUpperCase();(t.size===0||Array.from(t).some(t=>e.includes(t))||!e.includes(`@`))&&(a.push({code:n.setting_id,name:n.name,displayName:`${n.name} (Custom)`,isCustom:!0,allCodes:[n.setting_id],source:i?.has(n.setting_id)?`orca_cloud`:`cloud`}),s.add(n.setting_id))}else o.push({code:n.setting_id,name:n.name,displayName:n.name,isCustom:!1,allCodes:[n.setting_id],source:i?.has(n.setting_id)?`orca_cloud`:`cloud`}),s.add(n.setting_id);let c=n&&n.length>0?cke(n):[],l=[];if(r&&r.length>0)for(let e of r){let t=e.filament_id.startsWith(`GF`)?`GFS`+e.filament_id.slice(2):e.filament_id;s.has(e.filament_id)||s.has(t)||l.push({code:e.filament_id,name:e.name,displayName:e.name,isCustom:!1,allCodes:[e.filament_id,t],source:`builtin`})}let u=[...a,...o,...c,...l];return u.length===0?ske:u.sort((e,t)=>e.displayName.localeCompare(t.displayName))}function ZH(e,t){if(!e)return;let n=t.find(t=>t.code===e);if(n||=t.find(t=>t.allCodes.includes(e)),!n){let r=e.toLowerCase();n=t.find(e=>e.code.toLowerCase()===r||e.allCodes.some(e=>e.toLowerCase()===r))}return n}function QH(e,t){let n=t.trim();return!n||e.some(e=>e.toLowerCase()===n.toLowerCase())?e:[...e,n].sort((e,t)=>e.localeCompare(t))}function $H(e,t,n){if(!t)return[];let r=n.get(t.toLowerCase());return!r||r.size===0?[]:e.filter(e=>r.has(e.toLowerCase()))}function eU(){try{let e=localStorage.getItem(GH);if(e)return JSON.parse(e)}catch{}return[]}function tU(e,t){let n=[e,...t.filter(t=>t.hex.toUpperCase()!==e.hex.toUpperCase())].slice(0,8);try{localStorage.setItem(GH,JSON.stringify(n))}catch{}return n}function nU(e){if(!e)return``;let t=e.split(`_`)[0];return/^GFS/i.test(t)&&(t=t.slice(0,2)+t.slice(3)),t.toUpperCase()}function lke(e){return!!e&&/^GF[A-Z]99$/i.test(e)}var uke={GFB99:`ABS`,GFC99:`PC`,GFG99:`PETG`,GFL99:`PLA`,GFN99:`PA`,GFP99:`PE`,GFR99:`EVA`,GFS99:`PVA`,GFU99:`TPU`};function dke(e){return e&&uke[e.toUpperCase()]||``}function rU(e){let t=e.trim().toUpperCase();return t===`NYLON`?`PA`:t}function fke(e,t){let n=dke(e);return!!n&&!!t&&rU(n)===rU(t)}function iU(e,t,n){return`${e}:${t}:${n}`}function aU(e,t){return`${e}\u0000${t}`}function pke(e){let[t=``,n=``]=e.split(`\0`);return{model:t,diameter:n}}function oU(e,t){if(!t.material)return!1;let n=nU(t.slicer_filament),r=nU(e.filament_id);if(n&&r&&n===r){if(!lke(r))return!0;let e=t.brand.trim();if((!e||e.toUpperCase()===`GENERIC`)&&fke(r,t.material))return!0}let i=(e.name||``).replace(/^High Flow[_\s]+/i,``).replace(/^Standard[_\s]+/i,``).replace(/^HF[_\s]+/i,``).replace(/^S[_\s]+/i,``).trim(),a=JH(i);return!(a.material.toUpperCase()!==t.material.toUpperCase()||t.brand&&!(a.brand.toLowerCase().includes(t.brand.toLowerCase())||t.brand.toLowerCase().includes(a.brand.toLowerCase()))||t.subtype&&!(a.variant.toLowerCase().includes(t.subtype.toLowerCase())||t.subtype.toLowerCase().includes(a.variant.toLowerCase())||i.toLowerCase().includes(t.subtype.toLowerCase())))}function sU(){let e=(0,y.useRef)(null),t=(0,y.useCallback)(()=>{e.current!==null&&(clearTimeout(e.current),e.current=null)},[]),n=(0,y.useCallback)((n,r)=>{t(),e.current=setTimeout(()=>{e.current=null,n()},r)},[t]);return(0,y.useEffect)(()=>t,[t]),{schedule:n,cancel:t}}function cU(e){let t=e.includes(`_`)?e.split(`_`)[0]:e;return t.startsWith(`GFS`)?`GF`+t.slice(3):(t.startsWith(`PFUS`)||t.startsWith(`PFSP`),t)}var lU=[`PLA`,`PETG`,`PCTG`,`ABS`,`ASA`,`TPU`,`PC`,`PA`,`NYLON`,`PVA`,`HIPS`,`PP`,`PET`];function uU(e){let t=e.replace(/@.+$/,``).trim(),n=t.toUpperCase(),r=n.match(/\bSUPPORT\s+FOR\s+/);if(r){let e=n.slice(r.index+r[0].length);for(let n of lU)if(RegExp(`\\b${n}\\b`).test(e))return{material:n,brand:t.slice(0,r.index).trim(),variant:`Support`}}for(let e of lU){let r=RegExp(`\\b${e}\\b`,`i`);if(r.test(n)){let n=t.split(r);return{material:e,brand:n[0]?.trim()||``,variant:n[1]?.trim()||``}}}let i=t.split(/\s+/);return i.length>=2?{material:i[1],brand:i[0],variant:i.slice(2).join(` `)}:{material:t,brand:``,variant:``}}function dU(e){return`${e.extruder_id??0}|${e.name}|${e.k_value}`}function fU(e,t,n){return n===void 0?e.find(e=>e.slot_id===t):e.find(e=>e.slot_id===t&&(e.extruder_id??0)===n)}function pU(e,t,n){return t?` \u00b7 ${e.extruder_id===1?n(`common.left`):n(`common.right`)}`:``}function mke(e){return!e.startsWith(`GF`)&&!e.startsWith(`P1`)}var hke={white:`FFFFFF`,black:`000000`,red:`FF0000`,green:`00FF00`,blue:`0000FF`,yellow:`FFFF00`,cyan:`00FFFF`,magenta:`FF00FF`,orange:`FFA500`,purple:`800080`,pink:`FFC0CB`,brown:`8B4513`,gray:`808080`,grey:`808080`,"jade white":`FFFEF2`,ivory:`FFFFF0`,beige:`F5F5DC`,cream:`FFFDD0`,silver:`C0C0C0`,gold:`FFD700`,bronze:`CD7F32`,copper:`B87333`,navy:`000080`,teal:`008080`,olive:`808000`,maroon:`800000`,coral:`FF7F50`,salmon:`FA8072`,lime:`32CD32`,mint:`98FF98`,"forest green":`228B22`,"sky blue":`87CEEB`,"royal blue":`4169E1`,turquoise:`40E0D0`,lavender:`E6E6FA`,violet:`EE82EE`,plum:`DDA0DD`,tan:`D2B48C`,chocolate:`D2691E`,charcoal:`36454F`,slate:`708090`,transparent:`000000`,natural:`F5F5DC`,wood:`DEB887`},mU=[{name:`White`,hex:`FFFFFF`},{name:`Black`,hex:`000000`},{name:`Red`,hex:`FF0000`},{name:`Blue`,hex:`0000FF`},{name:`Green`,hex:`00AA00`},{name:`Yellow`,hex:`FFFF00`},{name:`Orange`,hex:`FFA500`},{name:`Gray`,hex:`808080`}],hU=[{name:`Cyan`,hex:`00FFFF`},{name:`Magenta`,hex:`FF00FF`},{name:`Purple`,hex:`800080`},{name:`Pink`,hex:`FFC0CB`},{name:`Brown`,hex:`8B4513`},{name:`Beige`,hex:`F5F5DC`},{name:`Navy`,hex:`000080`},{name:`Teal`,hex:`008080`},{name:`Lime`,hex:`32CD32`},{name:`Gold`,hex:`FFD700`},{name:`Silver`,hex:`C0C0C0`},{name:`Maroon`,hex:`800000`},{name:`Olive`,hex:`808000`},{name:`Coral`,hex:`FF7F50`},{name:`Salmon`,hex:`FA8072`},{name:`Turquoise`,hex:`40E0D0`},{name:`Violet`,hex:`EE82EE`},{name:`Indigo`,hex:`4B0082`},{name:`Chocolate`,hex:`D2691E`},{name:`Tan`,hex:`D2B48C`},{name:`Slate`,hex:`708090`},{name:`Charcoal`,hex:`36454F`},{name:`Ivory`,hex:`FFFFF0`},{name:`Cream`,hex:`FFFDD0`}];function gU(e){return hke[e.toLowerCase().trim()]||null}function _U({isOpen:e,onClose:t,printerId:n,slotInfo:r,nozzleDiameter:i=`0.4`,printerModel:a,onSuccess:o,fullScreen:s}){let{t:c}=U(),[l,u]=(0,y.useState)(``),[d,f]=(0,y.useState)(null),p=(0,y.useRef)(null);p.current=d;let[m,h]=(0,y.useState)(``),[g,_]=(0,y.useState)(``),[v,b]=(0,y.useState)(``),[x,S]=(0,y.useState)(!1),[C,w]=(0,y.useState)(!1),T=(0,y.useRef)(``),{schedule:E}=sU(),{data:D,isLoading:O,isError:k}=K({queryKey:[`cloudSettings`],queryFn:()=>Z.getCloudSettings(),enabled:e,retry:!1}),{data:A}=K({queryKey:[`orcaCloudProfilesForAmsSlot`],queryFn:()=>Z.orcaCloudListProfiles(),enabled:e,retry:!1}),{data:j,isLoading:M}=K({queryKey:[`localPresets`],queryFn:()=>Z.getLocalPresets(),enabled:e}),{data:N,isLoading:P}=K({queryKey:[`builtinFilaments`],queryFn:()=>Z.getBuiltinFilaments(),enabled:e,staleTime:1/0}),{data:F,isLoading:I}=K({queryKey:[`kprofiles`,n,i],queryFn:()=>Z.getKProfiles(n,i),enabled:e&&!!n}),{data:L}=K({queryKey:[`colorCatalog`],queryFn:()=>Z.getColorCatalog(),enabled:e,staleTime:1/0}),{data:R}=K({queryKey:[`slicerPrinterModels`],queryFn:Z.getSlicerPrinterModels,enabled:e,staleTime:1/0}),{data:z}=K({queryKey:[`slot-spool-defaults`,n,r.amsId,r.trayId],queryFn:()=>Z.getSlotSpoolDefaults(n,r.amsId,r.trayId),enabled:e,staleTime:0}),B=(0,y.useMemo)(()=>MH(R??{}),[R]),V=(0,y.useMemo)(()=>{if(!a||!R)return null;for(let[e,t]of Object.entries(R))if(t===a)return`${e.startsWith(`Bambu Lab `)?e:`Bambu Lab ${e}`} ${i} nozzle`;return null},[a,R,i]),ee=q({mutationFn:async()=>{if(!l)throw Error(`No filament preset selected`);let e=l.startsWith(`local_`),t=l.startsWith(`builtin_`),a=l.startsWith(`orca_`)?l.replace(`orca_`,``):l,o=!e&&!t?A?.filament.find(e=>e.setting_id===a):void 0,s=!!o,c=o??null,u=e?parseInt(l.replace(`local_`,``),10):null,d=t?l.replace(`builtin_`,``):null,f=e?j?.filament.find(e=>e.id===u):null,h=t?N?.find(e=>e.filament_id===d):null,g=!e&&!t&&!s?D?.filament.find(e=>e.setting_id===l):null;if(!e&&!t&&!s&&!g)throw Error(`Selected preset not found`);if(e&&!f)throw Error(`Selected local preset not found`);if(t&&!h)throw Error(`Selected builtin preset not found`);if(s&&!c)throw Error(`Selected Orca Cloud preset not found`);let _=e?f.name:t?h.name:s?c.name:g.name,v=uU(_),y=p.current?.slot_id??-1,b=m||r.trayColor?.slice(0,6)||`FFFFFF`,x=_.replace(/@.+$/,``).trim(),S,C,w=v.material.toUpperCase(),T={PLA:`GFL99`,"PLA-CF":`GFL98`,"PLA SILK":`GFL96`,"PLA HIGH SPEED":`GFL95`,PETG:`GFG99`,"PETG HF":`GFG96`,"PETG-CF":`GFG98`,PCTG:`GFG97`,ABS:`GFB99`,ASA:`GFB98`,PC:`GFC99`,PA:`GFN99`,"PA-CF":`GFN98`,NYLON:`GFN99`,TPU:`GFU99`,PVA:`GFS99`,HIPS:`GFS98`,PE:`GFP99`,PP:`GFP97`};if(e){let e=(lU.includes(w)?w:f?.filament_type||v.material||``).toUpperCase();S=T[e]||T[e.replace(/[-\s]?CF$/,``)]||T[e.replace(/\+$/,``)]||T[e.split(/[-\s]/)[0]]||``,C=``}else if(s){let e=(lU.includes(w)?w:v.material||``).toUpperCase();S=T[e]||T[e.replace(/[-\s]?CF$/,``)]||T[e.replace(/\+$/,``)]||T[e.split(/[-\s]/)[0]]||``,C=``}else if(t)S=d,C=``;else if(S=cU(l),C=l,!l.startsWith(`GFS`))try{let e=await Z.getCloudSettingDetail(l);e.filament_id&&(S=e.filament_id)}catch(e){console.warn(`Failed to fetch preset detail for filament_id:`,e)}let E=e&&f?.nozzle_temp_min?f.nozzle_temp_min:190,O=e&&f?.nozzle_temp_max?f.nozzle_temp_max:230;if(!e||t||s||!f?.nozzle_temp_min&&!f?.nozzle_temp_max){let t=(e?lU.includes(w)?w:f?.filament_type||v.material||``:v.material).toUpperCase();t.includes(`PLA`)?(E=190,O=230):t.includes(`PETG`)?(E=220,O=260):t.includes(`ABS`)||t.includes(`ASA`)?(E=240,O=280):t.includes(`TPU`)?(E=200,O=240):t===`PCTG`?(E=220,O=260):t.includes(`PC`)?(E=260,O=300):(t.includes(`PA`)||t.includes(`NYLON`))&&(E=250,O=290)}let k=p.current?.k_value?parseFloat(p.current.k_value):0,M=e?lU.includes(w)?w:f?.filament_type||v.material||`PLA`:s&&lU.includes(w)?w:v.material||`PLA`,P=await Z.configureAmsSlot(n,r.amsId,r.trayId,{tray_info_idx:S,tray_type:M,tray_sub_brands:x,tray_color:b+`FF`,nozzle_temp_min:E,nozzle_temp_max:O,cali_idx:y,nozzle_diameter:i,setting_id:C,kprofile_filament_id:p.current?.filament_id,kprofile_setting_id:p.current?.setting_id||void 0,k_value:k}),F=e?`local_${u}`:t?`builtin_${d}`:l,I=e?`local`:t?`builtin`:s?`orca_cloud`:`cloud`;try{await Z.saveSlotPreset(n,r.amsId,r.trayId,F,x,I)}catch(e){console.warn(`Failed to save slot preset mapping:`,e)}return P},onSuccess:()=>{S(!0),o?.(),E(()=>{S(!1),t()},1500)}}),te=q({mutationFn:async()=>Z.resetAmsSlot(n,r.amsId,r.trayId),onSuccess:()=>{S(!0),o?.(),E(()=>{S(!1),t()},1500)}}),ne=(0,y.useMemo)(()=>{let e=v.toLowerCase(),t=[],n=new Set,i=r.savedPresetId,o=r.trayInfoIdx;if(A?.filament)for(let r of A.filament){let i=`orca_${r.setting_id}`;if(n.add(r.setting_id),n.add(i),!(e&&!r.name.toLowerCase().includes(e))){if(a){let e=zH(r.name,R??{});if(e&&!jH(e,a))continue}t.push({id:i,name:r.name,source:`orca_cloud`,isUser:!0})}}if(D?.filament)for(let r of D.filament){if(n.has(r.setting_id))continue;n.add(r.setting_id);let s=i===r.setting_id||o&&(r.setting_id===o||cU(r.setting_id)===o);if(!(e&&!r.name.toLowerCase().includes(e))){if(!s&&a){let e=zH(r.name,R??{});if(e&&!jH(e,a))continue}t.push({id:r.setting_id,name:r.name,source:`cloud`,isUser:mke(r.setting_id)})}}if(j?.filament){let n=r.savedPresetId;for(let r of j.filament){let i=`local_${r.id}`;if(!(e&&!r.name.toLowerCase().includes(e))){if(n!==i&&V){let e=null;if(r.compatible_printers)try{let t=JSON.parse(r.compatible_printers);Array.isArray(t)&&(e=t.filter(e=>typeof e==`string`))}catch{e=null}if(RH({name:r.name,compatible_printers:e},`filament`,V,B)===`mismatch`)continue}t.push({id:i,name:r.name,source:`local`,isUser:!1})}}}if(N)for(let r of N){if(n.has(r.filament_id))continue;let i=r.filament_id.startsWith(`GF`)?`GFS`+r.filament_id.slice(2):r.filament_id;n.has(i)||(!e||r.name.toLowerCase().includes(e))&&t.push({id:`builtin_${r.filament_id}`,name:r.name,source:`builtin`,isUser:!1})}return t.sort((e,t)=>{let n={local:0,orca_cloud:1,cloud:2,builtin:3};return e.source===t.source?e.isUser&&!t.isUser?-1:!e.isUser&&t.isUser?1:e.name.localeCompare(t.name):n[e.source]-n[t.source]})},[A?.filament,D?.filament,j?.filament,N,v,a,r.savedPresetId,r.trayInfoIdx,V,B,R]),re=(0,y.useMemo)(()=>{if(!l)return null;let e=null,t=``;if(l.startsWith(`local_`)){let t=parseInt(l.replace(`local_`,``),10);e=j?.filament.find(e=>e.id===t)?.name||null}else if(l.startsWith(`builtin_`)){let n=l.replace(`builtin_`,``);e=N?.find(e=>e.filament_id===n)?.name||null,t=nU(n)}else{let n=l.startsWith(`orca_`)?l.replace(`orca_`,``):l,r=A?.filament.find(e=>e.setting_id===n);if(r)e=r.name;else if(D?.filament){let n=D.filament.find(e=>e.setting_id===l);e=n?.name||null,n&&(t=nU(n.setting_id))}}if(!e)return null;let n=e.replace(/@.+$/,``).trim();n.startsWith(`# `)&&(n=n.slice(2).trim());let r=uU(n);return{fullName:n,material:r.material,brand:r.brand,filamentId:t}},[l,D?.filament,j?.filament,N,A?.filament]),ie=re?.fullName||``,ae=(0,y.useMemo)(()=>{if(!L||!re)return[];let{fullName:e,brand:t}=re,n=e.replace(/^(Bambu\s*(Lab)?|eSUN|Polymaker|Overture|Sunlu|Hatchbox)\s*/i,``).trim();return L.filter(e=>{let r=(e.material||``).toUpperCase(),i=e.manufacturer.toUpperCase();if(!(r===n.toUpperCase()||r.includes(n.toUpperCase())||n.toUpperCase().includes(r)))return!1;if(t){let e=t.toUpperCase();if(!i.includes(e)&&!e.includes(i))return!1}return!0})},[L,re]),oe=(0,y.useMemo)(()=>new Set((F?.profiles??[]).map(e=>e.extruder_id??0)).size>1,[F?.profiles]),se=(0,y.useMemo)(()=>{if(!F?.profiles)return[];if(!re){let e=r.caliIdx;if(e!=null&&e>0){let t=fU(F.profiles,e,r.extruderId);if(t)return[t]}return[]}let{fullName:e,material:t,brand:n,filamentId:i}=re,a=e.toUpperCase(),o=t.toUpperCase(),s=n.toUpperCase()===`GENERIC`?``:n.toUpperCase(),c=i;if(!o||o.length<2)return[];let l=F.profiles.filter(e=>{if(c){let t=nU(e.filament_id);if(t&&t===c)return!0}let t=e.name.toUpperCase();if(s)return!(!t.includes(s)||!t.includes(o));if(t.includes(a)||t.includes(o))return!0;let n={NYLON:[`PA`,`PA-CF`,`PA6`],PA:[`NYLON`]}[o]||[];for(let e of n)if(t.includes(e))return!0;return!1}),u=r.extruderId===void 0?l:l.filter(e=>(e.extruder_id??0)===r.extruderId),d=new Map;for(let e of u){let t=dU(e);d.has(t)||d.set(t,e)}let f=Array.from(d.values()),p=r.caliIdx;if(p!=null&&p>0&&!f.some(e=>e.slot_id===p)){let e=fU(F.profiles,p,r.extruderId);e&&f.unshift(e)}return f},[F?.profiles,re,r.extruderId,r.caliIdx]),H=(0,y.useMemo)(()=>{if(!F?.profiles)return[];let e=new Set(se.map(e=>dU(e))),t=new Map;for(let n of F.profiles){let r=dU(n);e.has(r)||t.has(r)||t.set(r,n)}return Array.from(t.values()).sort((e,t)=>e.name.localeCompare(t.name))},[F?.profiles,se]),ce=se.length>0||H.length>0,le=(0,y.useCallback)(e=>{if(!e){f(null);return}f(se.find(t=>dU(t)===e)||H.find(t=>dU(t)===e)||null)},[se,H]);(0,y.useEffect)(()=>{if(e){if(z?.slicer_filament)u(z.slicer_filament);else if(r.savedPresetId)u(r.savedPresetId);else if(r.trayInfoIdx&&D?.filament){let e=D.filament.find(e=>e.setting_id===r.trayInfoIdx);e||=D.filament.find(e=>cU(e.setting_id)===r.trayInfoIdx),e&&u(e.setting_id)}else if(r.trayInfoIdx&&N?.length){let e=r.trayInfoIdx,t=N.find(t=>t.filament_id===e);t&&u(`builtin_${t.filament_id}`)}if(r.trayColor){let e=r.trayColor.slice(0,6);e&&h(e)}}else u(``),f(null),h(``),_(``),b(``),S(!1),T.current=``},[e,z?.slicer_filament,r.savedPresetId,r.trayInfoIdx,r.trayColor,D?.filament,N]),(0,y.useEffect)(()=>{if(se.length>0){if(z?.cali_idx!=null){let e=fU(se,z.cali_idx,z.extruder??r.extruderId);if(e){f(e);return}}if(r.caliIdx!=null&&r.caliIdx>0){let e=fU(se,r.caliIdx,r.extruderId);if(e){f(e);return}}f(se[0])}else f(null)},[l,se,z?.cali_idx,z?.extruder,r.caliIdx,r.extruderId]);let ue=(0,y.useCallback)(e=>{e.key===`Escape`&&t()},[t]);(0,y.useEffect)(()=>{if(e)return document.addEventListener(`keydown`,ue),()=>document.removeEventListener(`keydown`,ue)},[e,ue]);let de=O&&!k||M||P||I;if((0,y.useEffect)(()=>{if(!de&&l&&l!==T.current){let e=requestAnimationFrame(()=>{let e=document.querySelector(`[class*="fixed inset-0 z-50"]`)?.querySelector(`[data-preset-id="${CSS.escape(l)}"]`);e&&(T.current=l,e.scrollIntoView({block:`nearest`}))});return()=>cancelAnimationFrame(e)}},[l,de]),!e)return null;let fe=l&&!ee.isPending,pe=m||r.trayColor||`FFFFFF`;return(0,G.jsxs)(`div`,{className:`fixed inset-0 z-50 flex ${s?``:`items-center justify-center`}`,children:[!s&&(0,G.jsx)(`div`,{className:`absolute inset-0 bg-black/60 backdrop-blur-sm`,onClick:t}),(0,G.jsxs)(`div`,{className:s?`relative w-full h-full bg-bambu-dark-secondary flex flex-col`:`relative w-full max-w-lg mx-4 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl`,children:[(0,G.jsxs)(`div`,{className:`flex items-center justify-between p-4 border-b border-bambu-dark-tertiary shrink-0`,children:[(0,G.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,G.jsx)(eu,{className:`w-5 h-5 text-bambu-blue`}),(0,G.jsx)(`h2`,{className:`text-lg font-semibold text-white`,children:c(`configureAmsSlot.title`)}),s&&(0,G.jsxs)(`div`,{className:`flex items-center gap-2 ml-4 text-sm text-bambu-gray`,children:[(0,G.jsx)(`span`,{className:`text-white/30`,children:`|`}),r.trayColor&&(0,G.jsx)(`span`,{className:`w-4 h-4 rounded-full border border-black/20`,style:Tf(r.trayColor)}),(0,G.jsx)(`span`,{className:`text-white/70`,children:c(`configureAmsSlot.slotLabel`,{ams:fp(r.amsId,r.trayCount),slot:r.trayId+1})}),r.traySubBrands&&(0,G.jsxs)(`span`,{children:[`(`,r.traySubBrands,`)`]})]})]}),(0,G.jsx)(`button`,{onClick:t,className:`p-1 text-bambu-gray hover:text-white rounded transition-colors`,children:(0,G.jsx)(ed,{className:`w-5 h-5`})})]}),(0,G.jsxs)(`div`,{className:`p-4 overflow-y-auto ${s?`flex-1 min-h-0`:`space-y-4 max-h-[60vh]`}`,children:[x&&(0,G.jsx)(`div`,{className:`absolute inset-0 bg-bambu-dark-secondary/95 z-10 flex items-center justify-center rounded-xl`,children:(0,G.jsxs)(`div`,{className:`text-center space-y-3`,children:[(0,G.jsx)(bs,{className:`w-16 h-16 text-bambu-green mx-auto`}),(0,G.jsx)(`p`,{className:`text-lg font-semibold text-white`,children:c(`configureAmsSlot.slotConfigured`)}),(0,G.jsx)(`p`,{className:`text-sm text-bambu-gray`,children:c(`configureAmsSlot.settingsSentToPrinter`)})]})}),!s&&(0,G.jsxs)(`div`,{className:`p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary`,children:[(0,G.jsx)(`p`,{className:`text-xs text-bambu-gray mb-1`,children:c(`configureAmsSlot.configuringSlot`)}),(0,G.jsxs)(`div`,{className:`flex items-center gap-2`,children:[r.trayColor&&(0,G.jsx)(`span`,{className:`w-4 h-4 rounded-full border border-black/20`,style:Tf(r.trayColor)}),(0,G.jsx)(`span`,{className:`text-white font-medium`,children:c(`configureAmsSlot.slotLabel`,{ams:fp(r.amsId,r.trayCount),slot:r.trayId+1})}),r.traySubBrands&&(0,G.jsxs)(`span`,{className:`text-bambu-gray`,children:[`(`,r.traySubBrands,`)`]})]})]}),de?(0,G.jsx)(`div`,{className:`flex justify-center py-8`,children:(0,G.jsx)(Y,{className:`w-6 h-6 text-bambu-green animate-spin`})}):s?(0,G.jsxs)(`div`,{className:`flex gap-4 h-full`,children:[(0,G.jsxs)(`div`,{className:`w-1/2 flex flex-col min-h-0`,children:[(0,G.jsxs)(`label`,{className:`block text-sm text-bambu-gray mb-2`,children:[c(`configureAmsSlot.filamentProfile`),` `,(0,G.jsx)(`span`,{className:`text-red-600 dark:text-red-400`,children:`*`})]}),(0,G.jsx)(`input`,{type:`text`,placeholder:c(`configureAmsSlot.searchPresets`),value:v,onChange:e=>b(e.target.value),className:`w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder:text-bambu-gray focus:border-bambu-green focus:outline-none mb-2 shrink-0`}),(0,G.jsx)(`div`,{className:`flex-1 min-h-0 overflow-y-auto space-y-1`,children:ne.length===0?(0,G.jsx)(`p`,{className:`text-center py-4 text-bambu-gray`,children:D?.filament?.length===0&&!j?.filament?.length?c(`configureAmsSlot.noPresetsAvailable`):c(`configureAmsSlot.noMatchingPresets`)}):ne.map(e=>(0,G.jsx)(`button`,{"data-preset-id":e.id,onClick:()=>u(e.id),className:`group w-full p-2 rounded-lg border text-left transition-colors ${l===e.id?`bg-bambu-green/20 border-bambu-green`:`bg-bambu-dark border-bambu-dark-tertiary hover:border-bambu-gray`}`,children:(0,G.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,G.jsx)(`span`,{className:`text-white text-sm truncate group-hover:whitespace-normal group-hover:break-all`,title:e.name,children:e.name}),(0,G.jsxs)(`div`,{className:`flex items-center gap-1 flex-shrink-0`,children:[e.source===`local`&&(0,G.jsx)(`span`,{className:`text-xs px-1.5 py-0.5 rounded bg-green-100 dark:bg-green-500/20 text-green-700 dark:text-green-400`,children:c(`profiles.localProfiles.badge`)}),e.source===`orca_cloud`&&(0,G.jsx)(`span`,{className:`text-xs px-1.5 py-0.5 rounded bg-purple-100 dark:bg-purple-500/20 text-purple-700 dark:text-purple-400`,children:c(`configureAmsSlot.orcaCloud`)}),e.source===`cloud`&&(0,G.jsx)(`span`,{className:`text-xs px-1.5 py-0.5 rounded bg-bambu-blue/20 text-bambu-blue`,children:c(`configureAmsSlot.bambuCloud`)}),e.source===`builtin`&&(0,G.jsx)(`span`,{className:`text-xs px-1.5 py-0.5 rounded bg-amber-100 dark:bg-amber-500/20 text-amber-700 dark:text-amber-400`,children:c(`configureAmsSlot.builtin`)})]})]})},e.id))})]}),(0,G.jsxs)(`div`,{className:`w-1/2 flex flex-col gap-4 min-h-0 overflow-y-auto`,children:[(0,G.jsxs)(`div`,{children:[(0,G.jsxs)(`label`,{className:`block text-sm text-bambu-gray mb-2`,children:[c(`configureAmsSlot.kProfileLabel`),ie&&(0,G.jsx)(`span`,{className:`ml-2 text-xs text-bambu-blue`,children:c(`configureAmsSlot.filteringFor`,{material:ie})})]}),ce?(0,G.jsxs)(`div`,{className:`relative`,children:[(0,G.jsxs)(`select`,{value:d?dU(d):``,onChange:e=>le(e.target.value),className:`w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none appearance-none pr-10`,children:[(0,G.jsx)(`option`,{value:``,children:c(`configureAmsSlot.noKProfile`)}),se.map(e=>(0,G.jsxs)(`option`,{value:dU(e),children:[e.name,` (K=`,e.k_value,`)`,pU(e,oe,c),pU(e,oe,c)]},dU(e))),H.length>0&&(0,G.jsx)(`optgroup`,{label:c(`configureAmsSlot.otherKProfiles`),children:H.map(e=>(0,G.jsxs)(`option`,{value:dU(e),children:[e.name,` (K=`,e.k_value,`)`,pU(e,oe,c),pU(e,oe,c),pU(e,oe,c)]},dU(e)))})]}),(0,G.jsx)(ds,{className:`absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none`})]}):l?(0,G.jsx)(`p`,{className:`text-sm text-bambu-gray italic py-2`,children:c(`configureAmsSlot.noMatchingKProfiles`)}):(0,G.jsx)(`span`,{className:`inline-block text-xs px-2 py-1 rounded bg-amber-100 dark:bg-amber-500/20 text-amber-700 dark:text-amber-400 border border-amber-300 dark:border-amber-500/30`,children:c(`configureAmsSlot.selectFilamentFirst`)}),d&&(0,G.jsx)(`p`,{className:`text-xs text-bambu-green mt-1`,children:c(`configureAmsSlot.kFromCalibration`,{value:d.k_value})})]}),(0,G.jsxs)(`div`,{children:[(0,G.jsx)(`label`,{className:`block text-sm text-bambu-gray mb-2`,children:c(`configureAmsSlot.customColorLabel`)}),ae.length>0&&(0,G.jsxs)(`div`,{className:`mb-3`,children:[(0,G.jsx)(`p`,{className:`text-xs text-bambu-gray mb-1.5`,children:c(`configureAmsSlot.presetColors`,{name:re?.fullName})}),(0,G.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,children:ae.map(e=>(0,G.jsxs)(`button`,{onClick:()=>{h(e.hex_color.replace(`#`,``).toUpperCase()),_(e.color_name)},className:`h-7 px-2 rounded-md border-2 transition-all flex items-center gap-1.5 ${m===e.hex_color.replace(`#`,``).toUpperCase()?`border-bambu-green scale-105`:`border-white/20 hover:border-white/40`}`,title:e.color_name,children:[(0,G.jsx)(`span`,{className:`w-4 h-4 rounded-full border border-black/20 flex-shrink-0`,style:{backgroundColor:e.hex_color}}),(0,G.jsx)(`span`,{className:`text-xs text-white/80 whitespace-nowrap`,children:e.color_name})]},e.id))})]}),(0,G.jsxs)(`div`,{className:`flex flex-wrap gap-1.5 mb-2`,children:[mU.map(e=>(0,G.jsx)(`button`,{onClick:()=>{h(e.hex),_(e.name)},className:`w-7 h-7 rounded-md border-2 transition-all ${m===e.hex?`border-bambu-green scale-110`:`border-white/20 hover:border-white/40`}`,style:{backgroundColor:`#${e.hex}`},title:e.name},e.hex)),(0,G.jsx)(`button`,{onClick:()=>w(!C),className:`w-7 h-7 rounded-md border-2 border-white/20 hover:border-white/40 flex items-center justify-center text-white/60 hover:text-white/80 transition-all text-xs`,title:c(C?`configureAmsSlot.showLessColors`:`configureAmsSlot.showMoreColors`),children:C?`−`:`+`})]}),C&&(0,G.jsx)(`div`,{className:`flex flex-wrap gap-1.5 mb-2`,children:hU.map(e=>(0,G.jsx)(`button`,{onClick:()=>{h(e.hex),_(e.name)},className:`w-7 h-7 rounded-md border-2 transition-all ${m===e.hex?`border-bambu-green scale-110`:`border-white/20 hover:border-white/40`}`,style:{backgroundColor:`#${e.hex}`},title:e.name},e.hex))}),(0,G.jsxs)(`div`,{className:`flex gap-2 items-center`,children:[(0,G.jsx)(`div`,{className:`w-10 h-10 rounded-lg border-2 border-white/20 flex-shrink-0`,style:Tf(pe)}),(0,G.jsx)(`input`,{type:`text`,placeholder:c(`configureAmsSlot.colorPlaceholder`),value:g,onChange:e=>{let t=e.target.value;_(t);let n=gU(t);if(n)h(n);else{let e=t.replace(/[^0-9A-Fa-f]/g,``).toUpperCase();e.length===6?h(e):e.length===3&&h(e.split(``).map(e=>e+e).join(``))}},className:`flex-1 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder:text-bambu-gray focus:border-bambu-green focus:outline-none text-sm`}),m&&(0,G.jsx)(`button`,{onClick:()=>{h(``),_(``)},className:`px-2 py-1 text-xs text-bambu-gray hover:text-white bg-bambu-dark-tertiary rounded`,title:c(`configureAmsSlot.clearCustomColor`),children:c(`configureAmsSlot.clear`)})]}),m&&(0,G.jsx)(`p`,{className:`text-xs text-bambu-gray mt-1.5`,children:c(`configureAmsSlot.hexLabel`,{hex:m})})]})]})]}):(0,G.jsxs)(G.Fragment,{children:[(0,G.jsxs)(`div`,{children:[(0,G.jsxs)(`label`,{className:`block text-sm text-bambu-gray mb-2`,children:[c(`configureAmsSlot.filamentProfile`),` `,(0,G.jsx)(`span`,{className:`text-red-600 dark:text-red-400`,children:`*`})]}),(0,G.jsxs)(`div`,{className:`relative`,children:[(0,G.jsx)(`input`,{type:`text`,placeholder:c(`configureAmsSlot.searchPresets`),value:v,onChange:e=>b(e.target.value),className:`w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder:text-bambu-gray focus:border-bambu-green focus:outline-none mb-2`}),(0,G.jsx)(`div`,{className:`max-h-48 overflow-y-auto space-y-1`,children:ne.length===0?(0,G.jsx)(`p`,{className:`text-center py-4 text-bambu-gray`,children:D?.filament?.length===0&&!j?.filament?.length?c(`configureAmsSlot.noPresetsAvailable`):c(`configureAmsSlot.noMatchingPresets`)}):ne.map(e=>(0,G.jsx)(`button`,{"data-preset-id":e.id,onClick:()=>u(e.id),className:`group w-full p-2 rounded-lg border text-left transition-colors ${l===e.id?`bg-bambu-green/20 border-bambu-green`:`bg-bambu-dark border-bambu-dark-tertiary hover:border-bambu-gray`}`,children:(0,G.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,G.jsx)(`span`,{className:`text-white text-sm truncate group-hover:whitespace-normal group-hover:break-all`,title:e.name,children:e.name}),(0,G.jsxs)(`div`,{className:`flex items-center gap-1 flex-shrink-0`,children:[e.source===`local`&&(0,G.jsx)(`span`,{className:`text-xs px-1.5 py-0.5 rounded bg-green-100 dark:bg-green-500/20 text-green-700 dark:text-green-400`,children:c(`profiles.localProfiles.badge`)}),e.source===`orca_cloud`&&(0,G.jsx)(`span`,{className:`text-xs px-1.5 py-0.5 rounded bg-purple-100 dark:bg-purple-500/20 text-purple-700 dark:text-purple-400`,children:c(`configureAmsSlot.orcaCloud`)}),e.source===`cloud`&&(0,G.jsx)(`span`,{className:`text-xs px-1.5 py-0.5 rounded bg-bambu-blue/20 text-bambu-blue`,children:c(`configureAmsSlot.bambuCloud`)}),e.source===`builtin`&&(0,G.jsx)(`span`,{className:`text-xs px-1.5 py-0.5 rounded bg-amber-100 dark:bg-amber-500/20 text-amber-700 dark:text-amber-400`,children:c(`configureAmsSlot.builtin`)})]})]})},e.id))})]})]}),(0,G.jsxs)(`div`,{children:[(0,G.jsxs)(`label`,{className:`block text-sm text-bambu-gray mb-2`,children:[c(`configureAmsSlot.kProfileLabel`),ie&&(0,G.jsx)(`span`,{className:`ml-2 text-xs text-bambu-blue`,children:c(`configureAmsSlot.filteringFor`,{material:ie})})]}),ce?(0,G.jsxs)(`div`,{className:`relative`,children:[(0,G.jsxs)(`select`,{value:d?dU(d):``,onChange:e=>le(e.target.value),className:`w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none appearance-none pr-10`,children:[(0,G.jsx)(`option`,{value:``,children:c(`configureAmsSlot.noKProfile`)}),se.map(e=>(0,G.jsxs)(`option`,{value:dU(e),children:[e.name,` (K=`,e.k_value,`)`,pU(e,oe,c)]},dU(e))),H.length>0&&(0,G.jsx)(`optgroup`,{label:c(`configureAmsSlot.otherKProfiles`),children:H.map(e=>(0,G.jsxs)(`option`,{value:dU(e),children:[e.name,` (K=`,e.k_value,`)`,pU(e,oe,c),pU(e,oe,c),pU(e,oe,c)]},dU(e)))})]}),(0,G.jsx)(ds,{className:`absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none`})]}):l?(0,G.jsx)(`p`,{className:`text-sm text-bambu-gray italic py-2`,children:c(`configureAmsSlot.noMatchingKProfiles`)}):(0,G.jsx)(`span`,{className:`inline-block text-xs px-2 py-1 rounded bg-amber-100 dark:bg-amber-500/20 text-amber-700 dark:text-amber-400 border border-amber-300 dark:border-amber-500/30`,children:c(`configureAmsSlot.selectFilamentFirst`)}),d&&(0,G.jsx)(`p`,{className:`text-xs text-bambu-green mt-1`,children:c(`configureAmsSlot.kFromCalibration`,{value:d.k_value})})]}),(0,G.jsxs)(`div`,{children:[(0,G.jsx)(`label`,{className:`block text-sm text-bambu-gray mb-2`,children:c(`configureAmsSlot.customColorLabel`)}),ae.length>0&&(0,G.jsxs)(`div`,{className:`mb-3`,children:[(0,G.jsx)(`p`,{className:`text-xs text-bambu-gray mb-1.5`,children:c(`configureAmsSlot.presetColors`,{name:re?.fullName})}),(0,G.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,children:ae.map(e=>(0,G.jsxs)(`button`,{onClick:()=>{h(e.hex_color.replace(`#`,``).toUpperCase()),_(e.color_name)},className:`h-7 px-2 rounded-md border-2 transition-all flex items-center gap-1.5 ${m===e.hex_color.replace(`#`,``).toUpperCase()?`border-bambu-green scale-105`:`border-white/20 hover:border-white/40`}`,title:e.color_name,children:[(0,G.jsx)(`span`,{className:`w-4 h-4 rounded-full border border-black/20 flex-shrink-0`,style:{backgroundColor:e.hex_color}}),(0,G.jsx)(`span`,{className:`text-xs text-white/80 whitespace-nowrap`,children:e.color_name})]},e.id))})]}),(0,G.jsxs)(`div`,{className:`flex flex-wrap gap-1.5 mb-2`,children:[mU.map(e=>(0,G.jsx)(`button`,{onClick:()=>{h(e.hex),_(e.name)},className:`w-7 h-7 rounded-md border-2 transition-all ${m===e.hex?`border-bambu-green scale-110`:`border-white/20 hover:border-white/40`}`,style:{backgroundColor:`#${e.hex}`},title:e.name},e.hex)),(0,G.jsx)(`button`,{onClick:()=>w(!C),className:`w-7 h-7 rounded-md border-2 border-white/20 hover:border-white/40 flex items-center justify-center text-white/60 hover:text-white/80 transition-all text-xs`,title:c(C?`configureAmsSlot.showLessColors`:`configureAmsSlot.showMoreColors`),children:C?`−`:`+`})]}),C&&(0,G.jsx)(`div`,{className:`flex flex-wrap gap-1.5 mb-2`,children:hU.map(e=>(0,G.jsx)(`button`,{onClick:()=>{h(e.hex),_(e.name)},className:`w-7 h-7 rounded-md border-2 transition-all ${m===e.hex?`border-bambu-green scale-110`:`border-white/20 hover:border-white/40`}`,style:{backgroundColor:`#${e.hex}`},title:e.name},e.hex))}),(0,G.jsxs)(`div`,{className:`flex gap-2 items-center`,children:[(0,G.jsx)(`div`,{className:`w-10 h-10 rounded-lg border-2 border-white/20 flex-shrink-0`,style:Tf(pe)}),(0,G.jsx)(`input`,{type:`text`,placeholder:c(`configureAmsSlot.colorPlaceholder`),value:g,onChange:e=>{let t=e.target.value;_(t);let n=gU(t);if(n)h(n);else{let e=t.replace(/[^0-9A-Fa-f]/g,``).toUpperCase();e.length===6?h(e):e.length===3&&h(e.split(``).map(e=>e+e).join(``))}},className:`flex-1 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder:text-bambu-gray focus:border-bambu-green focus:outline-none text-sm`}),m&&(0,G.jsx)(`button`,{onClick:()=>{h(``),_(``)},className:`px-2 py-1 text-xs text-bambu-gray hover:text-white bg-bambu-dark-tertiary rounded`,title:c(`configureAmsSlot.clearCustomColor`),children:c(`configureAmsSlot.clear`)})]}),m&&(0,G.jsx)(`p`,{className:`text-xs text-bambu-gray mt-1.5`,children:c(`configureAmsSlot.hexLabel`,{hex:m})})]})]})]}),(0,G.jsxs)(`div`,{className:`flex justify-between p-4 border-t border-bambu-dark-tertiary shrink-0`,children:[(0,G.jsx)(Q,{variant:`secondary`,onClick:()=>te.mutate(),disabled:te.isPending||ee.isPending,className:`text-red-600 dark:text-red-400 hover:text-red-700 dark:hover:text-red-300 hover:bg-red-50 dark:hover:bg-red-500/10`,children:te.isPending?(0,G.jsxs)(G.Fragment,{children:[(0,G.jsx)(Y,{className:`w-4 h-4 animate-spin`}),c(`configureAmsSlot.resetting`)]}):(0,G.jsxs)(G.Fragment,{children:[(0,G.jsx)(Hl,{className:`w-4 h-4`}),c(`configureAmsSlot.resetSlot`)]})}),(0,G.jsxs)(`div`,{className:`flex gap-2`,children:[(0,G.jsx)(Q,{variant:`secondary`,onClick:t,children:c(`configureAmsSlot.cancel`)}),(0,G.jsx)(Q,{onClick:()=>ee.mutate(),disabled:!fe,children:ee.isPending?(0,G.jsxs)(G.Fragment,{children:[(0,G.jsx)(Y,{className:`w-4 h-4 animate-spin`}),c(`configureAmsSlot.configuring`)]}):(0,G.jsxs)(G.Fragment,{children:[(0,G.jsx)(eu,{className:`w-4 h-4`}),c(`configureAmsSlot.configureSlot`)]})})]})]}),(ee.isError||te.isError)&&(0,G.jsx)(`div`,{className:`mx-4 mb-4 p-2 bg-red-100 dark:bg-red-500/20 border border-red-300 dark:border-red-500/50 rounded text-sm text-red-700 dark:text-red-400`,children:ee.error?.message||te.error?.message})]})]})}function vU({className:e=`w-4 h-4`}){return(0,G.jsx)(`svg`,{viewBox:`0 0 1945 1370`,fill:`none`,className:e,"aria-hidden":`true`,children:(0,G.jsxs)(`g`,{transform:`translate(-754.293 -471.685)`,children:[(0,G.jsxs)(`g`,{transform:`translate(0.18191 255.976)`,children:[(0,G.jsx)(`g`,{transform:`matrix(1.05469 0 0 0.241063 -153.484 1120.2)`,children:(0,G.jsx)(`rect`,{x:`922.048`,y:`1195.15`,width:`1721.5`,height:`470.135`,stroke:`currentColor`,strokeOpacity:`0.99`,strokeWidth:`168.84`,strokeLinecap:`round`,strokeLinejoin:`round`})}),(0,G.jsx)(`g`,{transform:`matrix(0.983656 0 0 1.0767 -62.2035 141.539)`,children:(0,G.jsx)(`path`,{d:`M2741.42,1175.93L895.832,1175.93L1125.16,621.902L2512.09,621.902L2741.42,1175.93Z`,fill:`currentColor`,fillOpacity:`0.05`,stroke:`currentColor`,strokeOpacity:`0.99`,strokeWidth:`125.26`,strokeLinecap:`round`,strokeLinejoin:`round`})})]}),(0,G.jsx)(`g`,{transform:`translate(21.1916 0.684817)`,children:(0,G.jsx)(`path`,{d:`M1981.31,567.518C1954.86,567.518 1933.39,546.047 1933.39,519.601C1933.39,493.156 1954.86,471.685 1981.31,471.685L2146.61,471.685C2173.07,471.685 2194.53,493.138 2194.53,519.601L2194.53,688.741C2194.53,715.187 2173.05,736.658 2146.61,736.658C2120.16,736.658 2098.69,715.187 2098.69,688.741L2098.69,567.518L1981.31,567.518ZM2098.69,1252.54C2098.69,1226.1 2120.16,1204.62 2146.61,1204.62C2173.05,1204.62 2194.53,1226.1 2194.53,1252.54L2194.53,1421.68C2194.53,1448.14 2173.07,1469.6 2146.61,1469.6L1981.31,1469.6C1954.86,1469.6 1933.39,1448.13 1933.39,1421.68C1933.39,1395.24 1954.86,1373.76 1981.31,1373.76L2098.69,1373.76L2098.69,1252.54ZM1430.29,1373.76C1456.74,1373.76 1478.21,1395.24 1478.21,1421.68C1478.21,1448.13 1456.74,1469.6 1430.29,1469.6L1264.99,1469.6C1238.53,1469.6 1217.07,1448.14 1217.07,1421.68L1217.07,1252.54C1217.07,1226.1 1238.55,1204.62 1264.99,1204.62C1291.44,1204.62 1312.91,1226.1 1312.91,1252.54L1312.91,1373.76L1430.29,1373.76ZM1312.91,688.741C1312.91,715.187 1291.44,736.658 1264.99,736.658C1238.55,736.658 1217.07,715.187 1217.07,688.741L1217.07,519.601C1217.07,493.138 1238.53,471.685 1264.99,471.685L1430.29,471.685C1456.74,471.685 1478.21,493.156 1478.21,519.601C1478.21,546.047 1456.74,567.518 1430.29,567.518L1312.91,567.518L1312.91,688.741Z`,fill:`currentColor`,fillOpacity:`0.99`})})]})})}function yU({folderId:e,onClose:t,onUploadComplete:n,onFileUploaded:r,autoUpload:i,validateFile:a,accept:o,initialFiles:s}){let{t:c}=U(),[l,u]=(0,y.useState)([]),[d,f]=(0,y.useState)(!1),[p,m]=(0,y.useState)(!1),[h,g]=(0,y.useState)(!0),[_,v]=(0,y.useState)(!1),[b,x]=(0,y.useState)(!0),[S,C]=(0,y.useState)(null),w=(0,y.useRef)(null),T=e=>{e.preventDefault(),f(!0)},E=e=>{e.preventDefault(),f(!1)},D=e=>{e.preventDefault(),f(!1),j(Array.from(e.dataTransfer.files))},O=e=>{e.target.files&&j(Array.from(e.target.files))},k=(e,t)=>{u(n=>n.map(n=>n.file===e?{...n,...t}:n))},A=async i=>{m(!0);for(let t of i)if(t.status===`pending`){k(t.file,{status:`uploading`});try{if(t.isZip){let n=await Z.extractZipFile(t.file,e,h,_,b);k(t.file,{status:n.errors.length>0&&n.extracted===0?`error`:`success`,extractedCount:n.extracted,error:n.errors.length>0?c(`fileManager.zipFilesFailed`,`{{count}} files failed`,{count:n.errors.length}):void 0})}else{let n=await Z.uploadLibraryFile(t.file,e,b);k(t.file,{status:`success`});let i=r?.(n);if(i){C(i),u([]),m(!1);return}}}catch(e){k(t.file,{status:`error`,error:e instanceof Error?e.message:c(`fileManager.uploadFailed`,`Upload failed`)})}}m(!1),n(),u(e=>(e.some(e=>e.status===`error`)||t(),e))},j=e=>{if(C(null),a)for(let t of e){let e=a(t);if(e){C(e);return}}let t=e.map(e=>({file:e,status:`pending`,isZip:e.name.toLowerCase().endsWith(`.zip`),is3mf:e.name.toLowerCase().endsWith(`.3mf`)}));u(e=>[...e,...t]),i&&e.length>0&&A(t)},M=e=>{u(t=>t.filter((t,n)=>n!==e))},N=(0,y.useRef)(!1);(0,y.useEffect)(()=>{N.current||!s||s.length===0||(N.current=!0,j(s))},[]);let P=l.some(e=>e.isZip&&e.status===`pending`),F=l.some(e=>e.file.name.toLowerCase().endsWith(`.stl`)&&e.status===`pending`),I=l.some(e=>e.is3mf&&e.status===`pending`),L=l.filter(e=>e.status===`pending`).length,R=l.length>0&&L===0&&!p;return(0,G.jsx)(`div`,{className:`fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4`,children:(0,G.jsxs)(`div`,{className:`bg-bambu-dark-secondary rounded-lg w-full max-w-lg border border-bambu-dark-tertiary`,children:[(0,G.jsxs)(`div`,{className:`p-4 border-b border-bambu-dark-tertiary flex items-center justify-between`,children:[(0,G.jsx)(`h2`,{className:`text-lg font-semibold text-white`,children:c(`fileManager.uploadFiles`)}),(0,G.jsx)(`button`,{onClick:t,className:`p-1 hover:bg-bambu-dark rounded`,children:(0,G.jsx)(ed,{className:`w-5 h-5 text-bambu-gray`})})]}),(0,G.jsxs)(`div`,{className:`p-4 space-y-4`,children:[(0,G.jsxs)(`div`,{onDragOver:T,onDragLeave:E,onDrop:D,onClick:()=>w.current?.click(),className:`border-2 border-dashed rounded-lg p-8 text-center cursor-pointer transition-colors ${d?`border-bambu-green bg-bambu-green/10`:`border-bambu-dark-tertiary hover:border-bambu-green/50`}`,children:[(0,G.jsx)(zu,{className:`w-10 h-10 mx-auto mb-3 ${d?`text-bambu-green`:`text-bambu-gray`}`}),(0,G.jsx)(`p`,{className:`text-white font-medium`,children:c(d?`fileManager.dropFilesHere`:`fileManager.dragDropFiles`)}),(0,G.jsx)(`p`,{className:`text-sm text-bambu-gray mt-1`,children:c(`fileManager.orClickToBrowse`)}),(0,G.jsx)(`p`,{className:`text-xs text-bambu-gray/70 mt-2`,children:c(`fileManager.allFileTypesSupported`)})]}),(0,G.jsx)(`input`,{ref:w,type:`file`,multiple:!0,accept:o,className:`hidden`,onChange:O}),P&&(0,G.jsx)(`div`,{className:`p-3 bg-blue-50 dark:bg-blue-500/10 border border-blue-300 dark:border-blue-500/30 rounded-lg`,children:(0,G.jsxs)(`div`,{className:`flex items-start gap-3`,children:[(0,G.jsx)(Mo,{className:`w-5 h-5 text-blue-600 dark:text-blue-400 mt-0.5 flex-shrink-0`}),(0,G.jsxs)(`div`,{className:`flex-1`,children:[(0,G.jsx)(`p`,{className:`text-sm text-blue-700 dark:text-blue-300 font-medium`,children:c(`fileManager.zipFilesDetected`)}),(0,G.jsx)(`p`,{className:`text-xs text-blue-700/80 dark:text-blue-300/70 mt-1`,children:c(`fileManager.zipExtractOptions`)}),(0,G.jsxs)(`label`,{className:`flex items-center gap-2 mt-2 cursor-pointer`,children:[(0,G.jsx)(`input`,{type:`checkbox`,checked:h,onChange:e=>g(e.target.checked),className:`w-4 h-4 rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green`}),(0,G.jsx)(`span`,{className:`text-sm text-white`,children:c(`fileManager.preserveZipStructure`)})]}),(0,G.jsxs)(`label`,{className:`flex items-center gap-2 mt-2 cursor-pointer`,children:[(0,G.jsx)(`input`,{type:`checkbox`,checked:_,onChange:e=>v(e.target.checked),className:`w-4 h-4 rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green`}),(0,G.jsx)(`span`,{className:`text-sm text-white`,children:c(`fileManager.createFolderFromZip`)})]})]})]})}),I&&(0,G.jsx)(`div`,{className:`p-3 bg-purple-50 dark:bg-purple-500/10 border border-purple-300 dark:border-purple-500/30 rounded-lg`,children:(0,G.jsxs)(`div`,{className:`flex items-start gap-3`,children:[(0,G.jsx)(Il,{className:`w-5 h-5 text-purple-600 dark:text-purple-400 mt-0.5 flex-shrink-0`}),(0,G.jsxs)(`div`,{className:`flex-1`,children:[(0,G.jsx)(`p`,{className:`text-sm text-purple-700 dark:text-purple-300 font-medium`,children:c(`fileManager.threemfDetected`)}),(0,G.jsx)(`p`,{className:`text-xs text-purple-700/80 dark:text-purple-300/70 mt-1`,children:c(`fileManager.threemfExtractionInfo`)})]})]})}),(F||P)&&(0,G.jsx)(`div`,{className:`p-3 bg-bambu-green/10 border border-bambu-green/30 rounded-lg`,children:(0,G.jsxs)(`div`,{className:`flex items-start gap-3`,children:[(0,G.jsx)(Bc,{className:`w-5 h-5 text-bambu-green mt-0.5 flex-shrink-0`}),(0,G.jsxs)(`div`,{className:`flex-1`,children:[(0,G.jsx)(`p`,{className:`text-sm text-bambu-green font-medium`,children:c(`fileManager.stlThumbnailGeneration`)}),(0,G.jsx)(`p`,{className:`text-xs text-bambu-green/70 mt-1`,children:c(P&&!F?`fileManager.zipMayContainStl`:`fileManager.thumbnailsCanBeGenerated`)}),(0,G.jsxs)(`label`,{className:`flex items-center gap-2 mt-2 cursor-pointer`,children:[(0,G.jsx)(`input`,{type:`checkbox`,checked:b,onChange:e=>x(e.target.checked),className:`w-4 h-4 rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green`}),(0,G.jsx)(`span`,{className:`text-sm text-white`,children:c(`fileManager.generateThumbnailsForStl`)})]})]})]})}),l.length>0&&(0,G.jsx)(`div`,{className:`max-h-48 overflow-y-auto space-y-2`,children:l.map((e,t)=>(0,G.jsxs)(`div`,{className:`flex items-center gap-3 p-2 bg-bambu-dark rounded-lg`,children:[e.isZip?(0,G.jsx)(Mo,{className:`w-4 h-4 text-blue-600 dark:text-blue-400 flex-shrink-0`}):(0,G.jsx)(dc,{className:`w-4 h-4 text-bambu-gray flex-shrink-0`}),(0,G.jsxs)(`div`,{className:`flex-1 min-w-0`,children:[(0,G.jsx)(`p`,{className:`text-sm text-white truncate`,children:e.file.name}),(0,G.jsxs)(`p`,{className:`text-xs text-bambu-gray`,children:[(e.file.size/1024/1024).toFixed(2),` MB`,e.isZip&&e.status===`pending`&&(0,G.jsxs)(`span`,{className:`text-blue-700 dark:text-blue-400 ml-2`,children:[`• `,c(`fileManager.willBeExtracted`)]}),e.extractedCount!==void 0&&(0,G.jsxs)(`span`,{className:`text-green-700 dark:text-green-400 ml-2`,children:[`• `,c(`fileManager.filesExtracted`,{count:e.extractedCount})]})]}),e.status===`error`&&e.error&&(0,G.jsx)(`p`,{className:`text-xs text-red-700 dark:text-red-400 mt-1 break-words`,children:e.error})]}),e.status===`pending`&&(0,G.jsx)(`button`,{onClick:()=>M(t),className:`p-1 hover:bg-bambu-dark-tertiary rounded`,children:(0,G.jsx)(ed,{className:`w-4 h-4 text-bambu-gray`})}),e.status===`uploading`&&(0,G.jsx)(Y,{className:`w-4 h-4 text-bambu-green animate-spin`}),e.status===`success`&&(0,G.jsx)(ys,{className:`w-4 h-4 text-green-500`}),e.status===`error`&&(0,G.jsx)(`span`,{title:e.error,children:(0,G.jsx)(Ts,{className:`w-4 h-4 text-red-500`})})]},t))}),S&&(0,G.jsx)(`div`,{className:`p-3 bg-red-50 dark:bg-red-500/10 border border-red-300 dark:border-red-500/30 rounded-lg`,children:(0,G.jsxs)(`div`,{className:`flex items-start gap-3`,children:[(0,G.jsx)(Ts,{className:`w-5 h-5 text-red-600 dark:text-red-400 mt-0.5 flex-shrink-0`}),(0,G.jsx)(`p`,{className:`text-sm text-red-700 dark:text-red-300`,children:S})]})})]}),(0,G.jsxs)(`div`,{className:`p-4 border-t border-bambu-dark-tertiary flex justify-end gap-2`,children:[(0,G.jsx)(Q,{variant:`secondary`,onClick:t,children:c(`common.cancel`)}),!R&&(0,G.jsx)(Q,{onClick:()=>A(l),disabled:L===0||p,children:p?(0,G.jsxs)(G.Fragment,{children:[(0,G.jsx)(Y,{className:`w-4 h-4 mr-2 animate-spin`}),c(`fileManager.uploading`)]}):(0,G.jsxs)(G.Fragment,{children:[(0,G.jsx)(zu,{className:`w-4 h-4 mr-2`}),c(`common.upload`),` `,L>0?`(${L})`:``]})})]})]})})}function bU(e){if(!e)return null;let t=[e.brand,e.material,e.subtype].filter(Boolean);return t.length>0?t.join(` `):null}function xU(e,t){let n=[],r=e?.ams_extruder_map,i=!!e?.nozzles?.[1]?.nozzle_diameter||r&&Object.keys(r).length>0||(e?.vt_tray?.length??0)>1;e?.ams?.forEach(e=>{let i=e.tray.length===1;e.tray.forEach(a=>{if(a.tray_type){let o=sp(a.tray_color),s=wp(e.id,a.id,!1),c=t?.get(s);n.push({type:a.tray_type,color:o,colorName:c?.color_name?.trim()||bf(o,a.tray_sub_brands),amsId:e.id,trayId:a.id,isHt:i,isExternal:!1,label:Cp(e.id,a.id,i,!1),globalTrayId:s,trayInfoIdx:a.tray_info_idx||``,traySubBrands:a.tray_sub_brands||``,spoolName:bU(c)??void 0,extruderId:r?.[String(e.id)],remain:a.remain??-1})}})});for(let r of e?.vt_tray??[])if(r.tray_type){let a=sp(r.tray_color),o=r.id??254,s=(e?.vt_tray?.length??0)>1,c=t?.get(o);n.push({type:r.tray_type,color:a,colorName:c?.color_name?.trim()||bf(a,r.tray_sub_brands),amsId:-1,trayId:o-254,isHt:!1,isExternal:!0,label:s?o===254?`Ext-L`:`Ext-R`:`External`,globalTrayId:o,trayInfoIdx:r.tray_info_idx||``,traySubBrands:r.tray_sub_brands||``,spoolName:bU(c)??void 0,extruderId:i?255-o:void 0,remain:r.remain??-1})}return n}function SU(e,t,n,r){let i=xU(t);if(i.length!==0)return TU(wU(e,i,{},n,r,t?.fila_switch?.installed===!0))}function gke(e,t){return(0,y.useMemo)(()=>xU(e,t),[e,t])}function CU(e,t){let n=cp(t);return n?cp(e)===n||_p(e,t):!0}function wU(e,t,n,r,i,a=!1){if(!e?.filaments||e.filaments.length===0)return[];let o=new Set(Object.values(n));return e.filaments.map(e=>{let s=e.slot_id||0;if(s>0&&n[s]!==void 0){let r=n[s],i=t.find(e=>e.globalTrayId===r);if(i){let t=gp(i.type,e.type),n=CU(i.color,e.color),r;return r=t&&n?`match`:t?`type_only`:`mismatch`,{...e,loaded:i,hasFilament:!0,typeMatch:t,colorMatch:n,status:r,isManual:!0}}}let c=e.tray_info_idx||``,l=t.filter(e=>!o.has(e.globalTrayId));e.nozzle_id!=null&&!a&&(l=l.filter(t=>t.extruderId===e.nozzle_id)),r&&(l=[...l].sort((e,t)=>Np(Mp(e,i),Mp(t,i))));let u,d,f,p;if(c){let t=l.filter(e=>e.trayInfoIdx===c);t.length===1?u=t[0]:t.length>1&&(r&&t.sort((e,t)=>Np(Mp(e,i),Mp(t,i))),d=t.find(t=>gp(t.type,e.type)&&cp(t.color)===cp(e.color)),d||(f=Sp(t.filter(t=>gp(t.type,e.type)),e.color,e=>e.color)),!d&&!f&&(p=t.find(t=>gp(t.type,e.type))))}!u&&!d&&!f&&!p&&(d=l.find(t=>gp(t.type,e.type)&&cp(t.color)===cp(e.color)),d||(f=Sp(l.filter(t=>gp(t.type,e.type)),e.color,e=>e.color)),!d&&!f&&(p=l.find(t=>gp(t.type,e.type))));let m=u||d||f||p||void 0;m&&o.add(m.globalTrayId);let h=!!m,g=h,_=h&&CU(m.color,e.color),v;return v=h?_?`match`:`type_only`:`mismatch`,{...e,loaded:m,hasFilament:h,typeMatch:g,colorMatch:_,status:v,isManual:!1}})}function TU(e){if(e.length===0)return;let t=Math.max(...e.map(e=>e.slot_id||0));if(t<=0)return;let n=Array(t).fill(-1);return e.forEach(e=>{e.slot_id&&e.slot_id>0&&(n[e.slot_id-1]=e.loaded?.globalTrayId??-1)}),n}function EU(e,t,n,r,i,a){let o=gke(t,a),s=t?.fila_switch?.installed===!0,c=(0,y.useMemo)(()=>wU(e,o,n,r,i,s),[e,o,n,r,s,i]);return{loadedFilaments:o,filamentComparison:c,amsMapping:(0,y.useMemo)(()=>o.length===0?void 0:TU(c),[c,o.length]),hasTypeMismatch:c.some(e=>e.status===`mismatch`),hasColorMismatch:c.some(e=>e.status===`type_only`)}}function _ke(e,t,n,r,i){if(!e||e.length===0)return{exactMatches:0,typeOnlyMatches:0,missingTypes:0,totalSlots:0,status:`full`};let a=0,o=0,s=0,c=new Set(Object.values(n));for(let l of e){let e=l.slot_id||0;if(e>0&&n[e]!==void 0){let r=n[e],i=t.find(e=>e.globalTrayId===r);if(i){let e=gp(i.type,l.type),t=cp(i.color)===cp(l.color)||_p(i.color,l.color);e&&t?a++:e?o++:s++;continue}}let u=t.filter(e=>!c.has(e.globalTrayId));if(l.nozzle_id!=null){let e=u.filter(e=>e.extruderId===l.nozzle_id);e.length>0&&(u=e)}r&&(u=[...u].sort((e,t)=>Np(Mp(e,i),Mp(t,i))));let d=u.find(e=>gp(e.type,l.type)&&cp(e.color)===cp(l.color)),f=d?void 0:Sp(u.filter(e=>gp(e.type,l.type)),l.color,e=>e.color),p=d||f?void 0:u.find(e=>gp(e.type,l.type)),m=d??f??p;m&&c.add(m.globalTrayId),d||f?a++:p?o++:s++}let l=e.length,u=`full`;return s>0?u=`missing`:o>0&&(u=`partial`),{exactMatches:a,typeOnlyMatches:o,missingTypes:s,totalSlots:l,status:u}}function vke(e,t,n,r,i){if(!e?.filaments||e.filaments.length===0)return;let a=xU(t);if(a.length===0)return;let o=new Set(Object.values(n)),s=[];for(let t of e.filaments){let e=t.slot_id||0;if(e>0&&n[e]!==void 0){s.push({slot_id:e,globalTrayId:n[e]});continue}let c=a.filter(e=>!o.has(e.globalTrayId));if(t.nozzle_id!=null){let e=c.filter(e=>e.extruderId===t.nozzle_id);e.length>0&&(c=e)}r&&(c=[...c].sort((e,t)=>Np(Mp(e,i),Mp(t,i))));let l=c.find(e=>gp(e.type,t.type)&&cp(e.color)===cp(t.color)),u=l?void 0:Sp(c.filter(e=>gp(e.type,t.type)),t.color,e=>e.color),d=l||u?void 0:c.find(e=>gp(e.type,t.type)),f=l??u??d;f&&o.add(f.globalTrayId),s.push({slot_id:e,globalTrayId:f?.globalTrayId??-1})}let c=Math.max(...s.map(e=>e.slot_id||0));if(c<=0)return;let l=Array(c).fill(-1);return s.forEach(e=>{e.slot_id&&e.slot_id>0&&(l[e.slot_id-1]=e.globalTrayId)}),l}var DU={useDefault:!0,manualMappings:{},autoConfigured:!1};function yke(e,t,n,r,i,a,o,s){let c=xo({queries:e.map(t=>({queryKey:[`printer-status`,t],queryFn:()=>Z.getPrinterStatus(t),enabled:e.length>0,staleTime:5e3}))}),l=(0,y.useMemo)(()=>e.map((e,a)=>{let l=c[a],u=l?.data,d=t?.find(t=>t.id===e)?.name||`Printer ${e}`,f=xU(u),p=i[e]||DU,m=s?.get(e),h=Pp(o,u?.ams_filament_backup),g=SU(n,u,h,m),_=p.useDefault?r:p.manualMappings,v=vke(n,u,_,h,m),y=_ke(n?.filaments,f,_,h,m);return{printerId:e,printerName:d,status:u,isLoading:l?.isLoading??!1,loadedFilaments:f,autoMapping:g,finalMapping:v,matchStatus:y.status,exactMatches:y.exactMatches,typeOnlyMatches:y.typeOnlyMatches,missingTypes:y.missingTypes,totalSlots:y.totalSlots,config:p,inventoryByTrayId:m}}),[e,c,t,n,i,r,o,s]),u=c.some(e=>e.isLoading),d=(e,t)=>{a(n=>({...n,[e]:{...n[e]||DU,...t}}))},f=e=>{let t=l.find(t=>t.printerId===e);if(!t||!t.status||!n?.filaments)return;let r=SU(n,t.status,Pp(o,t.status?.ams_filament_backup),s?.get(e));if(!r)return;let i={};r.forEach((e,t)=>{e!==-1&&(i[t+1]=e)}),d(e,{useDefault:!1,manualMappings:i,autoConfigured:!0})};return{printerResults:l,isLoading:u,perPrinterConfigs:i,updatePrinterConfig:d,autoConfigureAll:()=>{for(let t of e)f(t)},autoConfigurePrinter:f,getFinalMapping:e=>l.find(t=>t.printerId===e)?.finalMapping,allPrintersReady:l.every(e=>e.matchStatus!==`missing`)}}var OU=`/img/bed`,bke={"cool plate":{icon:`${OU}/bed_cool.png`,label:`Cool Plate`},"pc plate":{icon:`${OU}/bed_cool.png`,label:`Cool Plate`},"cool plate (supertack)":{icon:`${OU}/bed_cool_supertack.png`,label:`Cool Plate SuperTack`},"supertack plate":{icon:`${OU}/bed_cool_supertack.png`,label:`Cool Plate SuperTack`},"bambu cool plate supertack":{icon:`${OU}/bed_cool_supertack.png`,label:`Cool Plate SuperTack`},"engineering plate":{icon:`${OU}/bed_engineering.png`,label:`Engineering Plate`},"high temp plate":{icon:`${OU}/bed_high_templ.png`,label:`High Temp Plate`},"textured pei plate":{icon:`${OU}/bed_pei.png`,label:`Textured PEI Plate`},"pei plate":{icon:`${OU}/bed_pei.png`,label:`PEI Plate`},"smooth pei plate":{icon:`${OU}/bed_pei_cool.png`,label:`Smooth PEI Plate`}};function kU(e){return e?bke[e.trim().toLowerCase()]??null:null}function xke(e,t){if(t==null)return;let n=e?.slicer_ams_mapping;if(!(!n||typeof n!=`object`)&&n.printer_id===t&&!(!Array.isArray(n.mapping)||n.mapping.length===0))return n.mapping}function Ske(e){let t=e.trim().split(/\s+/);return t.length<=1?e.trim():t.slice(1).join(` `)}function AU(e){let{data:t}=K({queryKey:[`builtin-filaments`],queryFn:()=>Z.getBuiltinFilaments(),staleTime:300*1e3}),{data:n}=K({queryKey:[`filament-id-map`],queryFn:()=>Z.getFilamentIdMap(),staleTime:300*1e3}),r=(0,y.useMemo)(()=>{let e={};for(let n of t||[])n.filament_id&&(e[n.filament_id]=n.name);for(let[t,r]of Object.entries(n||{}))t&&r&&(e[t]=r);return e},[t,n]),i=(0,y.useMemo)(()=>(e||[]).map(e=>{let t=e.tray_info_idx&&r[e.tray_info_idx]||e.type;return{resolvedName:t,materialHint:Ske(t),color:e.color}}),[e,r]),a=xo({queries:i.map(({color:e,materialHint:t})=>({queryKey:[`color-by-material`,e,t],queryFn:()=>Z.getColorByMaterial(e,t),enabled:!!e,staleTime:300*1e3}))});return i.map(({resolvedName:e,color:t},n)=>({resolvedName:e,colorLabel:(a[n]?.data?.color_name??null)||bf(t)}))}var jU=Array.from({length:6},(e,t)=>t+1),Cke=0;function MU(e){let t=new Map,n;for(let r of e??[]){if(r.id===Cke){n=r;continue}let e=r.id-15;e>=1&&e<=6&&t.set(e,r)}let r=jU.filter(e=>!t.has(e));return r.length===1&&n&&(n.nozzle_diameter||n.nozzle_type)&&t.set(r[0],n),t}function NU(e,t){if(!e||!e.nozzle_diameter&&!e.nozzle_type)return!1;let n=Number.parseFloat(e.nozzle_diameter),r=Number.parseFloat(t.nozzle_diameter);if(!Number.isFinite(n)||!Number.isFinite(r)||Math.abs(n-r)>.005)return!1;let i=(t.volume_type||``).trim().toLowerCase();if(i&&e.nozzle_type){let t=e.nozzle_type.toUpperCase().startsWith(`HH`);if(i.startsWith(`high flow`)!==t)return!1}return!0}function wke(e,t,n){let r=MU(e);return jU.map(e=>{let i=r.get(e),a=NU(i,t),o;return a||(o=i?n(`printModal.rackWrongNozzle`,{has:`${i.nozzle_diameter||`?`} ${i.nozzle_type||``}`.trim(),needs:`${t.nozzle_diameter} ${t.volume_type}`.trim()}):n(`printModal.rackEmptyPosition`)),{position:e,diameter:i?.nozzle_diameter??``,nozzleType:i?.nozzle_type??``,filamentColor:i?.filament_color??``,eligible:a,reason:o}})}function Tke(e,t,n={}){let r=MU(e),i={},a=new Set,o=[...t.keys()].filter(e=>t.get(e).on_rack).sort((e,t)=>e-t);for(let e of o){let o=n[e];if(o!=null){if(a.has(o)||!NU(r.get(o),t.get(e)))return null;i[e]=o,a.add(o)}}for(let e of o){if(i[e]!=null)continue;let n=t.get(e),o=jU.filter(e=>!a.has(e)&&NU(r.get(e),n));if(o.length===0)return null;let s=PU(n.filament_color),c=(s?o.find(e=>PU(r.get(e)?.filament_color)===s):void 0)??o[0];i[e]=c,a.add(c)}return i}function PU(e){return(e??``).trim().replace(/^#/,``).slice(0,6).toUpperCase()}function FU({printerId:e,filamentReqs:t,manualMappings:n,onManualMappingChange:r,onEstimatedCostChange:i,budgetAvailable:a,quantity:o=1,currencySymbol:s,defaultCostPerKg:c,defaultExpanded:l=!1,forceColorMatch:u,onForceColorMatchChange:d,plateLabel:f,archiveAmsMapping:p,nozzleRackChoice:m,onNozzleRackChoiceChange:h}){let{t:g}=U(),_=oo(),[v,b]=(0,y.useState)(!1),[x,S]=(0,y.useState)(l),[C,w]=(0,y.useState)(!1),T=(0,y.useRef)([]);(0,y.useEffect)(()=>{w(!1),T.current=[]},[p,f,e]);let E=()=>{if(!p||!t?.filaments)return;if(C){let e={...n};for(let t of T.current)delete e[t];r(e),T.current=[],w(!1);return}let e={...n},i=[];for(let n of t.filaments){let t=n.slot_id-1;n.slot_id>0&&t>=0&&t=0&&(e[n.slot_id]=p[t],i.push(n.slot_id))}r(e),T.current=i,w(!0)},{data:D}=K({queryKey:[`printer-status`,e],queryFn:()=>Z.getPrinterStatus(e),enabled:!!e}),{data:O}=K({queryKey:[`spool-assignments`,e],queryFn:()=>Z.getAssignments(e),enabled:!!e}),{data:k}=K({queryKey:[`settings`],queryFn:Z.getSettings}),{data:A}=K({queryKey:[`printer-inventory-remain`,e],queryFn:()=>Z.getInventoryRemain(e),enabled:!!e,staleTime:30*1e3,refetchOnMount:`always`}),j=(0,y.useMemo)(()=>{if(!A?.inventory_remain_g)return;let e=new Map;return Object.entries(A.inventory_remain_g).forEach(([t,n])=>{let r=Number(t);Number.isNaN(r)||e.set(r,n)}),e},[A]),M=(0,y.useMemo)(()=>{let e=A?.slot_materials;if(!e?.length)return;let t=new Map;return e.forEach(e=>{e.spool&&t.set(e.global_tray_id,e.spool)}),t.size>0?t:void 0},[A]),{loadedFilaments:N,filamentComparison:P,hasTypeMismatch:F,hasColorMismatch:I}=EU(t,D,n,Pp(k?.prefer_lowest_filament,D?.ams_filament_backup),j,M),L=AU(t?.filaments),R=(0,y.useMemo)(()=>{let e=new Map;for(let t of O||[]){let n=t.ams_id===255,r=wp(t.ams_id,t.tray_id,n);e.set(r,t.spool?.cost_per_kg??null)}return e},[O]),z=(0,y.useMemo)(()=>{let e=new Map;for(let t of O||[]){let n=t.ams_id===255,r=wp(t.ams_id,t.tray_id,n),i=t.spool;if(!i){e.set(r,null);continue}e.set(r,Math.max(0,Math.round((i.label_weight??0)-(i.weight_used??0))))}return e},[O]),B=(0,y.useMemo)(()=>{let e=0;for(let t of P){let n=t.loaded?.globalTrayId;if(n==null)continue;let r=R.get(n)??null??c;r>0&&(e+=t.used_grams/1e3*r)}return e},[P,R,c]),V=(0,y.useRef)(i);(0,y.useEffect)(()=>{V.current=i},[i]),(0,y.useEffect)(()=>{V.current?.(B>0?B:null)},[B]);let ee=(0,y.useMemo)(()=>Array.from(R.values()).some(e=>e!=null&&e>0),[R]),te=B*Math.max(1,o),ne=a!=null&&te>a,re=t?.filaments&&t.filaments.length>0,ie=t?.filaments?.some(e=>e.nozzle_id!=null)??!1,ae=(0,y.useMemo)(()=>{let e=new Map;for(let n of t?.filaments??[])n.group_id!=null&&n.group&&e.set(n.group_id,n.group);return e},[t]),oe=(D?.nozzle_rack?.some(e=>e.id>=16)??!1)&&[...ae.values()].some(e=>e.on_rack),se=(0,y.useMemo)(()=>oe?Tke(D?.nozzle_rack,ae,m??{})??m??{}:{},[oe,D?.nozzle_rack,ae,m]),H=(e,t)=>{h&&h({...se,[e]:t})},ce=D?.fila_switch?.installed===!0,le=D?.ams_switch_inlet,ue=e=>ce&&le?.[String(e)]||null,de=(0,y.useMemo)(()=>{if(!ce)return null;let e=new Set;for(let t of P){if(!t.loaded||t.loaded.isExternal)return null;let n=ue(t.loaded.amsId);if(!n)return null;e.add(n)}return P.length<2||e.size!==1?null:[...e][0]},[ce,le,P]);if(!re||!D)return null;let fe=F?`#f97316`:I?`#facc15`:`#00ae42`,pe=(e,t)=>{if(e>0)if(t===``){let t={...n};delete t[e],r(t)}else r({...n,[e]:parseInt(t,10)})};return(0,G.jsxs)(`div`,{className:`mb-4`,children:[(0,G.jsxs)(`button`,{type:`button`,onClick:()=>S(!x),className:`flex items-center gap-2 text-sm text-bambu-gray hover:text-white transition-colors w-full`,children:[(0,G.jsx)(Es,{className:`w-4 h-4`,fill:fe,stroke:`none`}),(0,G.jsx)(`span`,{children:f?`${g(`printModal.filamentMapping`)} — ${f}`:g(`printModal.filamentMapping`)}),F?(0,G.jsxs)(`span`,{className:`text-xs text-orange-700 dark:text-orange-400`,children:[`(`,g(`printModal.statusTypeNotFound`),`)`]}):I?(0,G.jsxs)(`span`,{className:`text-xs text-yellow-700 dark:text-yellow-400`,children:[`(`,g(`printModal.statusColorMismatch`),`)`]}):(0,G.jsxs)(`span`,{className:`text-xs text-bambu-green`,children:[`(`,g(`printModal.statusReady`),`)`]}),x?(0,G.jsx)(ms,{className:`w-4 h-4 ml-auto`}):(0,G.jsx)(ds,{className:`w-4 h-4 ml-auto`})]}),x&&(0,G.jsxs)(`div`,{className:`mt-2 bg-bambu-dark rounded-lg p-3 space-y-2`,children:[(0,G.jsxs)(`div`,{className:`flex items-center justify-between mb-2`,children:[(0,G.jsx)(`span`,{className:`text-xs text-bambu-gray`,children:g(`printModal.clickToChangeSlot`)}),(0,G.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[p&&(0,G.jsxs)(`button`,{type:`button`,onClick:E,title:g(`printModal.useArchiveMappingTooltip`),className:`flex items-center gap-1 px-2 py-0.5 text-xs rounded border transition-colors ${C?`border-bambu-green bg-bambu-green/10 text-bambu-green`:`border-bambu-gray/30 hover:border-bambu-gray hover:bg-bambu-dark-tertiary text-bambu-gray hover:text-white`}`,children:[(0,G.jsx)(us,{className:`w-3 h-3`}),(0,G.jsx)(`span`,{children:g(`printModal.useArchiveMapping`)})]}),(0,G.jsxs)(`button`,{type:`button`,onClick:async()=>{b(!0);try{await Z.refreshPrinterStatus(e),await new Promise(e=>setTimeout(e,500)),await _.refetchQueries({queryKey:[`printer-status`,e]})}finally{b(!1)}},className:`flex items-center gap-1 px-2 py-0.5 text-xs rounded border border-bambu-gray/30 hover:border-bambu-gray hover:bg-bambu-dark-tertiary transition-colors text-bambu-gray hover:text-white`,disabled:v,children:[(0,G.jsx)(Bl,{className:`w-3 h-3 ${v?`animate-spin`:``}`}),(0,G.jsx)(`span`,{children:g(`printModal.reRead`)})]})]})]}),de&&(0,G.jsxs)(`div`,{className:`flex items-start gap-1.5 rounded border border-yellow-500/40 bg-yellow-500/10 px-2 py-1.5 text-xs text-yellow-700 dark:text-yellow-400`,children:[(0,G.jsx)(Fu,{className:`w-3 h-3 mt-0.5 shrink-0`}),(0,G.jsx)(`span`,{children:g(`printModal.ftsSameInletHint`,{inlet:de})})]}),P.map((e,t)=>{let n=e.slot_id??0,r=n>0&&d!=null,{resolvedName:i,colorLabel:a}=L[t]??{resolvedName:e.type,colorLabel:bf(e.color)},[o,s]=xf({name:a,hex:e.color},{name:e.loaded?.colorName,hex:e.loaded?.color});return(0,G.jsxs)(`div`,{className:`space-y-1`,children:[(0,G.jsxs)(`div`,{className:`grid items-center gap-2 text-xs`,style:{gridTemplateColumns:oe?`16px minmax(210px, 1.4fr) auto 2fr 16px`:`16px minmax(70px, 1fr) auto 2fr 16px`},children:[(0,G.jsx)(`span`,{title:g(`printModal.requiredTooltip`,{name:i,color:o}),children:(0,G.jsx)(Es,{className:`w-3 h-3`,fill:e.color,stroke:e.color})}),(0,G.jsxs)(`span`,{className:`text-white flex items-center gap-1 min-w-0`,children:[oe&&e.group_id!=null&&e.group?e.group.on_rack?(0,G.jsx)(`select`,{value:se[e.group_id]??``,onChange:t=>H(e.group_id,Number(t.target.value)),disabled:!h,title:g(`printModal.rackPositionTooltip`),"aria-label":g(`printModal.rackPosition`),className:`shrink-0 bg-bambu-dark-tertiary text-white text-[10px] font-bold rounded px-1 py-0.5 border border-bambu-dark-tertiary focus:border-bambu-green outline-none disabled:opacity-60`,children:wke(D?.nozzle_rack,e.group,g).map(e=>(0,G.jsxs)(`option`,{value:e.position,disabled:!e.eligible,title:e.reason,children:[`R`,e.position,e.diameter?` · ${e.diameter}`:``]},e.position))}):(0,G.jsx)(`span`,{className:`inline-flex items-center justify-center w-3.5 h-3.5 rounded text-[9px] font-bold leading-none bg-bambu-gray/20 text-bambu-gray shrink-0`,title:g(`printModal.leftNozzleTooltip`),children:g(`printModal.leftNozzle`)}):ie&&e.nozzle_id!=null?(0,G.jsx)(`span`,{className:`inline-flex items-center justify-center w-3.5 h-3.5 rounded text-[9px] font-bold leading-none bg-bambu-gray/20 text-bambu-gray shrink-0`,title:e.nozzle_id===1?g(`printModal.leftNozzleTooltip`):g(`printModal.rightNozzleTooltip`),children:e.nozzle_id===1?g(`printModal.leftNozzle`):g(`printModal.rightNozzle`)}):null,(0,G.jsx)(`span`,{className:`truncate min-w-0`,title:i,children:i}),(0,G.jsxs)(`span`,{className:`text-bambu-gray shrink-0 whitespace-nowrap`,children:[`(`,e.used_grams,`g)`]})]}),(0,G.jsx)(`span`,{className:`text-bambu-gray`,children:`→`}),(0,G.jsxs)(`select`,{value:e.loaded?.globalTrayId??``,onChange:e=>pe(n,e.target.value),className:`flex-1 px-2 py-1 rounded border text-xs bg-bambu-dark-secondary focus:outline-none focus:ring-1 focus:ring-bambu-green ${e.status===`match`?`border-bambu-green/50 text-bambu-green`:e.status===`type_only`?`border-yellow-500 dark:border-yellow-400/50 text-yellow-700 dark:text-yellow-400`:`border-orange-500 dark:border-orange-400/50 text-orange-700 dark:text-orange-400`} ${e.isManual?`ring-1 ring-blue-400/50`:``}`,title:e.isManual?g(`printModal.manuallySelected`):g(`printModal.autoMatched`),children:[(0,G.jsxs)(`option`,{value:``,className:`bg-bambu-dark text-bambu-gray`,children:[`-- `,g(`printModal.selectSlot`),` --`]}),N.map(e=>{let t=z.get(e.globalTrayId),n=t==null?``:g(`printModal.slotRemainingShort`,{grams:t,defaultValue:` - ${t}g left`}),r=ue(e.amsId),i=r==null?``:` [${lp[r]}]`;return(0,G.jsxs)(`option`,{value:e.globalTrayId,className:`bg-bambu-dark text-white`,children:[e.label,`: `,e.spoolName||e.traySubBrands||e.type,` (`,e.colorName,`)`,n,i]},e.globalTrayId)})]}),e.status===`match`?(0,G.jsx)(us,{className:`w-3 h-3 text-bambu-green`}):e.status===`type_only`?(0,G.jsx)(`span`,{title:o&&s?g(`printModal.sameTypeDifferentColorDetail`,{required:o,loaded:s}):g(`printModal.sameTypeDifferentColor`),children:(0,G.jsx)(Fu,{className:`w-3 h-3 text-yellow-600 dark:text-yellow-400`})}):(0,G.jsx)(`span`,{title:g(`printModal.filamentTypeNotLoaded`),children:(0,G.jsx)(Fu,{className:`w-3 h-3 text-orange-600 dark:text-orange-400`})})]}),r&&(0,G.jsxs)(`label`,{className:`inline-flex items-center gap-1.5 text-xs text-bambu-gray cursor-pointer select-none pl-5`,children:[(0,G.jsx)(`input`,{type:`checkbox`,checked:u?.[n]??!1,onChange:e=>d(n,e.target.checked),className:`accent-bambu-green w-3 h-3`}),(0,G.jsx)(Sl,{className:`w-3 h-3`}),g(`printModal.forceColorMatch`)]})]},t)}),(0,G.jsxs)(`div`,{className:`text-xs text-bambu-gray`,children:[g(`printModal.totalCost`),` `,(0,G.jsx)(`span`,{className:`text-white`,children:B>0||ee?`${s}${B.toFixed(2)}`:`N/A`}),o>1&&B>0&&(0,G.jsx)(`span`,{className:`ml-2`,children:g(`printModal.totalCostForQuantity`,`total: {{cost}}`,{cost:`${s}${te.toFixed(2)}`})})]}),ne&&(0,G.jsx)(`p`,{className:`text-xs text-red-400 mt-2`,children:g(`printModal.insufficientBudget`,`Insufficient budget for this cost center.`)}),F&&(0,G.jsx)(`p`,{className:`text-xs text-orange-700 dark:text-orange-400 mt-2`,children:g(`printModal.requiredTypeNotInPrinter`)})]})]})}function IU({filamentReqs:e,availableFilaments:t,overrides:n,onChange:r,forceColorMatch:i,onForceColorMatchChange:a,plateLabel:o,showHint:s=!0}){let{t:c}=U(),l=AU(e?.filaments),u=(0,y.useMemo)(()=>{let e={};for(let n of t){let t=hp(n.type);e[t]||(e[t]=[]),e[t].push(n)}return e},[t]),d=e?.filaments;if(!d||d.length===0||t.length===0)return null;let f=(e,t)=>{if(t===``){let t={...n};delete t[e],r(t)}else{let[i,a]=t.split(`|`);r({...n,[e]:{type:i,color:a}})}};return(0,G.jsxs)(`div`,{className:`mb-4`,children:[(0,G.jsx)(`div`,{className:`flex items-center gap-2 text-sm text-bambu-gray mb-2`,children:(0,G.jsx)(`span`,{children:o?`${c(`printModal.filamentOverride`)} — ${o}`:c(`printModal.filamentOverride`)})}),s&&(0,G.jsx)(`p`,{className:`text-xs text-bambu-gray mb-2`,children:c(`printModal.filamentOverrideHint`)}),(0,G.jsx)(`div`,{className:`bg-bambu-dark rounded-lg p-3 space-y-2`,children:d.map((e,t)=>{let r=n[e.slot_id],o=!!r,s=u[hp(e.type)]||[],d=e.nozzle_id==null?s:s.filter(t=>t.extruder_id==null||t.extruder_id===e.nozzle_id),{resolvedName:p,colorLabel:m}=l[t]??{resolvedName:e.type,colorLabel:bf(e.color)};return(0,G.jsxs)(`div`,{className:`space-y-1`,children:[(0,G.jsxs)(`div`,{className:`grid items-center gap-2 text-xs`,style:{gridTemplateColumns:`16px minmax(70px, 1fr) auto 2fr 20px`},children:[(0,G.jsx)(`span`,{title:`${c(`printModal.originalFilament`)}: ${p} - ${m}`,children:(0,G.jsx)(Es,{className:`w-3 h-3`,fill:e.color,stroke:e.color})}),(0,G.jsxs)(`span`,{className:`text-white truncate`,children:[p,` `,(0,G.jsxs)(`span`,{className:`text-bambu-gray`,children:[`(`,e.used_grams,`g)`]})]}),(0,G.jsx)(`span`,{className:`text-bambu-gray`,children:`→`}),(0,G.jsxs)(`select`,{value:o?`${r.type}|${r.color}`:``,onChange:t=>f(e.slot_id,t.target.value),disabled:d.length===0,className:`flex-1 px-2 py-1 rounded border text-xs bg-bambu-dark-secondary focus:outline-none focus:ring-1 focus:ring-bambu-green ${o?`border-blue-500/50 dark:border-blue-400/50 text-blue-700 dark:text-blue-400`:`border-bambu-gray/30 text-bambu-gray`}`,children:[(0,G.jsxs)(`option`,{value:``,className:`bg-bambu-dark text-bambu-gray`,children:[c(`printModal.originalFilament`),`: `,p,` (`,m,`)`]}),d.map((e,t)=>(0,G.jsxs)(`option`,{value:`${e.type}|${e.color}`,className:`bg-bambu-dark text-white`,children:[e.tray_sub_brands||e.type,` (`,bf(e.color,e.tray_sub_brands),`)`]},`${e.type}-${e.color}-${e.tray_sub_brands}-${t}`))]}),o?(0,G.jsx)(`button`,{type:`button`,onClick:()=>f(e.slot_id,``),className:`text-bambu-gray hover:text-white transition-colors`,title:c(`printModal.resetToOriginal`),children:(0,G.jsx)(Hl,{className:`w-3 h-3`})}):(0,G.jsx)(`span`,{className:`w-3`})]}),(0,G.jsxs)(`label`,{className:`inline-flex items-center gap-1.5 text-xs text-bambu-gray cursor-pointer select-none pl-5`,children:[(0,G.jsx)(`input`,{type:`checkbox`,checked:i?.[e.slot_id]??!1,onChange:t=>a?.(e.slot_id,t.target.checked),className:`accent-bambu-green w-3 h-3`}),(0,G.jsx)(Sl,{className:`w-3 h-3`}),c(`printModal.forceColorMatch`)]})]},e.slot_id)})})]})}function Eke({plates:e,isMultiPlate:t,selectedPlates:n,onToggle:r,onSelectAll:i,onDeselectAll:a,multiSelect:o,quantities:s,onQuantityChange:c}){let{t:l}=U();if(!t||e.length<=1)return null;let u=n.size===e.length,d=!!s&&!!c,f=d?e.reduce((e,t)=>n.has(t.index)?e+(s[t.index]??1):e,0):0;return(0,G.jsxs)(`div`,{className:`mb-4`,children:[(0,G.jsxs)(`div`,{className:`flex items-center gap-2 mb-2`,children:[(0,G.jsx)(Kc,{className:`w-4 h-4 text-bambu-gray`}),(0,G.jsxs)(`span`,{className:`text-sm text-bambu-gray`,children:[`Select Plate`,o?`s`:``,` to Print`]}),n.size===0&&(0,G.jsxs)(`span`,{className:`text-xs text-orange-700 dark:text-orange-400 flex items-center gap-1`,children:[(0,G.jsx)(Fu,{className:`w-3 h-3`}),`Selection required`]}),o&&i&&a&&(0,G.jsx)(`button`,{type:`button`,onClick:u?a:i,className:`ml-auto text-xs px-2 py-0.5 rounded-full border transition-colors ${u?`border-bambu-green bg-bambu-green/10 text-bambu-green`:`border-bambu-dark-tertiary text-bambu-gray hover:border-bambu-gray`}`,children:u?l(`queue.deselectAll`):l(`queue.selectAllPlates`,{count:e.length})})]}),(0,G.jsx)(`div`,{className:`grid grid-cols-2 gap-2`,children:e.map(e=>{let t=n.has(e.index);return(0,G.jsxs)(`div`,{className:`flex items-center gap-2 p-2 rounded-lg border transition-colors ${t?`border-bambu-green bg-bambu-green/10`:`border-bambu-dark-tertiary bg-bambu-dark hover:border-bambu-gray`}`,children:[(0,G.jsxs)(`button`,{type:`button`,onClick:()=>r(e.index),className:`flex items-center gap-2 text-left min-w-0 flex-1`,children:[o&&(t?(0,G.jsx)(gu,{className:`w-4 h-4 text-bambu-green flex-shrink-0`}):(0,G.jsx)(vu,{className:`w-4 h-4 text-bambu-gray flex-shrink-0`})),e.has_thumbnail&&e.thumbnail_url!=null?(0,G.jsx)(`img`,{src:fd(e.thumbnail_url),alt:`Plate ${e.index}`,className:`w-10 h-10 rounded object-cover bg-bambu-dark-tertiary`}):(0,G.jsx)(`div`,{className:`w-10 h-10 rounded bg-bambu-dark-tertiary flex items-center justify-center`,children:(0,G.jsx)(Kc,{className:`w-5 h-5 text-bambu-gray`})}),(0,G.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,G.jsx)(`p`,{className:`text-sm text-white font-medium truncate`,children:e.name||`Plate ${e.index}`}),(0,G.jsxs)(`p`,{className:`text-xs text-bambu-gray truncate`,children:[e.objects.length>0?e.objects.slice(0,3).join(`, `)+(e.objects.length>3?`...`:``):`${e.filaments.length} filament${e.filaments.length===1?``:`s`}`,e.print_time_seconds==null?``:` • ${np(e.print_time_seconds)}`]}),(()=>{let t=kU(e.bed_type);return t?(0,G.jsxs)(`p`,{className:`text-xs text-bambu-gray flex items-center gap-1 mt-0.5 truncate`,title:t.label,children:[(0,G.jsx)(`img`,{src:t.icon,alt:``,className:`w-3.5 h-3.5 object-contain flex-shrink-0`}),(0,G.jsx)(`span`,{className:`truncate`,children:t.label})]}):null})()]}),!o&&t&&(0,G.jsx)(us,{className:`w-4 h-4 text-bambu-green flex-shrink-0`})]}),d&&t&&(0,G.jsxs)(`div`,{className:`flex items-center gap-1 flex-shrink-0`,children:[(0,G.jsx)(`span`,{className:`text-xs text-bambu-gray`,"aria-hidden":`true`,children:`×`}),(0,G.jsx)(`input`,{type:`number`,min:1,max:999,value:s[e.index]??1,"aria-label":l(`queue.plateQuantityLabel`,{plate:e.name||l(`queue.plateNumber`,{index:e.index})}),onChange:t=>c(e.index,Math.max(1,Math.min(999,parseInt(t.target.value)||1))),className:`w-14 px-1.5 py-1 text-sm bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-center focus:outline-none focus:ring-1 focus:ring-bambu-green`})]})]},e.index)})}),d&&f>n.size&&(0,G.jsx)(`p`,{className:`text-xs text-bambu-gray mt-2`,children:l(`queue.plateQuantityTotal`,{count:f})})]})}var Dke=new Set([`IDLE`,`FINISH`,`FAILED`]);function Oke({printerResult:e,filamentReqs:t,onUpdateConfig:n}){let r=oo(),[i,a]=(0,y.useState)(!1),o=(t,r)=>{if(t<=0)return;let i={...e.config.manualMappings};r===``?delete i[t]:i[t]=parseInt(r,10),n({useDefault:!1,manualMappings:i,autoConfigured:!1})},s=async()=>{a(!0);try{await Z.refreshPrinterStatus(e.printerId),await new Promise(e=>setTimeout(e,500)),await r.refetchQueries({queryKey:[`printer-status`,e.printerId]})}finally{a(!1)}},c=t.map(t=>{let n=t.slot_id||0,i=e.config.manualMappings[n],a,o=!1;if(i!==void 0)a=e.loadedFilaments.find(e=>e.globalTrayId===i),o=!0;else{let n=new Set(Object.values(e.config.manualMappings)),i=r.getQueryData([`settings`]);a=Fp(t,e.loadedFilaments,n,Pp(i?.prefer_lowest_filament,e.status?.ams_filament_backup),e.inventoryByTrayId)}let s=`mismatch`;if(a){let e=gp(a.type,t.type),n=cp(a.color)===cp(t.color)||_p(a.color,t.color);e&&n?s=`match`:e&&(s=`type_only`)}return{req:t,loaded:a,status:s,isManual:o}});return(0,G.jsxs)(`div`,{className:`mt-2 bg-bambu-dark rounded-lg p-3 space-y-2`,children:[(0,G.jsxs)(`div`,{className:`flex items-center justify-between mb-2`,children:[(0,G.jsx)(`span`,{className:`text-xs text-bambu-gray`,children:`Custom slot mapping`}),(0,G.jsxs)(`button`,{type:`button`,onClick:s,className:`flex items-center gap-1 px-2 py-0.5 text-xs rounded border border-bambu-gray/30 hover:border-bambu-gray hover:bg-bambu-dark-tertiary transition-colors text-bambu-gray hover:text-white`,disabled:i,children:[(0,G.jsx)(Bl,{className:`w-3 h-3 ${i?`animate-spin`:``}`}),(0,G.jsx)(`span`,{children:`Re-read`})]})]}),c.map(({req:t,loaded:n,status:r,isManual:i},a)=>(0,G.jsxs)(`div`,{className:`grid items-center gap-2 text-xs`,style:{gridTemplateColumns:`16px minmax(70px, 1fr) auto 2fr 16px`},children:[(0,G.jsx)(`span`,{title:`Required: ${t.type} - ${bf(t.color)}`,children:(0,G.jsx)(Es,{className:`w-3 h-3`,fill:t.color,stroke:t.color})}),(0,G.jsxs)(`span`,{className:`text-white flex items-center gap-1 min-w-0`,children:[(0,G.jsx)(`span`,{className:`truncate min-w-0`,title:t.type,children:t.type}),(0,G.jsxs)(`span`,{className:`text-bambu-gray shrink-0 whitespace-nowrap`,children:[`(`,t.used_grams,`g)`]})]}),(0,G.jsx)(`span`,{className:`text-bambu-gray`,children:`→`}),(0,G.jsxs)(`select`,{value:n?.globalTrayId??``,onChange:e=>o(t.slot_id||0,e.target.value),className:`flex-1 px-2 py-1 rounded border text-xs bg-bambu-dark-secondary focus:outline-none focus:ring-1 focus:ring-bambu-green ${r===`match`?`border-bambu-green/50 text-bambu-green`:r===`type_only`?`border-yellow-500 dark:border-yellow-400/50 text-yellow-700 dark:text-yellow-400`:`border-orange-500 dark:border-orange-400/50 text-orange-700 dark:text-orange-400`} ${i?`ring-1 ring-blue-400/50`:``}`,title:i?`Manually selected`:`Auto-matched`,children:[(0,G.jsx)(`option`,{value:``,className:`bg-bambu-dark text-bambu-gray`,children:`-- Select slot --`}),Ip(e.loadedFilaments,t.nozzle_id).map(e=>(0,G.jsxs)(`option`,{value:e.globalTrayId,className:`bg-bambu-dark text-white`,children:[e.label,`: `,e.traySubBrands||e.type,` (`,e.colorName,`)`]},e.globalTrayId))]}),r===`match`?(0,G.jsx)(us,{className:`w-3 h-3 text-bambu-green`}):r===`type_only`?(0,G.jsx)(`span`,{title:`Same type, different color`,children:(0,G.jsx)(Fu,{className:`w-3 h-3 text-yellow-600 dark:text-yellow-400`})}):(0,G.jsx)(`span`,{title:`Filament type not loaded`,children:(0,G.jsx)(Fu,{className:`w-3 h-3 text-orange-600 dark:text-orange-400`})})]},a))]})}function kke({printers:e,selectedPrinterIds:t,onMultiSelect:n,isLoading:r=!1,allowMultiple:i=!1,showInactive:a=!1,disableBusy:o=!1,printerMappingResults:s,filamentReqs:c,onAutoConfigurePrinter:l,onUpdatePrinterConfig:u,assignmentMode:d=`printer`,onAssignmentModeChange:f,targetModel:p,onTargetModelChange:m,targetLocation:h,onTargetLocationChange:g,slicedForModel:_}){let[v,b]=(0,y.useState)(!1),x=a?e:e.filter(e=>e.is_active),S=xo({queries:x.map(e=>({queryKey:[`printerStatus`,e.id],queryFn:()=>Z.getPrinterStatus(e.id),staleTime:5e3}))}),C=(0,y.useMemo)(()=>{let e=new Map;return x.forEach((t,n)=>{let r=S[n];r?.data&&e.set(t.id,r.data)}),e},[x,S]),w=e=>{let t=C.get(e);return t?t.connected?!Dke.has(t.state??``):!0:!1},T=e=>{let t=C.get(e);if(!t)return null;if(!t.connected)return`Offline`;let n=t.state;return n?n===`RUNNING`?t.stg_cur_name||`Printing`:n===`PREPARE`?`Preparing`:n===`PAUSE`?`Paused`:n===`IDLE`?`Idle`:n===`FINISH`?`Finished`:n===`FAILED`?`Failed`:n:null},E=(0,y.useMemo)(()=>{if(d!==`printer`||!_||v)return x;let e=x.filter(e=>e.model===_);return e.length>0?e:x},[x,d,_,v]),D=x.length-E.length,O=(0,y.useMemo)(()=>{let e=x.map(e=>e.model).filter(e=>!!e);return[...new Set(e)].sort()},[x]),k=(0,y.useMemo)(()=>{if(!p)return[];let e=x.filter(e=>e.model===p&&e.location).map(e=>e.location).filter(e=>!!e);return[...new Set(e)].sort()},[x,p]),A=f&&m&&O.length>0,j=i&&t.length>1&&s&&c?.filaments&&c.filaments.length>0&&l&&u;if(r)return(0,G.jsx)(`div`,{className:`flex justify-center py-8`,children:(0,G.jsx)(Y,{className:`w-6 h-6 text-bambu-green animate-spin`})});if(E.length===0)return(0,G.jsxs)(`div`,{className:`flex items-center gap-2 text-red-700 dark:text-red-400 text-sm mb-4`,children:[(0,G.jsx)(_s,{className:`w-4 h-4`}),`No `,a?``:`active `,`printers available`]});let M=e=>{o&&w(e)||(i?t.includes(e)?n(t.filter(t=>t!==e)):n([...t,e]):n([e]))},N=()=>{n((o?E.filter(e=>!w(e.id)):E).map(e=>e.id))},P=()=>{n([])},F=(e,t,n)=>{n.stopPropagation(),!(!l||!u)&&(t?l(e):u(e,{useDefault:!0,manualMappings:{},autoConfigured:!1}))},I=e=>t.includes(e),L=t.length,R=e=>s?.find(t=>t.printerId===e);return(0,G.jsxs)(`div`,{className:`space-y-2 mb-6`,children:[A&&(0,G.jsxs)(`div`,{className:`flex gap-2 mb-4`,children:[(0,G.jsxs)(`button`,{type:`button`,onClick:()=>{f(`printer`),m(null)},className:`flex-1 flex items-center justify-center gap-2 px-3 py-2 rounded-lg border transition-colors ${d===`printer`?`border-bambu-green bg-bambu-green/10 text-white`:`border-bambu-dark-tertiary bg-bambu-dark text-bambu-gray hover:border-bambu-gray`}`,children:[(0,G.jsx)(Il,{className:`w-4 h-4`}),(0,G.jsx)(`span`,{className:`text-sm`,children:`Specific Printer`})]}),(0,G.jsxs)(`button`,{type:`button`,onClick:()=>{f(`model`),n([]),m(_&&O.includes(_)?_:null)},className:`flex-1 flex items-center justify-center gap-2 px-3 py-2 rounded-lg border transition-colors ${d===`model`?`border-bambu-green bg-bambu-green/10 text-white`:`border-bambu-dark-tertiary bg-bambu-dark text-bambu-gray hover:border-bambu-gray`}`,children:[(0,G.jsx)(Vu,{className:`w-4 h-4`}),(0,G.jsxs)(`span`,{className:`text-sm`,children:[`Any `,(d===`model`?p:null)||_||`Model`]})]})]}),d===`model`&&A&&(0,G.jsxs)(`div`,{className:`space-y-3 mb-4`,children:[(0,G.jsxs)(`div`,{children:[(0,G.jsxs)(`label`,{className:`block text-xs text-bambu-gray mb-1`,children:[`Target Model`,_&&(0,G.jsxs)(`span`,{className:`ml-2 text-bambu-gray/70`,children:[`(sliced for `,_,`)`]})]}),(0,G.jsxs)(`select`,{value:p||``,onChange:e=>{m(e.target.value||null),g&&g(null)},className:`w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none text-sm`,children:[(0,G.jsx)(`option`,{value:``,children:`Select a model...`}),O.map(e=>{let t=hm(_,e);return(0,G.jsxs)(`option`,{value:e,disabled:!t,children:[e,t?``:` — incompatible with ${_} G-code`]},e)})]})]}),_&&p&&p!==_&&(hm(_,p)?(0,G.jsxs)(`div`,{className:`p-3 bg-yellow-50 dark:bg-yellow-500/10 border border-yellow-300 dark:border-yellow-500/30 rounded-lg flex items-center gap-2`,children:[(0,G.jsx)(Fu,{className:`w-4 h-4 text-yellow-600 dark:text-yellow-400 flex-shrink-0`}),(0,G.jsxs)(`span`,{className:`text-sm text-yellow-700 dark:text-yellow-400`,children:[`File was sliced for `,_,`, but will be dispatched to a `,p,` printer`]})]}):(0,G.jsxs)(`div`,{className:`p-3 bg-red-50 dark:bg-red-500/10 border border-red-300 dark:border-red-500/30 rounded-lg flex items-center gap-2`,children:[(0,G.jsx)(_s,{className:`w-4 h-4 text-red-600 dark:text-red-400 flex-shrink-0`}),(0,G.jsxs)(`span`,{className:`text-sm text-red-700 dark:text-red-400`,children:[`File was sliced for `,_,` and cannot be dispatched to `,p,` printers — select a compatible model`]})]})),p&&k.length>0&&g&&(0,G.jsxs)(`div`,{children:[(0,G.jsx)(`label`,{className:`block text-xs text-bambu-gray mb-1`,children:`Location Filter (optional)`}),(0,G.jsxs)(`select`,{value:h||``,onChange:e=>g(e.target.value||null),className:`w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none text-sm`,children:[(0,G.jsx)(`option`,{value:``,children:`Any location`}),k.map(e=>(0,G.jsx)(`option`,{value:e,children:e},e))]})]}),p&&(0,G.jsxs)(`p`,{className:`text-xs text-bambu-gray`,children:[`Scheduler will assign to first available idle `,p,` printer`,h?` in ${h}`:``]})]}),d===`printer`&&i&&E.length>1&&(0,G.jsxs)(`div`,{className:`flex items-center justify-between text-xs text-bambu-gray mb-2`,children:[(0,G.jsx)(`span`,{children:L===0?`Select printers`:`${L} printer${L===1?``:`s`} selected`}),(0,G.jsxs)(`div`,{className:`flex gap-2`,children:[L0&&(0,G.jsx)(`button`,{type:`button`,onClick:P,className:`text-bambu-gray hover:text-white transition-colors`,children:`Clear`})]})]}),d===`printer`&&E.map(e=>{let t=I(e.id),n=R(e.id),r=n&&!n.config.useDefault,a=w(e.id),s=o&&a,d=T(e.id);return(0,G.jsxs)(`div`,{children:[(0,G.jsxs)(`button`,{type:`button`,onClick:()=>M(e.id),disabled:s,className:`w-full flex items-center gap-3 p-3 rounded-lg border transition-colors ${s?`border-bambu-dark-tertiary bg-bambu-dark opacity-50 cursor-not-allowed`:t?`border-bambu-green bg-bambu-green/10`:`border-bambu-dark-tertiary bg-bambu-dark hover:border-bambu-gray`} ${e.is_active?``:`opacity-60`}`,children:[(0,G.jsx)(`div`,{className:`p-2 rounded-lg ${s?`bg-bambu-dark-tertiary`:t?`bg-bambu-green/20`:`bg-bambu-dark-tertiary`}`,children:(0,G.jsx)(Il,{className:`w-5 h-5 ${s?`text-bambu-gray/50`:t?`text-bambu-green`:`text-bambu-gray`}`})}),(0,G.jsxs)(`div`,{className:`text-left flex-1`,children:[(0,G.jsxs)(`p`,{className:`font-medium ${s?`text-bambu-gray`:`text-white`}`,children:[e.name,!e.is_active&&(0,G.jsx)(`span`,{className:`text-bambu-gray text-xs ml-2`,children:`(inactive)`})]}),(0,G.jsxs)(`p`,{className:`text-xs text-bambu-gray`,children:[e.model||`Unknown model`,` • `,e.ip_address]})]}),d&&(0,G.jsx)(`span`,{className:`text-xs px-2 py-0.5 rounded-full ${a?`bg-yellow-100 dark:bg-yellow-500/20 text-yellow-700 dark:text-yellow-400`:`bg-bambu-green/20 text-bambu-green`}`,children:d}),i&&(0,G.jsx)(`div`,{className:`w-5 h-5 rounded border-2 flex items-center justify-center transition-colors ${s?`border-bambu-gray/30`:t?`bg-bambu-green border-bambu-green`:`border-bambu-gray/50`}`,children:t&&(0,G.jsx)(us,{className:`w-3 h-3 text-white`})})]}),t&&j&&n&&(0,G.jsxs)(`div`,{className:`ml-4 mt-2 mb-3`,children:[(0,G.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,G.jsxs)(`label`,{className:`flex items-center gap-2 cursor-pointer`,onClick:e=>e.stopPropagation(),children:[(0,G.jsx)(`input`,{type:`checkbox`,checked:r,onChange:t=>F(e.id,t.target.checked,t),className:`w-3.5 h-3.5 rounded border-bambu-gray/30 bg-bambu-dark-secondary text-bambu-green focus:ring-bambu-green focus:ring-offset-0`}),(0,G.jsx)(`span`,{className:`text-xs text-bambu-gray`,children:`Custom mapping`})]}),(0,G.jsxs)(`span`,{className:`text-xs ml-2 ${n.matchStatus===`full`?`text-bambu-green`:n.matchStatus===`partial`?`text-yellow-700 dark:text-yellow-400`:`text-orange-700 dark:text-orange-400`}`,children:[`(`,n.exactMatches,`/`,n.totalSlots,` matched)`]}),n.isLoading&&(0,G.jsx)(Bl,{className:`w-3 h-3 text-bambu-gray animate-spin`}),r&&(0,G.jsxs)(`button`,{type:`button`,onClick:t=>{t.stopPropagation(),l(e.id)},className:`ml-auto flex items-center gap-1 px-2 py-0.5 text-xs rounded border border-bambu-gray/30 hover:border-bambu-gray hover:bg-bambu-dark-tertiary transition-colors text-bambu-gray hover:text-white`,children:[(0,G.jsx)(qu,{className:`w-3 h-3`}),`Auto`]})]}),r&&(0,G.jsx)(Oke,{printerResult:n,filamentReqs:c.filaments,onUpdateConfig:t=>u(e.id,t)})]})]},e.id)}),d===`printer`&&D>0&&!v&&(0,G.jsxs)(`button`,{type:`button`,onClick:()=>b(!0),className:`text-xs text-bambu-gray hover:text-white transition-colors mt-2 flex items-center gap-1`,children:[(0,G.jsx)(Fu,{className:`w-3 h-3 text-yellow-600 dark:text-yellow-400`}),D,` other printer`,D>1?`s`:``,` hidden (different model) —`,(0,G.jsx)(`span`,{className:`underline`,children:`show all`})]}),d===`printer`&&v&&_&&(0,G.jsx)(`button`,{type:`button`,onClick:()=>b(!1),className:`text-xs text-bambu-gray hover:text-white transition-colors mt-2`,children:(0,G.jsxs)(`span`,{className:`underline`,children:[`Show only `,_,` printers`]})}),d===`printer`&&L===0&&(0,G.jsxs)(`p`,{className:`text-xs text-orange-700 dark:text-orange-400 mt-1 flex items-center gap-1`,children:[(0,G.jsx)(_s,{className:`w-3 h-3`}),`Select at least one printer`]}),d===`model`&&!p&&(0,G.jsxs)(`p`,{className:`text-xs text-orange-700 dark:text-orange-400 mt-1 flex items-center gap-1`,children:[(0,G.jsx)(_s,{className:`w-3 h-3`}),`Select a target printer model`]})]})}var LU=[`off`,`auto`,`on`],RU={off:`bg-red-500 text-white`,auto:`bg-blue-500 text-white`,on:`bg-bambu-green text-white`},Ake=[`off`,`on`];function jke({options:e,onChange:t,defaultExpanded:n=!1,showDualNozzleOptions:r=!1}){let{t:i}=U(),[a,o]=(0,y.useState)(n),s=[{key:`bed_levelling`,label:i(`settings.defaultBedLevelling`),desc:i(`settings.defaultBedLevellingDesc`),tristate:!0},{key:`flow_cali`,label:i(`settings.defaultFlowCali`),desc:i(`settings.defaultFlowCaliDesc`),tristate:!0},{key:`vibration_cali`,label:i(`settings.defaultVibrationCali`),desc:i(`settings.defaultVibrationCaliDesc`)},{key:`layer_inspect`,label:i(`settings.defaultLayerInspect`),desc:i(`settings.defaultLayerInspectDesc`)},{key:`timelapse`,label:i(`settings.defaultTimelapse`),desc:i(`settings.defaultTimelapseDesc`)},{key:`nozzle_offset_cali`,label:i(`settings.defaultNozzleOffsetCali`),desc:i(`settings.defaultNozzleOffsetCaliDesc`),dualNozzleOnly:!0,tristate:!0}].filter(e=>!e.dualNozzleOnly||r),c=(n,r)=>{t({...e,[n]:r})},l=(n,r)=>{t({...e,[n]:r})},u=n=>{t({...e,preheat_override:n,...n===`off`?{preheat_chamber_target_override:null}:{}})},d=n=>{if(n===``){t({...e,preheat_chamber_target_override:null});return}let r=parseInt(n,10);Number.isNaN(r)||t({...e,preheat_chamber_target_override:Math.max(0,Math.min(65,r))})};return(0,G.jsxs)(`div`,{className:`mb-4`,children:[(0,G.jsxs)(`button`,{type:`button`,onClick:()=>o(!a),className:`flex items-center gap-2 text-sm text-bambu-gray hover:text-white transition-colors w-full`,children:[(0,G.jsx)(tu,{className:`w-4 h-4`}),(0,G.jsx)(`span`,{children:i(`queue.bulkEdit.printOptions`)}),a?(0,G.jsx)(ms,{className:`w-4 h-4 ml-auto`}):(0,G.jsx)(ds,{className:`w-4 h-4 ml-auto`})]}),a&&(0,G.jsxs)(`div`,{className:`mt-2 bg-bambu-dark rounded-lg p-3 space-y-2`,children:[s.map(({key:t,label:n,desc:r,tristate:a})=>a?(0,G.jsxs)(`div`,{className:`flex items-center justify-between gap-3`,children:[(0,G.jsxs)(`div`,{children:[(0,G.jsx)(`span`,{className:`text-sm text-white`,children:n}),(0,G.jsx)(`p`,{className:`text-xs text-bambu-gray`,children:r})]}),(0,G.jsx)(`div`,{className:`flex gap-1 shrink-0`,children:LU.map(n=>(0,G.jsx)(`button`,{type:`button`,onClick:()=>l(t,n),className:`px-2.5 py-1 text-xs rounded transition-colors ${e[t]===n?RU[n]:`bg-bambu-dark-tertiary text-bambu-gray hover:text-white`}`,children:i(`settings.calibrationMode_${n}`)},n))})]},t):(0,G.jsxs)(`div`,{className:`flex items-center justify-between gap-3`,children:[(0,G.jsxs)(`div`,{children:[(0,G.jsx)(`span`,{className:`text-sm text-white`,children:n}),(0,G.jsx)(`p`,{className:`text-xs text-bambu-gray`,children:r})]}),(0,G.jsx)(`div`,{className:`flex gap-1 shrink-0`,children:Ake.map(n=>(0,G.jsx)(`button`,{type:`button`,onClick:()=>c(t,n===`on`),className:`px-2.5 py-1 text-xs rounded transition-colors ${(e[t]?`on`:`off`)===n?RU[n]:`bg-bambu-dark-tertiary text-bambu-gray hover:text-white`}`,children:i(`settings.calibrationMode_${n}`)},n))})]},t)),(0,G.jsxs)(`div`,{className:`pt-2 mt-1 border-t border-bambu-dark-tertiary/60`,children:[(0,G.jsxs)(`div`,{className:`flex items-center gap-2 mb-1.5`,children:[(0,G.jsx)(pc,{className:`w-3.5 h-3.5 text-amber-600 dark:text-amber-400`}),(0,G.jsx)(`span`,{className:`text-sm text-white`,children:i(`settings.preheatTitle`,`Preheat & Heat Soak`)})]}),(0,G.jsx)(`p`,{className:`text-xs text-bambu-gray mb-2`,children:i(`settings.preheatPerItemDesc`,`Heat the bed and chamber before this print starts. Defaults to the global Settings → Workflow toggle.`)}),(0,G.jsx)(`div`,{className:`flex gap-1.5 mb-2`,children:[`inherit`,`on`,`off`].map(t=>(0,G.jsx)(`button`,{type:`button`,onClick:()=>u(t),className:`flex-1 px-2 py-1.5 text-xs rounded transition-colors ${e.preheat_override===t?`bg-bambu-green text-white`:`bg-bambu-dark-tertiary text-bambu-gray hover:text-white`}`,children:i(`settings.preheatOverride_${t}`,t===`inherit`?`Inherit`:t===`on`?`On`:`Off`)},t))}),e.preheat_override!==`off`&&(0,G.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,G.jsx)(`label`,{className:`text-xs text-bambu-gray flex-1`,children:i(`settings.preheatTargetOverride`,`Chamber target override (°C, blank = filament default)`)}),(0,G.jsx)(`input`,{type:`number`,min:0,max:65,step:1,value:e.preheat_chamber_target_override??``,onChange:e=>d(e.target.value),placeholder:`—`,className:`w-16 px-2 py-1 bg-bambu-dark-tertiary border border-bambu-dark-tertiary rounded text-white text-xs text-right focus:outline-none focus:border-bambu-green`})]})]})]})]})}function Mke({options:e,onChange:t,dateFormat:n=`system`,timeFormat:r=`system`,canControlPrinter:i=!0,showStagger:a=!1,printerCount:o=0,hasGcodeSnippets:s=!1}){let{t:c}=U(),[l,u]=(0,y.useState)(``),[d,f]=(0,y.useState)(``),[p,m]=(0,y.useState)(!0),[h,g]=(0,y.useState)(!0),_=(0,y.useRef)(null),v=(0,y.useRef)(!1);(0,y.useEffect)(()=>{if(e.scheduleType!==`scheduled`){v.current=!1;return}if(!v.current){v.current=!0;let i;e.scheduledTime?(i=new Date(e.scheduledTime),isNaN(i.getTime())&&(i=new Date,i.setHours(i.getHours()+1,0,0,0))):(i=new Date,i.setHours(i.getHours()+1,0,0,0),t({...e,scheduledTime:Jf(i)})),u(Hf(i,n)),f(Uf(i,r)),m(!0),g(!0)}},[e.scheduleType,e.scheduledTime,n,r,t,e]);let b=n=>{t({...e,scheduleType:n,requireManualStart:n===`queue`?e.requireManualStart:!1})},x=(r,i)=>{let a=Kf(r,n),o=qf(i);m(!!a),g(!!o),a&&o&&(a.setHours(o.hours,o.minutes,0,0),a>new Date&&t({...e,scheduledTime:Jf(a)}))},S=e=>{u(e),x(e,d)},C=e=>{f(e),x(l,e)};return(0,G.jsxs)(`div`,{className:`space-y-4`,children:[(0,G.jsxs)(`div`,{children:[(0,G.jsx)(`label`,{className:`block text-sm text-bambu-gray mb-2`,children:c(`printModal.whenToPrint`)}),(0,G.jsxs)(`div`,{className:`flex gap-2`,children:[(0,G.jsxs)(`button`,{type:`button`,className:`flex-1 px-2 py-2 rounded-lg border text-sm flex items-center justify-center gap-1.5 transition-colors ${e.scheduleType===`asap`?`bg-bambu-green border-bambu-green text-white`:`bg-bambu-dark border-bambu-dark-tertiary text-bambu-gray hover:text-white`}`,onClick:()=>b(`asap`),children:[(0,G.jsx)(ks,{className:`w-4 h-4`}),c(`printModal.asap`)]}),(0,G.jsxs)(`button`,{type:`button`,className:`flex-1 px-2 py-2 rounded-lg border text-sm flex items-center justify-center gap-1.5 transition-colors ${e.scheduleType===`queue`?`bg-bambu-green border-bambu-green text-white`:`bg-bambu-dark border-bambu-dark-tertiary text-bambu-gray hover:text-white`}`,onClick:()=>b(`queue`),children:[(0,G.jsx)(Xc,{className:`w-4 h-4`}),c(`printModal.queue`)]}),(0,G.jsxs)(`button`,{type:`button`,className:`flex-1 px-2 py-2 rounded-lg border text-sm flex items-center justify-center gap-1.5 transition-colors ${e.scheduleType===`scheduled`?`bg-bambu-green border-bambu-green text-white`:`bg-bambu-dark border-bambu-dark-tertiary text-bambu-gray hover:text-white`}`,onClick:()=>b(`scheduled`),children:[(0,G.jsx)(rs,{className:`w-4 h-4`}),c(`printModal.schedule`)]})]})]}),e.scheduleType===`scheduled`&&(0,G.jsxs)(`div`,{children:[(0,G.jsx)(`label`,{className:`block text-sm text-bambu-gray mb-1`,children:c(`printModal.dateTime`)}),(0,G.jsxs)(`div`,{className:`flex gap-2`,children:[(0,G.jsxs)(`div`,{className:`flex-1 relative`,children:[(0,G.jsx)(`input`,{type:`text`,className:`w-full px-3 py-2 pr-10 bg-bambu-dark border rounded-lg text-white focus:outline-none ${p?`border-bambu-dark-tertiary focus:border-bambu-green`:`border-red-500`}`,value:l,onChange:e=>S(e.target.value),placeholder:Bf(n)}),(0,G.jsx)(`button`,{type:`button`,onClick:()=>{_.current?.showPicker()},className:`absolute right-2 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white`,title:c(`printModal.openCalendar`),children:(0,G.jsx)(rs,{className:`w-4 h-4`})}),(0,G.jsx)(`input`,{ref:_,type:`datetime-local`,className:`absolute top-0 left-0 w-0 h-0 opacity-0 pointer-events-none`,value:e.scheduledTime,onChange:i=>{let a=i.target.value;if(a){let i=new Date(a);isNaN(i.getTime())||(u(Hf(i,n)),f(Uf(i,r)),m(!0),g(!0),t({...e,scheduledTime:a}))}},tabIndex:-1})]}),(0,G.jsx)(`div`,{className:`w-32`,children:(0,G.jsx)(`input`,{type:`text`,className:`w-full px-3 py-2 bg-bambu-dark border rounded-lg text-white focus:outline-none ${h?`border-bambu-dark-tertiary focus:border-bambu-green`:`border-red-500`}`,value:d,onChange:e=>C(e.target.value),placeholder:Vf(r)})})]}),(!p||!h)&&(0,G.jsx)(`p`,{className:`mt-1 text-xs text-red-700 dark:text-red-400`,children:c(`printModal.invalidDateTime`)})]}),e.scheduleType===`queue`&&(0,G.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,G.jsx)(`input`,{type:`checkbox`,id:`requireManualStart`,checked:e.requireManualStart,onChange:n=>t({...e,requireManualStart:n.target.checked}),className:`rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green`}),(0,G.jsxs)(`label`,{htmlFor:`requireManualStart`,className:`text-sm flex items-center gap-1 text-bambu-gray`,children:[(0,G.jsx)(jc,{className:`w-3.5 h-3.5`}),c(`printModal.requireManualStart`)]})]}),(0,G.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,G.jsx)(`input`,{type:`checkbox`,id:`requirePrevious`,checked:e.requirePreviousSuccess,onChange:n=>t({...e,requirePreviousSuccess:n.target.checked}),className:`rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green`}),(0,G.jsx)(`label`,{htmlFor:`requirePrevious`,className:`text-sm text-bambu-gray`,children:c(`printModal.requirePreviousSuccess`)})]}),(0,G.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,G.jsx)(`input`,{type:`checkbox`,id:`autoOffAfter`,checked:e.autoOffAfter,onChange:n=>t({...e,autoOffAfter:n.target.checked}),disabled:!i,className:`rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green disabled:opacity-50`}),(0,G.jsxs)(`label`,{htmlFor:`autoOffAfter`,className:`text-sm flex items-center gap-1 ${i?`text-bambu-gray`:`text-bambu-gray/50`}`,children:[(0,G.jsx)(Fl,{className:`w-3.5 h-3.5`}),c(`printModal.autoOffAfter`)]})]}),s&&(0,G.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,G.jsx)(`input`,{type:`checkbox`,id:`gcodeInjection`,checked:e.gcodeInjection,onChange:n=>t({...e,gcodeInjection:n.target.checked}),className:`rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green`}),(0,G.jsxs)(`label`,{htmlFor:`gcodeInjection`,className:`text-sm flex items-center gap-1 text-bambu-gray`,children:[(0,G.jsx)(Ns,{className:`w-3.5 h-3.5`}),c(`printModal.gcodeInjection`,`Inject auto-print G-code`)]})]}),a&&e.scheduleType!==`queue`&&(0,G.jsxs)(`div`,{className:`space-y-3`,children:[(0,G.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,G.jsx)(`input`,{type:`checkbox`,id:`staggerEnabled`,checked:e.staggerEnabled,onChange:n=>t({...e,staggerEnabled:n.target.checked}),className:`rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green`}),(0,G.jsxs)(`label`,{htmlFor:`staggerEnabled`,className:`text-sm flex items-center gap-1 text-bambu-gray`,children:[(0,G.jsx)(Kc,{className:`w-3.5 h-3.5`}),c(`printModal.staggerPrinterStarts`,`Stagger printer starts`)]})]}),e.staggerEnabled&&(0,G.jsxs)(`div`,{className:`ml-6 space-y-3`,children:[(0,G.jsxs)(`div`,{className:`flex gap-3`,children:[(0,G.jsxs)(`div`,{className:`flex-1`,children:[(0,G.jsx)(`label`,{className:`block text-xs text-bambu-gray mb-1`,children:c(`printModal.staggerGroupSize`,`Group size`)}),(0,G.jsx)(`input`,{type:`number`,min:1,max:o,value:e.staggerGroupSize,onChange:n=>t({...e,staggerGroupSize:Math.max(1,parseInt(n.target.value)||1)}),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`})]}),(0,G.jsxs)(`div`,{className:`flex-1`,children:[(0,G.jsx)(`label`,{className:`block text-xs text-bambu-gray mb-1`,children:c(`printModal.staggerInterval`,`Interval (min)`)}),(0,G.jsx)(`input`,{type:`number`,min:1,max:60,value:e.staggerIntervalMinutes,onChange:n=>t({...e,staggerIntervalMinutes:Math.max(1,parseInt(n.target.value)||1)}),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`})]})]}),o>0&&(()=>{let t=Math.ceil(o/e.staggerGroupSize),n=o%e.staggerGroupSize,r=(t-1)*e.staggerIntervalMinutes;return(0,G.jsxs)(`p`,{className:`text-xs text-bambu-gray`,children:[c(`printModal.staggerPreview`,`{{printers}} printers → {{groups}} groups of {{size}}, starting every {{interval}} min`,{printers:o,groups:t,size:e.staggerGroupSize,interval:e.staggerIntervalMinutes}),n!==0&&e.staggerGroupSize1?` (${c(`printModal.staggerTotal`,`total: {{minutes}} min`,{minutes:r})})`:``]})})()]})]}),(0,G.jsx)(`p`,{className:`text-xs text-bambu-gray`,children:e.scheduleType===`asap`?c(`printModal.helpAsap`):e.scheduleType===`scheduled`?c(`printModal.helpSchedule`):c(`printModal.helpQueue`)})]})}function zU({candidates:e,onReorder:t,plateByFile:n,onPlateChange:r,readOnly:i=!1,readOnlyNote:a}){let{t:o}=U(),s=xo({queries:i?[]:e.map(e=>({queryKey:[`library-file-plates`,e.id],queryFn:()=>Z.getLibraryFilePlates(e.id),staleTime:6e4}))}),c=(0,y.useMemo)(()=>{let t={};return e.forEach((e,n)=>{let r=s[n]?.data;r?.is_multi_plate&&r.plates.length>1&&(t[e.id]=r.plates.map(e=>({index:e.index,name:e.name})))}),t},[e,s]),l=(n,r)=>{if(r<0||r>=e.length)return;let i=[...e],[a]=i.splice(n,1);i.splice(r,0,a),t(i)};return(0,G.jsxs)(`div`,{className:`mb-4`,children:[(0,G.jsxs)(`div`,{className:`flex items-center gap-2 mb-2`,children:[(0,G.jsx)(Il,{className:`w-4 h-4 text-bambu-gray`}),(0,G.jsx)(`span`,{className:`text-sm text-bambu-gray`,children:o(`printModal.variants.title`)})]}),(0,G.jsx)(`p`,{className:`text-xs text-bambu-gray mb-2`,children:i?a??o(`printModal.variants.help`):o(`printModal.variants.help`)}),(0,G.jsx)(`div`,{className:`space-y-2`,children:e.map((t,a)=>{let s=c[t.id],u=t.sliced_for_model;return(0,G.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2 rounded border border-bambu-dark-tertiary p-2`,children:[(0,G.jsxs)(`span`,{className:`text-xs font-mono text-bambu-gray w-5 shrink-0`,children:[a+1,`.`]}),(0,G.jsx)(`span`,{className:`px-2 py-0.5 rounded-full bg-bambu-green/10 text-bambu-green text-xs shrink-0`,children:u||o(`printModal.variants.unknownModel`)}),(0,G.jsx)(`span`,{className:`text-sm text-white truncate min-w-0 flex-1`,title:t.filename,children:t.filename}),s&&(0,G.jsxs)(`label`,{className:`flex items-center gap-1 text-xs text-bambu-gray shrink-0`,children:[(0,G.jsx)(Kc,{className:`w-3 h-3`}),(0,G.jsx)(`select`,{className:`bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-1 py-0.5 text-xs text-white`,value:n[t.id]??s[0].index,onChange:e=>r(t.id,Number(e.target.value)),"aria-label":o(`printModal.variants.plateFor`,{filename:t.filename}),children:s.map(e=>(0,G.jsx)(`option`,{value:e.index,children:e.name||o(`printModal.plateN`,{n:e.index})},e.index))})]}),!i&&(0,G.jsxs)(`div`,{className:`flex items-center gap-1 shrink-0`,children:[(0,G.jsx)(`button`,{type:`button`,onClick:()=>l(a,a-1),disabled:a===0,className:`p-1 rounded text-bambu-gray hover:text-white disabled:opacity-30`,"aria-label":o(`printModal.variants.moveUp`),children:(0,G.jsx)(Bo,{className:`w-3.5 h-3.5`})}),(0,G.jsx)(`button`,{type:`button`,onClick:()=>l(a,a+1),disabled:a===e.length-1,className:`p-1 rounded text-bambu-gray hover:text-white disabled:opacity-30`,"aria-label":o(`printModal.variants.moveDown`),children:(0,G.jsx)(Po,{className:`w-3.5 h-3.5`})})]})]},t.id)})})]})}function Nke({costCenters:e,selectedCostCenterId:t,onChange:n}){let{t:r}=U();if(e.length===0)return null;let i=e.find(e=>e.id===t);return(0,G.jsxs)(`div`,{className:`space-y-1`,children:[(0,G.jsx)(`label`,{htmlFor:`printCostCenter`,className:`text-sm text-bambu-gray`,children:r(`printModal.costCenter`,`Cost center`)}),(0,G.jsx)(`select`,{id:`printCostCenter`,value:t??``,onChange:e=>n(e.target.value?Number(e.target.value):null),className:`w-full px-3 py-2 text-sm bg-bambu-dark border border-bambu-dark-tertiary rounded text-white focus:outline-none focus:ring-1 focus:ring-bambu-green`,children:e.map(e=>(0,G.jsxs)(`option`,{value:e.id,children:[e.name,e.is_private?` (${r(`printModal.personalDefault`,`Personal`)})`:``]},e.id))}),i?.budget_mode===`none`&&(0,G.jsx)(`p`,{className:`text-xs text-bambu-gray`,children:r(`printModal.unlimitedNoBudget`,`Unlimited – no budget limit is set.`)})]})}var BU={bed_levelling:`auto`,flow_cali:`auto`,vibration_cali:!0,layer_inspect:!1,timelapse:!1,nozzle_offset_cali:`auto`,preheat_override:`inherit`,preheat_chamber_target_override:null},VU={scheduleType:`asap`,scheduledTime:``,requireManualStart:!1,requirePreviousSuccess:!1,autoOffAfter:!1,gcodeInjection:!1,staggerEnabled:!1,staggerGroupSize:2,staggerIntervalMinutes:5};function HU({mode:e,archiveId:t,libraryFileId:n,archiveName:r,queueItem:i,initialSelectedPrinterIds:a,onClose:o,onSuccess:s,projectId:c,cleanupLibraryAfterDispatch:l,variantFiles:u}){let{t:d}=U(),f=oo(),{showToast:p}=Bd(),{hasPermission:m,user:h}=Dd(),g=!!n&&!t,_=e===`edit-queue-item`,v=e===`create`&&(u?.length??0)>1,b=e===`edit-queue-item`&&(i?.variants?.length??0)>1?i.variants.map(e=>({id:e.library_file_id,filename:e.filename,sliced_for_model:e.target_model})):[],x=b.length>0,[S,C]=(0,y.useState)(u??[]),[w,T]=(0,y.useState)({}),[E,D]=(0,y.useState)(()=>e===`edit-queue-item`&&i?.printer_id?[i.printer_id]:a?.length?a:[]),[O,k]=(0,y.useState)(()=>e===`edit-queue-item`&&i?.plate_id!=null?new Set([i.plate_id]):new Set),A=O.size===1?[...O][0]:null,[j,M]=(0,y.useState)(1),[N,P]=(0,y.useState)({}),[F,I]=(0,y.useState)(()=>e===`edit-queue-item`&&i?{bed_levelling:i.bed_levelling??BU.bed_levelling,flow_cali:i.flow_cali??BU.flow_cali,vibration_cali:i.vibration_cali??BU.vibration_cali,layer_inspect:i.layer_inspect??BU.layer_inspect,timelapse:i.timelapse??BU.timelapse,nozzle_offset_cali:i.nozzle_offset_cali??BU.nozzle_offset_cali,preheat_override:i.preheat_override??BU.preheat_override,preheat_chamber_target_override:i.preheat_chamber_target_override??BU.preheat_chamber_target_override}:BU),[L,R]=(0,y.useState)(()=>{if(e===`edit-queue-item`&&i){let e=`queue`;i.scheduled_time&&!Ap(i.scheduled_time)&&(e=`scheduled`);let t=``;return i.scheduled_time&&!Ap(i.scheduled_time)&&(t=Jf(Xf(i.scheduled_time)??new Date)),{scheduleType:e,scheduledTime:t,requireManualStart:i.manual_start,requirePreviousSuccess:i.require_previous_success,autoOffAfter:i.auto_off_after,gcodeInjection:i.gcode_injection??!1,staggerEnabled:!1,staggerGroupSize:VU.staggerGroupSize,staggerIntervalMinutes:VU.staggerIntervalMinutes}}return VU}),[z,B]=(0,y.useState)(()=>{if(e===`edit-queue-item`&&i?.ams_mapping&&Array.isArray(i.ams_mapping)){let e={};return i.ams_mapping.forEach((t,n)=>{t!==-1&&(e[n+1]=t)}),e}return{}}),[V,ee]=(0,y.useState)({}),[te,ne]=(0,y.useState)(()=>v||e===`edit-queue-item`&&i?.target_model?`model`:`printer`),[re,ie]=(0,y.useState)(()=>e===`edit-queue-item`&&i?.target_model?i.target_model:null),[ae,oe]=(0,y.useState)(()=>e===`edit-queue-item`&&i?.target_location?i.target_location:null),[se,H]=(0,y.useState)(()=>e===`edit-queue-item`?i?.cost_center_id??null:null),[ce,le]=(0,y.useState)(i?.estimated_cost??null),[ue,de]=(0,y.useState)({}),[fe,pe]=(0,y.useState)(()=>{if(e===`edit-queue-item`&&i?.filament_overrides){let e={};for(let t of i.filament_overrides)e[t.slot_id]={type:t.type,color:t.color};return e}return{}}),[me,he]=(0,y.useState)(()=>{if(e===`edit-queue-item`&&i?.filament_overrides){let e={};for(let t of i.filament_overrides)e[t.slot_id]=t.force_color_match===!0;return e}return{}}),[ge]=(0,y.useState)(()=>e===`edit-queue-item`&&i?.printer_id?[i.printer_id]:[]),[_e]=(0,y.useState)(()=>e===`edit-queue-item`&&i?i.plate_id:null),[ve,ye]=(0,y.useState)(!1),[be,xe]=(0,y.useState)({current:0,total:0}),[Se,Ce]=(0,y.useState)(null),[we,Te]=(0,y.useState)(new Set),Ee=E.length,De=E.length>0?E[0]:null,{data:Oe}=K({queryKey:[`settings`],queryFn:Z.getSettings}),ke=(0,y.useRef)(!1);(0,y.useEffect)(()=>{!Oe||ke.current||e===`edit-queue-item`||(ke.current=!0,I({bed_levelling:Oe.default_bed_levelling??BU.bed_levelling,flow_cali:Oe.default_flow_cali??BU.flow_cali,vibration_cali:Oe.default_vibration_cali??BU.vibration_cali,layer_inspect:Oe.default_layer_inspect??BU.layer_inspect,timelapse:Oe.default_timelapse??BU.timelapse,nozzle_offset_cali:Oe.default_nozzle_offset_cali??BU.nozzle_offset_cali,preheat_override:BU.preheat_override,preheat_chamber_target_override:BU.preheat_chamber_target_override}))},[Oe,e]);let Ae=(0,y.useRef)(!1);(0,y.useEffect)(()=>{!Oe||Ae.current||e===`edit-queue-item`||(Ae.current=!0,R(e=>({...e,staggerGroupSize:Oe.stagger_group_size??e.staggerGroupSize,staggerIntervalMinutes:Oe.stagger_interval_minutes??e.staggerIntervalMinutes})))},[Oe,e]);let je=Af(Oe?.currency||`USD`),Me=Oe?.default_filament_cost??0,Ne=Oe?.billing_enabled===!0,{data:Pe,isLoading:Fe}=K({queryKey:[`printers`],queryFn:Z.getPrinters}),{data:Ie,isLoading:Le}=K({queryKey:[`finance`,`cost-centers`,`mine`],queryFn:Z.getMyCostCenters,enabled:!!h&&Ne}),Re=(0,y.useMemo)(()=>(Ie||[]).filter(e=>e.can_print&&e.is_active),[Ie]),ze=(0,y.useMemo)(()=>Re.find(e=>e.id===se)??null,[Re,se]);(0,y.useEffect)(()=>{Re.length!==0&&(se!=null&&Re.some(e=>e.id===se)||H(Re.find(e=>e.is_private)?.id??Re[0].id))},[Re,se]);let Be=xo({queries:E.map(e=>({queryKey:[`printer-inventory-remain`,e],queryFn:()=>Z.getInventoryRemain(e),staleTime:30*1e3,refetchOnMount:`always`,enabled:E.length>0}))}),Ve=(0,y.useMemo)(()=>{let e=new Map;return E.forEach((t,n)=>{let r=Be[n]?.data?.inventory_remain_g;if(!r)return;let i=new Map;Object.entries(r).forEach(([e,t])=>{let n=Number(e);Number.isNaN(n)||i.set(n,t)}),e.set(t,i)}),e},[E,Be]),He=(0,y.useMemo)(()=>{let e=new Map;return E.forEach((t,n)=>{let r=Be[n]?.data?.slot_materials;if(!r)return;let i=new Map;r.forEach(e=>i.set(e.global_tray_id,e)),e.set(t,i)}),e},[E,Be]),{data:Ue}=K({queryKey:[`archive`,t],queryFn:()=>Z.getArchive(t),enabled:!!t&&!g}),{data:We}=K({queryKey:[`library-file`,n],queryFn:()=>Z.getLibraryFile(n),enabled:g&&!!n}),Ge=Ue?.sliced_for_model||We?.sliced_for_model||null,Ke=(0,y.useMemo)(()=>g?void 0:xke(Ue?.extra_data,De),[g,Ue?.extra_data,De]),{data:qe,isError:Je}=K({queryKey:[`archive-plates`,t],queryFn:()=>Z.getArchivePlates(t),enabled:!!t&&!g,retry:!1}),{data:Ye}=K({queryKey:[`library-file-plates`,n],queryFn:()=>Z.getLibraryFilePlates(n),enabled:g&&!!n}),Xe=g?Ye:qe,{data:Ze,isError:Qe}=K({queryKey:[`archive-filaments`,t,A],queryFn:()=>Z.getArchiveFilamentRequirements(t,A??void 0),enabled:!!t&&!g&&(A!==null||!Xe?.is_multi_plate),retry:!1}),{data:$e}=K({queryKey:[`library-file-filaments`,n,A],queryFn:()=>Z.getLibraryFileFilamentRequirements(n,A??void 0),enabled:g&&!!n&&(A!==null||!Xe?.is_multi_plate)}),et=!g&&(Je||Qe),tt=g?$e:Ze,{data:nt}=K({queryKey:[`available-filaments`,re,ae],queryFn:()=>Z.getAvailableFilaments(re,ae??void 0),enabled:te===`model`&&!!re}),rt=(0,y.useMemo)(()=>Array.from(new Set(S.map(e=>e.sliced_for_model).filter(e=>!!e))),[S]),it=xo({queries:v?rt.map(e=>({queryKey:[`available-filaments`,e,ae],queryFn:()=>Z.getAvailableFilaments(e,ae??void 0)})):[]}),at=(0,y.useMemo)(()=>{let e=new Set,t=[];for(let n of it)for(let r of n.data??[]){let n=`${r.type}|${r.color}|${r.tray_info_idx}`;e.has(n)||(e.add(n),t.push(r))}return t},[it]),ot=v?at:nt,{data:st,isLoading:ct}=K({queryKey:[`printer-status`,De],queryFn:()=>Z.getPrinterStatus(De),enabled:!!De}),lt=Pp(Oe?.prefer_lowest_filament,st?.ams_filament_backup),ut=async()=>{if(L.scheduleType!==`asap`||te!==`printer`||E.length===0)return!1;try{return(await Promise.all(E.map(e=>f.fetchQuery({queryKey:[`printer-status`,e],queryFn:()=>Z.getPrinterStatus(e),staleTime:0})))).some(e=>!_m(e))}catch{return!0}},{amsMapping:dt}=EU(tt,st,z,lt,De?Ve.get(De):void 0),ft=(0,y.useMemo)(()=>[...O].sort((e,t)=>e-t),[O]),pt=O.size>1,mt=xo({queries:(pt?ft:[]).map(e=>({queryKey:g?[`library-file-filaments`,n,e]:[`archive-filaments`,t,e],queryFn:()=>g?Z.getLibraryFileFilamentRequirements(n,e):Z.getArchiveFilamentRequirements(t,e),enabled:g?!!n:!!t,retry:!1}))}),ht=mt.some(e=>e.isPending),gt=mt.some(e=>e.isError),_t=(0,y.useMemo)(()=>{let e=new Map;return ft.forEach((t,n)=>{let r=mt[n]?.data;r&&e.set(t,r)}),e},[ft,mt.map(e=>e.dataUpdatedAt).join(`|`)]),[vt,yt]=(0,y.useState)({}),[bt,xt]=(0,y.useState)(()=>{if(e===`edit-queue-item`&&i?.nozzle_rack_choice){let e={};for(let[t,n]of Object.entries(i.nozzle_rack_choice)){let r=Number(t);Number.isInteger(r)&&Number.isInteger(n)&&(e[r]=n)}return e}return{}}),[St,Ct]=(0,y.useState)({}),wt=(0,y.useMemo)(()=>{let e=new Map;if(!pt||!De||E.length!==1)return e;let t=xU(st),n=st?.fila_switch?.installed===!0,r=Ve.get(De);for(let i of ft){let a=_t.get(i);if(!a)continue;let o=wU(a,t,vt[i]??{},lt,r,n);e.set(i,TU(o))}return e},[pt,De,st,Ve,ft,_t,vt,lt,E.length]),Tt=yke(E,Pe,tt,z,V,ee,Oe?.prefer_lowest_filament,Ve);(0,y.useEffect)(()=>{Xe?.plates&&Xe.plates.length>=1&&O.size===0&&k(new Set([Xe.plates[0].index]))},[Xe,O.size]),(0,y.useEffect)(()=>{if(e===`edit-queue-item`)return;let t=Pe?.filter(e=>e.is_active)||[];t.length===1&&E.length===0&&D([t[0].id])},[e,Pe,E.length]),(0,y.useEffect)(()=>{e===`edit-queue-item`?(JSON.stringify(E.sort())!==JSON.stringify(ge.sort())||A!==_e)&&(B({}),yt({}),ee({}),Te(new Set)):(B({}),yt({}),ee({}),Te(new Set))},[e,E,A,ge,_e]);let[Et,Dt]=(0,y.useState)(re),[Ot,kt]=(0,y.useState)(A);(0,y.useEffect)(()=>{(re!==Et||A!==Ot)&&(Dt(re),kt(A),(e!==`edit-queue-item`||Et!==null)&&(pe({}),he({})))},[re,A,Et,Ot,e]),(0,y.useEffect)(()=>{te!==`model`||re||!Ge||Pe?.some(e=>e.is_active&&e.model===Ge)&&ie(Ge)},[te,re,Ge,Pe]),(0,y.useEffect)(()=>{if(!Oe?.per_printer_mapping_expanded||E.length<=1)return;let e=E.filter(e=>{if(we.has(e))return!1;let t=Tt.printerResults.find(t=>t.printerId===e);return t&&t.status&&!t.isLoading});e.length>0&&(Te(t=>{let n=new Set(t);return e.forEach(e=>n.add(e)),n}),e.forEach(e=>{Tt.autoConfigurePrinter(e)}))},[Oe?.per_printer_mapping_expanded,E,we,Tt]),(0,y.useEffect)(()=>{let e=e=>{e.key===`Escape`&&!ve&&o()};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[o,ve]);let At=Xe?.is_multi_plate??!1,jt=Xe?.plates??[],Mt=(0,y.useMemo)(()=>{if(!Se||Se.length===0)return``;let e=Se.map(e=>e.pooled?d(`printModal.insufficientFilamentLinePooled`,{printer:e.printerName,slot:e.slotLabel,required:Math.round(e.requiredGrams),remaining:Math.round(e.remainingGrams)}):d(`printModal.insufficientFilamentLine`,{printer:e.printerName,slot:e.slotLabel,required:Math.round(e.requiredGrams),remaining:Math.round(e.remainingGrams)}));return[d(`printModal.insufficientFilamentMessage`),...e].join(` + `})]}),document.body)]})}function DH({isOpen:e,onClose:t,tagUid:n,trayUuid:r,printerId:i,amsId:a,trayId:o}){let{t:s}=U(),c=oo(),{showToast:l}=Bd(),[u,d]=(0,y.useState)(``),f=r||n,{data:p,isLoading:m}=K({queryKey:[`unlinked-spools`],queryFn:Z.getUnlinkedSpools,enabled:e}),h=(0,y.useMemo)(()=>p?p.filter(e=>{if(!u)return!0;let t=u.toLowerCase();return e.filament_name&&e.filament_name.toLowerCase().includes(t)||e.filament_vendor&&e.filament_vendor.toLowerCase().includes(t)||e.filament_material&&e.filament_material.toLowerCase().includes(t)||String(e.id).includes(t)}):[],[p,u]),g=q({mutationFn:e=>Z.linkSpool(e,{spoolTag:f,printerId:i,amsId:a,trayId:o}),onSuccess:()=>{c.invalidateQueries({queryKey:[`unlinked-spools`]}),c.invalidateQueries({queryKey:[`linked-spools`]}),c.invalidateQueries({queryKey:[`spoolman-slot-assignments`]}),l(s(`spoolman.linkSuccess`),`success`),t()},onError:e=>{l(e.message||s(`spoolman.linkFailed`),`error`)}});return e?(0,G.jsxs)(`div`,{className:`fixed inset-0 z-50 flex items-center justify-center`,children:[(0,G.jsx)(`div`,{className:`absolute inset-0 bg-black/60 backdrop-blur-sm`,onClick:t}),(0,G.jsxs)(`div`,{className:`relative bg-bambu-dark-secondary rounded-xl shadow-xl w-full max-w-md mx-4 max-h-[80vh] flex flex-col border border-bambu-dark-tertiary`,children:[(0,G.jsxs)(`div`,{className:`flex items-center justify-between p-4 border-b border-white/10`,children:[(0,G.jsxs)(`div`,{children:[(0,G.jsxs)(`h3`,{className:`text-lg font-semibold text-white flex items-center gap-2`,children:[(0,G.jsx)(Yc,{className:`w-5 h-5 text-bambu-green`}),s(`spoolman.selectSpool`)]}),(0,G.jsxs)(`p`,{className:`text-xs text-bambu-gray mt-1`,children:[`AMS `,a,` T`,o,` · Printer #`,i]})]}),(0,G.jsx)(`button`,{onClick:t,className:`p-1 text-bambu-gray hover:text-white rounded transition-colors`,children:(0,G.jsx)(ed,{className:`w-5 h-5`})})]}),(0,G.jsxs)(`div`,{className:`p-4 border-b border-white/10`,children:[(0,G.jsxs)(`div`,{className:`relative`,children:[(0,G.jsx)(Xl,{className:`absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray`}),(0,G.jsx)(`input`,{type:`text`,value:u,onChange:e=>d(e.target.value),placeholder:s(`inventory.searchSpools`),className:`w-full pl-9 pr-3 py-2 bg-bambu-dark rounded-lg border border-white/10 text-white text-sm placeholder:text-bambu-gray focus:outline-none focus:border-bambu-green`})]}),(r||n)&&(0,G.jsxs)(`p`,{className:`text-xs text-bambu-gray mt-2 font-mono truncate`,title:r||n,children:[`Tag: `,r||n]})]}),(0,G.jsx)(`div`,{className:`flex-1 overflow-y-auto p-2 min-h-0`,children:m?(0,G.jsx)(`div`,{className:`flex justify-center py-8`,children:(0,G.jsx)(Y,{className:`w-6 h-6 animate-spin text-bambu-green`})}):h.length===0?(0,G.jsx)(`p`,{className:`text-center text-bambu-gray py-8 text-sm`,children:s(`inventory.noSpoolsMatch`)}):h.map(e=>(0,G.jsxs)(`button`,{onClick:()=>g.mutate(e.id),disabled:g.isPending||!f,className:`w-full flex items-center gap-3 p-3 rounded-lg hover:bg-white/5 transition-colors text-left`,children:[(0,G.jsx)(`span`,{className:`w-6 h-6 rounded-full border border-black/20 flex-shrink-0`,style:Tf(e.filament_color_hex)}),(0,G.jsxs)(`div`,{className:`flex-1 min-w-0`,children:[(0,G.jsx)(`div`,{className:`text-sm text-white font-medium truncate`,children:e.filament_name||s(`spoolman.spoolId`)}),(0,G.jsxs)(`div`,{className:`text-xs text-bambu-gray truncate`,children:[e.filament_vendor?`${e.filament_vendor} · `:``,e.filament_material||`Unknown`,` · #`,e.id]})]}),(0,G.jsx)(`span`,{className:`text-xs text-bambu-gray`,children:e.remaining_weight==null?`—`:`${Math.round(e.remaining_weight)}g`})]},e.id))}),(0,G.jsx)(`div`,{className:`p-4 border-t border-white/10 flex justify-end`,children:(0,G.jsx)(Q,{variant:`ghost`,onClick:t,children:s(`inventory.cancel`)||`Cancel`})})]})]}):null}function YOe(e,t){if(!t)return!0;let n=t.toLowerCase();return String(e.id).includes(n)||e.material.toLowerCase().includes(n)||(e.brand?.toLowerCase().includes(n)??!1)||(e.color_name?.toLowerCase().includes(n)??!1)||(e.subtype?.toLowerCase().includes(n)??!1)||(e.note?.toLowerCase().includes(n)??!1)||(e.slicer_filament_name?.toLowerCase().includes(n)??!1)||(e.storage_location?.toLowerCase().includes(n)??!1)}function OH(e,t){return t?e.filter(e=>YOe(e,t)):e}function kH({isOpen:e,onClose:t,printerId:n,amsId:r,trayId:i,trayInfo:a,spoolmanEnabled:o}){let{t:s}=U(),c=oo(),{showToast:l}=Bd(),[u,d]=(0,y.useState)(!1),[f,p]=(0,y.useState)(null),[m,h]=(0,y.useState)(null);(0,y.useEffect)(()=>{p(null),h(null)},[u]);let[g,_]=(0,y.useState)(``),[v,b]=(0,y.useState)(null),[x,S]=(0,y.useState)(!1),[C,w]=(0,y.useState)(null);(0,y.useEffect)(()=>{e&&d(!1)},[e]);let{data:T,isLoading:E}=K({queryKey:[`inventory-spools`,`assign-modal`],queryFn:()=>Z.getSpools(!0),enabled:e&&!o}),{data:D}=K({queryKey:[`spool-assignments`],queryFn:()=>Z.getAssignments(),enabled:e}),{data:O}=K({queryKey:[`settings`],queryFn:()=>Z.getSettings(),enabled:e}),{data:k,isLoading:A}=K({queryKey:[`spoolman-inventory-spools`,`assign-modal`],queryFn:()=>Z.getSpoolmanInventorySpools(!1),enabled:e&&!!o}),{data:j}=K({queryKey:[`spoolman-slot-assignments-all`],queryFn:()=>Z.getSpoolmanSlotAssignments(),enabled:e&&!!o}),M=(0,y.useMemo)(()=>j?new Set(j.filter(e=>!(e.printer_id===n&&e.ams_id===r&&e.tray_id===i)).map(e=>e.spoolman_spool_id)):new Set,[j,n,r,i]),N=()=>{Z.refreshPrinterStatus(n).catch(()=>{}),c.invalidateQueries({queryKey:[`printerStatus`,n]})},P=q({mutationFn:e=>Z.assignSpool({spool_id:e,printer_id:n,ams_id:r,tray_id:i}),onSuccess:e=>{c.setQueryData([`spool-assignments`],t=>{let a=(t||[]).filter(e=>!(e.printer_id===n&&e.ams_id===r&&e.tray_id===i));return a.push(e),a}),c.invalidateQueries({queryKey:[`spool-assignments`]}),N(),l(s(e.pending_config?`inventory.assignPendingInsert`:`inventory.assignSuccess`),`success`),S(!1),b(null),w(null),t()},onError:e=>{l(`${s(`inventory.assignFailed`)}: ${e.message}`,`error`)}}),F=q({mutationFn:e=>Z.assignSpoolmanSlot({spoolman_spool_id:e,printer_id:n,ams_id:r,tray_id:i}),onSuccess:()=>{c.invalidateQueries({queryKey:[`spoolman-inventory-spools`]}),c.invalidateQueries({queryKey:[`spoolman-slot-assignments`]}),N(),l(s(`inventory.assignSuccess`),`success`),t()},onError:e=>{l(`${s(`inventory.assignFailed`)}: ${e.message}`,`error`)}}),I=e=>(e??``).trim().toUpperCase(),L=(e,t)=>{let n=I(e),r=I(t);return!n||!r?`none`:n===r?`exact`:r.includes(n)||n.includes(r)?`partial`:`none`},R=e=>e.split(`@`)[0].trim(),z=(e,t)=>{let n=R(I(e)),r=R(I(t));return!n||!r?!1:n===r};if(!e)return null;let B=new Set((D||[]).filter(e=>!(e.printer_id===n&&e.ams_id===r&&e.tray_id===i)).map(e=>e.spool_id)),V=T?.filter(e=>!e.archived_at&&(u||!B.has(e.id))),ee=V;if(!u){let e=R(I(a?.profile)),t=I(a?.material||a?.type);(e||t)&&(ee=ee?.filter(n=>{let r=R(I(n.slicer_filament_name||n.slicer_filament)),i=I(n.material);return e&&r&&r===e?!0:t&&i?i===t||t.includes(i)||i.includes(t):!r&&!i}))}g&&ee&&(ee=OH(ee,g));let te=()=>{if(m!==null){F.mutate(m);return}if(!f)return;let e=T?.find(e=>e.id===f);if(!e){l(s(`inventory.assignFailed`),`error`);return}if(!O?.disable_filament_warnings&&a){let t=a.material||a.type,n=L(e.material,t),r=e.slicer_filament_name||e.slicer_filament,i=a.profile||a.type,o=z(r,i);if(n!==`exact`){let a;a=n===`none`&&!o?`material_profile`:n===`partial`&&!o?`partial_profile`:n===`none`?`material`:`partial`,b(f),w({type:a,spoolMaterial:e.material||``,trayMaterial:t||``,spoolProfile:r||void 0,trayProfile:i||void 0}),S(!0);return}}P.mutate(f)},ne=()=>{v&&(P.mutate(v),S(!1),b(null))};return(0,G.jsxs)(G.Fragment,{children:[(0,G.jsxs)(`div`,{className:`fixed inset-0 z-[100] flex items-start sm:items-center justify-center p-4 overflow-y-auto`,children:[(0,G.jsx)(`div`,{className:`absolute inset-0 bg-black/60 backdrop-blur-sm`,onClick:t}),(0,G.jsxs)(`div`,{className:`relative w-full max-w-2xl bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl max-h-[90vh] overflow-hidden flex flex-col my-auto`,children:[(0,G.jsxs)(`div`,{className:`flex items-center justify-between p-4 border-b border-bambu-dark-tertiary`,children:[(0,G.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,G.jsx)(xl,{className:`w-5 h-5 text-bambu-green`}),(0,G.jsx)(`h2`,{className:`text-lg font-semibold text-white`,children:s(`inventory.assignSpool`)})]}),(0,G.jsx)(`button`,{onClick:t,className:`p-1 text-bambu-gray hover:text-white rounded transition-colors`,children:(0,G.jsx)(ed,{className:`w-5 h-5`})})]}),(0,G.jsxs)(`div`,{className:`p-4 space-y-4 overflow-y-auto`,children:[a&&(0,G.jsxs)(`div`,{className:`p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary`,children:[(0,G.jsxs)(`p`,{className:`text-xs text-bambu-gray mb-1`,children:[s(`inventory.selectSpool`),`:`]}),(0,G.jsxs)(`div`,{className:`flex items-center gap-2`,children:[a.color&&(0,G.jsx)(`span`,{className:`w-4 h-4 rounded-full border border-black/20`,style:Tf(a.color)}),(0,G.jsx)(`span`,{className:`text-white font-medium`,children:a.type||s(`ams.emptySlot`)}),(0,G.jsxs)(`span`,{className:`text-bambu-gray`,children:[`(`,a.location,`)`]})]})]}),(0,G.jsxs)(`div`,{className:`relative`,children:[(0,G.jsx)(Xl,{className:`absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray`}),(0,G.jsx)(`input`,{type:`text`,value:g,onChange:e=>_(e.target.value),placeholder:s(`inventory.searchSpools`),className:`w-full pl-9 pr-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray focus:outline-none focus:border-bambu-green`})]}),(0,G.jsxs)(`div`,{className:`space-y-3`,children:[!o&&(E?(0,G.jsx)(`div`,{className:`flex justify-center py-8`,children:(0,G.jsx)(Y,{className:`w-6 h-6 text-bambu-green animate-spin`})}):ee&&ee.length>0?(0,G.jsx)(`div`,{className:`max-h-96 overflow-y-auto grid grid-cols-2 sm:grid-cols-3 gap-2`,children:ee.map(e=>(0,G.jsxs)(`button`,{onClick:()=>{p(e.id),h(null)},title:e.note||void 0,className:`p-2.5 rounded-lg border text-left transition-colors ${f===e.id?`bg-bambu-green/20 border-bambu-green`:`bg-bambu-dark border-bambu-dark-tertiary hover:border-bambu-gray`}`,children:[(0,G.jsxs)(`p`,{className:`text-white text-sm font-medium truncate`,children:[e.brand?`${e.brand} `:``,e.material,e.subtype?` ${e.subtype}`:``]}),(0,G.jsxs)(`div`,{className:`flex items-center gap-1.5 mt-1`,children:[e.rgba&&(0,G.jsx)(`span`,{className:`w-3 h-3 rounded-full border border-black/20 flex-shrink-0`,style:Tf(e.rgba)}),(0,G.jsx)(`span`,{className:`text-xs text-bambu-gray truncate`,children:e.color_name||``})]}),e.label_weight&&(0,G.jsxs)(`p`,{className:`text-xs text-bambu-gray mt-1`,children:[Math.max(0,Math.round(e.label_weight-e.weight_used)),` / `,e.label_weight,`g`]}),e.note&&(0,G.jsx)(`p`,{className:`text-[10px] text-bambu-gray/70 mt-1 truncate`,title:e.note,children:e.note})]},e.id))}):V&&V.length===0?(0,G.jsxs)(`div`,{className:`text-center py-8 text-bambu-gray`,children:[(0,G.jsx)(`p`,{children:s(`inventory.noAvailableSpools`)}),T&&(0,G.jsxs)(`p`,{className:`text-[10px] mt-2 opacity-60`,children:[T.length,` fetched · `,T.filter(e=>e.archived_at).length,` archived ·`,` `,T.filter(e=>B.has(e.id)).length,` assigned to other slots`]})]}):(0,G.jsxs)(`div`,{className:`text-center py-8 text-bambu-gray`,children:[(0,G.jsx)(`p`,{children:s(`inventory.noSpoolsMatch`)}),V&&(0,G.jsxs)(`p`,{className:`text-[10px] mt-2 opacity-60`,children:[V.length,` unassigned spools — `,V.length-(ee?.length??0),` filtered by tray match. Try "Show all spools".`]})]})),o&&(0,G.jsx)(G.Fragment,{children:A?(0,G.jsx)(`div`,{className:`flex justify-center py-4`,children:(0,G.jsx)(Y,{className:`w-5 h-5 text-bambu-green animate-spin`})}):k&&k.filter(e=>!e.archived_at&&!M.has(e.id)).length>0?(0,G.jsxs)(G.Fragment,{children:[(0,G.jsx)(`p`,{className:`text-xs font-medium text-bambu-gray uppercase tracking-wide pt-1`,children:s(`inventory.spoolmanSpools`)}),(0,G.jsx)(`div`,{className:`max-h-64 overflow-y-auto grid grid-cols-2 sm:grid-cols-3 gap-2`,children:OH(k.filter(e=>!e.archived_at&&!M.has(e.id)),g).map(e=>(0,G.jsxs)(`button`,{onClick:()=>{h(e.id),p(null)},title:e.note||void 0,className:`p-2.5 rounded-lg border text-left transition-colors ${m===e.id?`bg-bambu-green/20 border-bambu-green`:`bg-bambu-dark border-bambu-dark-tertiary hover:border-bambu-gray`}`,children:[(0,G.jsxs)(`p`,{className:`text-white text-sm font-medium truncate`,children:[e.brand?`${e.brand} `:``,e.material,e.subtype?` ${e.subtype}`:``]}),(0,G.jsxs)(`div`,{className:`flex items-center gap-1.5 mt-1`,children:[e.rgba&&(0,G.jsx)(`span`,{className:`w-3 h-3 rounded-full border border-black/20 flex-shrink-0`,style:Tf(e.rgba)}),(0,G.jsx)(`span`,{className:`text-xs text-bambu-gray truncate`,children:e.color_name||``})]}),e.label_weight&&(0,G.jsxs)(`p`,{className:`text-xs text-bambu-gray mt-1`,children:[Math.max(0,Math.round(e.label_weight-e.weight_used)),` / `,e.label_weight,`g`]}),e.note&&(0,G.jsx)(`p`,{className:`text-[10px] text-bambu-gray/70 mt-1 truncate`,title:e.note,children:e.note})]},`spoolman-${e.id}`))})]}):null})]})]}),(0,G.jsxs)(`div`,{className:`flex justify-between items-center p-4 border-t border-bambu-dark-tertiary`,children:[(0,G.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,G.jsx)(`input`,{id:`disable-filtering-toggle`,type:`checkbox`,checked:u,onChange:()=>d(e=>!e),className:`accent-bambu-green w-4 h-4 rounded focus:ring-0 border-bambu-dark-tertiary`}),(0,G.jsx)(`label`,{htmlFor:`disable-filtering-toggle`,className:`text-xs text-bambu-gray select-none cursor-pointer`,children:s(`inventory.showAllSpools`)})]}),(0,G.jsxs)(`div`,{className:`flex gap-2`,children:[(0,G.jsx)(Q,{variant:`secondary`,onClick:t,children:s(`common.cancel`)}),(0,G.jsx)(Q,{onClick:te,disabled:!f&&m===null||P.isPending||F.isPending,children:P.isPending||F.isPending?(0,G.jsxs)(G.Fragment,{children:[(0,G.jsx)(Y,{className:`w-4 h-4 animate-spin`}),s(`inventory.assigning`)]}):(0,G.jsxs)(G.Fragment,{children:[(0,G.jsx)(xl,{className:`w-4 h-4`}),s(`inventory.assignSpool`)]})})]})]}),P.isError&&(0,G.jsx)(`div`,{className:`mx-4 mb-4 p-2 bg-red-100 dark:bg-red-500/20 border border-red-300 dark:border-red-500/50 rounded text-sm text-red-700 dark:text-red-400`,children:P.error.message})]})]}),x&&a&&f&&C&&(()=>{let e=``;return C.type===`material`?e=s(`inventory.assignMismatchMessage`,{spoolMaterial:C.spoolMaterial,trayMaterial:C.trayMaterial,location:a.location}):C.type===`partial`?e=s(`inventory.assignPartialMismatchMessage`,{spoolMaterial:C.spoolMaterial,trayMaterial:C.trayMaterial,location:a.location}):C.type===`material_profile`?e=`${s(`inventory.assignMismatchMessage`,{spoolMaterial:C.spoolMaterial,trayMaterial:C.trayMaterial,location:a.location})}\n\n${s(`inventory.assignProfileMismatchMessage`,{spoolProfile:C.spoolProfile||s(`common.unknown`),trayProfile:C.trayProfile||s(`common.unknown`),location:a.location})}`:C.type===`partial_profile`&&(e=`${s(`inventory.assignPartialMismatchMessage`,{spoolMaterial:C.spoolMaterial,trayMaterial:C.trayMaterial,location:a.location})}\n\n${s(`inventory.assignProfileMismatchMessage`,{spoolProfile:C.spoolProfile||s(`common.unknown`),trayProfile:C.trayProfile||s(`common.unknown`),location:a.location})}`),e=`${e}\n\n${s(`inventory.assignReconfigureNote`)}`,(0,G.jsx)(Qd,{title:s(`inventory.assignMismatchTitle`),message:e,confirmText:s(`inventory.assignMismatchConfirm`),variant:`warning`,overlayZIndex:`z-[110]`,isLoading:P.isPending,onConfirm:ne,onCancel:()=>{P.isPending||(S(!1),b(null),w(null))}})})()]})}var XOe={bambuModelByShortCode:{}},AH={"A1 MINI":[`A1M`],"H2D PRO":[`H2DP`]};function jH(e,t){let n=e.toUpperCase(),r=t.toUpperCase();if(n===r)return!0;let i=AH[r];if(i&&i.includes(n))return!0;let a=AH[n];return!!(a&&a.includes(r))}function ZOe(e){let t={};for(let[n,r]of Object.entries(e))r in t||(t[r]=n.replace(/^Bambu Lab\s+/,``));return t}function MH(e={}){return{bambuModelByShortCode:ZOe(e)}}function NH(e){return e.replace(/\s+/g,``).toLowerCase()}function PH(e){return e.replace(/^#\s*/,``).trim()}var QOe=`0.4`;function FH(e){let t=e.match(/^(.*?)\s+([\d.]+)\s*nozzle\s*$/i);return t?{stripped:t[1].trim(),nozzle:t[2]}:{stripped:e.trim(),nozzle:null}}function $Oe(e){let t=e.indexOf(`@BBL `);if(t<0)return null;let{stripped:n,nozzle:r}=FH(e.slice(t+5).trim());return n?{token:n,nozzle:r}:null}function IH(e){let t=PH(e).match(/^Bambu Lab\s+(.+)$/i);if(!t)return null;let{stripped:n,nozzle:r}=FH(t[1]);return n?{model:n,nozzle:r}:null}function eke(e){return e.replace(/\s*\([^)]*\)\s*$/,``).trim()}var tke=.1,nke=2;function LH(e,t){let n=Number.parseFloat(e),r=Number.parseFloat(t);return Number.isNaN(n)||Number.isNaN(r)?!1:n===r}function rke(e){let t=eke(e),n=$Oe(t);if(n)return n;let r=t.lastIndexOf(`@`);if(r<0)return null;let i=t.slice(r+1).trim(),a=IH(i);if(a)return{token:a.model,nozzle:a.nozzle};let o=i.match(/^([\d.]+)\s*(?:mm)?\s*(?:nozzle)?$/i);if(o){let e=Number.parseFloat(o[1]);if(!Number.isNaN(e)&&e>=tke&&e<=nke)return{token:null,nozzle:o[1]}}return null}function ike(e,t,n){let r=rke(e);if(!r)return`unknown`;let i=IH(t);if(!i)return`unknown`;if(r.token===null)return i.nozzle!==null&&r.nozzle!==null&&!LH(r.nozzle,i.nozzle)?`mismatch`:`unknown`;let a=n[r.token]??r.token;return NH(i.model)!==NH(a)&&!jH(r.token,i.model)||i.nozzle!==null&&!LH(r.nozzle??QOe,i.nozzle)?`mismatch`:`match`}function RH(e,t,n,r){if(!n)return`unknown`;let i=e.compatible_printers;if(i&&i.length>0){let e=PH(n);return i.some(t=>PH(t)===e)?`match`:`mismatch`}return ike(e.name,n,r.bambuModelByShortCode)}function ake(e){let t=e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`).replace(/\s+/g,`\\s+`);return RegExp(`\\b${t}\\b`,`i`)}function zH(e,t){let n=e.indexOf(`@`);if(n>=0){let r=e.slice(n+1).trim(),i=r.match(/^BBL\s+(.+?)(?:\s+[\d.]+\s*nozzle)?$/i);if(i)return i[1].trim();let a=r.match(/^Bambu Lab\s+(.+?)(?:\s+[\d.]+\s*nozzle)?$/i);if(a){let e=a[1].trim(),n=`Bambu Lab ${e}`;if(t[n])return t[n];let r=n.toLowerCase();for(let[e,n]of Object.entries(t))if(e.toLowerCase()===r)return n;return e}}let r=[],i=new Set;for(let[e,n]of Object.entries(t)){let t=e.replace(/^Bambu Lab\s+/,``),a=t.toLowerCase();i.has(a)||(r.push({token:t,short:n}),i.add(a));let o=n.toLowerCase();i.has(o)||(r.push({token:n,short:n}),i.add(o))}r.sort((e,t)=>t.token.length-e.token.length);for(let{token:t,short:n}of r)if(ake(t).test(e))return n;return null}var BH=[`PLA`,`PETG`,`ABS`,`TPU`,`ASA`,`PC`,`PA`,`PVA`,`HIPS`,`PA-CF`,`PETG-CF`,`PLA-CF`],VH=[`Bambu`,`PolyLite`,`PolyTerra`,`eSUN`,`Overture`,`Fiberon`,`SUNLU`,`Inland`,`Hatchbox`,`Generic`],HH=`Basic.Matte.Silk.Silk+.Tough.Tough+.HF.High Flow.Engineering.CF.GF.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`.split(`.`),UH=[{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`},{name:`Clear`,hex:`00000000`}],oke=[{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`}],WH=[...UH,...oke],GH=`bambuddy-recent-colors`,KH=[`0.2`,`0.4`,`0.6`,`0.8`];async function qH(e,t){let n=Lp(t),r=Array.from(new Set([...KH,...n])),i=[];for(let t of r)i.push(await Z.getKProfiles(e,t).catch(()=>null));let a=[];for(let e of i)if(e)for(let t of e.profiles)a.push({cali_idx:t.slot_id,filament_id:t.filament_id,setting_id:t.setting_id||``,name:t.name,k_value:parseFloat(t.k_value)||0,n_coef:parseFloat(t.n_coef)||0,extruder_id:t.extruder_id,nozzle_diameter:t.nozzle_diameter,nozzle_id:t.nozzle_id});return a}var ske=[{code:`GFL00`,name:`Bambu PLA Basic`,displayName:`Bambu PLA Basic`,isCustom:!1,allCodes:[`GFL00`],source:`builtin`},{code:`GFL01`,name:`Bambu PLA Matte`,displayName:`Bambu PLA Matte`,isCustom:!1,allCodes:[`GFL01`],source:`builtin`},{code:`GFL05`,name:`Generic PLA`,displayName:`Generic PLA`,isCustom:!1,allCodes:[`GFL05`],source:`builtin`},{code:`GFG00`,name:`Bambu PETG Basic`,displayName:`Bambu PETG Basic`,isCustom:!1,allCodes:[`GFG00`],source:`builtin`},{code:`GFG05`,name:`Generic PETG`,displayName:`Generic PETG`,isCustom:!1,allCodes:[`GFG05`],source:`builtin`},{code:`GFB00`,name:`Bambu ABS Basic`,displayName:`Bambu ABS Basic`,isCustom:!1,allCodes:[`GFB00`],source:`builtin`},{code:`GFB05`,name:`Generic ABS`,displayName:`Generic ABS`,isCustom:!1,allCodes:[`GFB05`],source:`builtin`},{code:`GFA00`,name:`Bambu ASA Basic`,displayName:`Bambu ASA Basic`,isCustom:!1,allCodes:[`GFA00`],source:`builtin`},{code:`GFU00`,name:`Bambu TPU 95A`,displayName:`Bambu TPU 95A`,isCustom:!1,allCodes:[`GFU00`],source:`builtin`},{code:`GFU05`,name:`Generic TPU`,displayName:`Generic TPU`,isCustom:!1,allCodes:[`GFU05`],source:`builtin`},{code:`GFC00`,name:`Bambu PC Basic`,displayName:`Bambu PC Basic`,isCustom:!1,allCodes:[`GFC00`],source:`builtin`},{code:`GFN00`,name:`Bambu PA Basic`,displayName:`Bambu PA Basic`,isCustom:!1,allCodes:[`GFN00`],source:`builtin`},{code:`GFN05`,name:`Generic PA`,displayName:`Generic PA`,isCustom:!1,allCodes:[`GFN05`],source:`builtin`},{code:`GFS00`,name:`Bambu PLA-CF`,displayName:`Bambu PLA-CF`,isCustom:!1,allCodes:[`GFS00`],source:`builtin`},{code:`GFT00`,name:`Bambu PETG-CF`,displayName:`Bambu PETG-CF`,isCustom:!1,allCodes:[`GFT00`],source:`builtin`},{code:`GFNC0`,name:`Bambu PA-CF`,displayName:`Bambu PA-CF`,isCustom:!1,allCodes:[`GFNC0`],source:`builtin`},{code:`GFV00`,name:`Bambu PVA`,displayName:`Bambu PVA`,isCustom:!1,allCodes:[`GFV00`],source:`builtin`}];function JH(e){let t=e.replace(/@.*$/,``).trim();t=t.replace(/\(Custom\)/i,``).trim(),t=t.replace(/^[#*]+\s*/,``).trim();let 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`.split(`.`),r=``,i=-1;for(let e of n){let n=t.toUpperCase().indexOf(e.toUpperCase());if(n!==-1){r=e,i=n;break}}let a=``;i>0&&(a=t.substring(0,i).trim(),a=a.replace(/[-_\s]+$/,``));let o=``;i!==-1&&r&&(o=t.substring(i+r.length).trim(),o=o.replace(/^[-_\s]+/,``));let s=``;for(let e of HH)if(o.toLowerCase().includes(e.toLowerCase())){s=e;break}if(!s&&a)for(let e of HH){let t=RegExp(`\\s+${e}$`,`i`);if(t.test(a)){s=e,a=a.replace(t,``).trim();break}}return{brand:a,material:r,variant:s}}function YH(e,t){let n=new Set(VH);for(let t of e){let{brand:e}=JH(t.name);e&&e.length>1&&n.add(e)}if(t)for(let e of t)if(e.filament_vendor&&e.filament_vendor.length>1)n.add(e.filament_vendor);else{let{brand:t}=JH(e.name);t&&t.length>1&&n.add(t)}return Array.from(n).sort((e,t)=>e.localeCompare(t))}function cke(e){let t=e.filter(e=>e.preset_type===`filament`);return t.length===0?[]:t.map(e=>{let t=String(e.id),n=e.filament_type||t,r=Array.from(new Set([t,n]));return{code:t,name:e.name,displayName:e.name,isCustom:!1,allCodes:r,source:`local`}}).sort((e,t)=>e.displayName.localeCompare(t.displayName))}function XH(e,t,n,r,i){let a=[],o=[],s=new Set;for(let n of e)if(n.is_custom){let e=n.name.toUpperCase();(t.size===0||Array.from(t).some(t=>e.includes(t))||!e.includes(`@`))&&(a.push({code:n.setting_id,name:n.name,displayName:`${n.name} (Custom)`,isCustom:!0,allCodes:[n.setting_id],source:i?.has(n.setting_id)?`orca_cloud`:`cloud`}),s.add(n.setting_id))}else o.push({code:n.setting_id,name:n.name,displayName:n.name,isCustom:!1,allCodes:[n.setting_id],source:i?.has(n.setting_id)?`orca_cloud`:`cloud`}),s.add(n.setting_id);let c=n&&n.length>0?cke(n):[],l=[];if(r&&r.length>0)for(let e of r){let t=e.filament_id.startsWith(`GF`)?`GFS`+e.filament_id.slice(2):e.filament_id;s.has(e.filament_id)||s.has(t)||l.push({code:e.filament_id,name:e.name,displayName:e.name,isCustom:!1,allCodes:[e.filament_id,t],source:`builtin`})}let u=[...a,...o,...c,...l];return u.length===0?ske:u.sort((e,t)=>e.displayName.localeCompare(t.displayName))}function ZH(e,t){if(!e)return;let n=t.find(t=>t.code===e);if(n||=t.find(t=>t.allCodes.includes(e)),!n){let r=e.toLowerCase();n=t.find(e=>e.code.toLowerCase()===r||e.allCodes.some(e=>e.toLowerCase()===r))}return n}function QH(e,t){let n=t.trim();return!n||e.some(e=>e.toLowerCase()===n.toLowerCase())?e:[...e,n].sort((e,t)=>e.localeCompare(t))}function $H(e,t,n){if(!t)return[];let r=n.get(t.toLowerCase());return!r||r.size===0?[]:e.filter(e=>r.has(e.toLowerCase()))}function eU(){try{let e=localStorage.getItem(GH);if(e)return JSON.parse(e)}catch{}return[]}function tU(e,t){let n=[e,...t.filter(t=>t.hex.toUpperCase()!==e.hex.toUpperCase())].slice(0,8);try{localStorage.setItem(GH,JSON.stringify(n))}catch{}return n}function nU(e){if(!e)return``;let t=e.split(`_`)[0];return/^GFS/i.test(t)&&(t=t.slice(0,2)+t.slice(3)),t.toUpperCase()}function lke(e){return!!e&&/^GF[A-Z]99$/i.test(e)}var uke={GFB99:`ABS`,GFC99:`PC`,GFG99:`PETG`,GFL99:`PLA`,GFN99:`PA`,GFP99:`PE`,GFR99:`EVA`,GFS99:`PVA`,GFU99:`TPU`};function dke(e){return e&&uke[e.toUpperCase()]||``}function rU(e){let t=e.trim().toUpperCase();return t===`NYLON`?`PA`:t}function fke(e,t){let n=dke(e);return!!n&&!!t&&rU(n)===rU(t)}function iU(e,t,n){return`${e}:${t}:${n}`}function aU(e,t){return`${e}\u0000${t}`}function pke(e){let[t=``,n=``]=e.split(`\0`);return{model:t,diameter:n}}function oU(e,t){if(!t.material)return!1;let n=nU(t.slicer_filament),r=nU(e.filament_id);if(n&&r&&n===r){if(!lke(r))return!0;let e=t.brand.trim();if((!e||e.toUpperCase()===`GENERIC`)&&fke(r,t.material))return!0}let i=(e.name||``).replace(/^High Flow[_\s]+/i,``).replace(/^Standard[_\s]+/i,``).replace(/^HF[_\s]+/i,``).replace(/^S[_\s]+/i,``).trim(),a=JH(i);return!(a.material.toUpperCase()!==t.material.toUpperCase()||t.brand&&!(a.brand.toLowerCase().includes(t.brand.toLowerCase())||t.brand.toLowerCase().includes(a.brand.toLowerCase()))||t.subtype&&!(a.variant.toLowerCase().includes(t.subtype.toLowerCase())||t.subtype.toLowerCase().includes(a.variant.toLowerCase())||i.toLowerCase().includes(t.subtype.toLowerCase())))}function sU(){let e=(0,y.useRef)(null),t=(0,y.useCallback)(()=>{e.current!==null&&(clearTimeout(e.current),e.current=null)},[]),n=(0,y.useCallback)((n,r)=>{t(),e.current=setTimeout(()=>{e.current=null,n()},r)},[t]);return(0,y.useEffect)(()=>t,[t]),{schedule:n,cancel:t}}function cU(e){let t=e.includes(`_`)?e.split(`_`)[0]:e;return t.startsWith(`GFS`)?`GF`+t.slice(3):(t.startsWith(`PFUS`)||t.startsWith(`PFSP`),t)}var lU=[`PLA`,`PETG`,`PCTG`,`ABS`,`ASA`,`TPU`,`PC`,`PA`,`NYLON`,`PVA`,`HIPS`,`PP`,`PET`];function uU(e){let t=e.replace(/@.+$/,``).trim(),n=t.toUpperCase(),r=n.match(/\bSUPPORT\s+FOR\s+/);if(r){let e=n.slice(r.index+r[0].length);for(let n of lU)if(RegExp(`\\b${n}\\b`).test(e))return{material:n,brand:t.slice(0,r.index).trim(),variant:`Support`}}for(let e of lU){let r=RegExp(`\\b${e}\\b`,`i`);if(r.test(n)){let n=t.split(r);return{material:e,brand:n[0]?.trim()||``,variant:n[1]?.trim()||``}}}let i=t.split(/\s+/);return i.length>=2?{material:i[1],brand:i[0],variant:i.slice(2).join(` `)}:{material:t,brand:``,variant:``}}function dU(e){return`${e.extruder_id??0}|${e.name}|${e.k_value}`}function fU(e,t,n){return n===void 0?e.find(e=>e.slot_id===t):e.find(e=>e.slot_id===t&&(e.extruder_id??0)===n)}function pU(e,t,n){return t?` \u00b7 ${e.extruder_id===1?n(`common.left`):n(`common.right`)}`:``}function mke(e){return!e.startsWith(`GF`)&&!e.startsWith(`P1`)}var hke={white:`FFFFFF`,black:`000000`,red:`FF0000`,green:`00FF00`,blue:`0000FF`,yellow:`FFFF00`,cyan:`00FFFF`,magenta:`FF00FF`,orange:`FFA500`,purple:`800080`,pink:`FFC0CB`,brown:`8B4513`,gray:`808080`,grey:`808080`,"jade white":`FFFEF2`,ivory:`FFFFF0`,beige:`F5F5DC`,cream:`FFFDD0`,silver:`C0C0C0`,gold:`FFD700`,bronze:`CD7F32`,copper:`B87333`,navy:`000080`,teal:`008080`,olive:`808000`,maroon:`800000`,coral:`FF7F50`,salmon:`FA8072`,lime:`32CD32`,mint:`98FF98`,"forest green":`228B22`,"sky blue":`87CEEB`,"royal blue":`4169E1`,turquoise:`40E0D0`,lavender:`E6E6FA`,violet:`EE82EE`,plum:`DDA0DD`,tan:`D2B48C`,chocolate:`D2691E`,charcoal:`36454F`,slate:`708090`,transparent:`000000`,natural:`F5F5DC`,wood:`DEB887`},mU=[{name:`White`,hex:`FFFFFF`},{name:`Black`,hex:`000000`},{name:`Red`,hex:`FF0000`},{name:`Blue`,hex:`0000FF`},{name:`Green`,hex:`00AA00`},{name:`Yellow`,hex:`FFFF00`},{name:`Orange`,hex:`FFA500`},{name:`Gray`,hex:`808080`}],hU=[{name:`Cyan`,hex:`00FFFF`},{name:`Magenta`,hex:`FF00FF`},{name:`Purple`,hex:`800080`},{name:`Pink`,hex:`FFC0CB`},{name:`Brown`,hex:`8B4513`},{name:`Beige`,hex:`F5F5DC`},{name:`Navy`,hex:`000080`},{name:`Teal`,hex:`008080`},{name:`Lime`,hex:`32CD32`},{name:`Gold`,hex:`FFD700`},{name:`Silver`,hex:`C0C0C0`},{name:`Maroon`,hex:`800000`},{name:`Olive`,hex:`808000`},{name:`Coral`,hex:`FF7F50`},{name:`Salmon`,hex:`FA8072`},{name:`Turquoise`,hex:`40E0D0`},{name:`Violet`,hex:`EE82EE`},{name:`Indigo`,hex:`4B0082`},{name:`Chocolate`,hex:`D2691E`},{name:`Tan`,hex:`D2B48C`},{name:`Slate`,hex:`708090`},{name:`Charcoal`,hex:`36454F`},{name:`Ivory`,hex:`FFFFF0`},{name:`Cream`,hex:`FFFDD0`}];function gU(e){return hke[e.toLowerCase().trim()]||null}function _U({isOpen:e,onClose:t,printerId:n,slotInfo:r,nozzleDiameter:i=`0.4`,printerModel:a,onSuccess:o,fullScreen:s}){let{t:c}=U(),[l,u]=(0,y.useState)(``),[d,f]=(0,y.useState)(null),p=(0,y.useRef)(null);p.current=d;let[m,h]=(0,y.useState)(``),[g,_]=(0,y.useState)(``),[v,b]=(0,y.useState)(``),[x,S]=(0,y.useState)(!1),[C,w]=(0,y.useState)(!1),T=(0,y.useRef)(``),{schedule:E}=sU(),{data:D,isLoading:O,isError:k}=K({queryKey:[`cloudSettings`],queryFn:()=>Z.getCloudSettings(),enabled:e,retry:!1}),{data:A}=K({queryKey:[`orcaCloudProfilesForAmsSlot`],queryFn:()=>Z.orcaCloudListProfiles(),enabled:e,retry:!1}),{data:j,isLoading:M}=K({queryKey:[`localPresets`],queryFn:()=>Z.getLocalPresets(),enabled:e}),{data:N,isLoading:P}=K({queryKey:[`builtinFilaments`],queryFn:()=>Z.getBuiltinFilaments(),enabled:e,staleTime:1/0}),{data:F,isLoading:I}=K({queryKey:[`kprofiles`,n,i],queryFn:()=>Z.getKProfiles(n,i),enabled:e&&!!n}),{data:L}=K({queryKey:[`colorCatalog`],queryFn:()=>Z.getColorCatalog(),enabled:e,staleTime:1/0}),{data:R}=K({queryKey:[`slicerPrinterModels`],queryFn:Z.getSlicerPrinterModels,enabled:e,staleTime:1/0}),{data:z}=K({queryKey:[`slot-spool-defaults`,n,r.amsId,r.trayId],queryFn:()=>Z.getSlotSpoolDefaults(n,r.amsId,r.trayId),enabled:e,staleTime:0}),B=(0,y.useMemo)(()=>MH(R??{}),[R]),V=(0,y.useMemo)(()=>{if(!a||!R)return null;for(let[e,t]of Object.entries(R))if(t===a)return`${e.startsWith(`Bambu Lab `)?e:`Bambu Lab ${e}`} ${i} nozzle`;return null},[a,R,i]),ee=q({mutationFn:async()=>{if(!l)throw Error(`No filament preset selected`);let e=l.startsWith(`local_`),t=l.startsWith(`builtin_`),a=l.startsWith(`orca_`)?l.replace(`orca_`,``):l,o=!e&&!t?A?.filament.find(e=>e.setting_id===a):void 0,s=!!o,c=o??null,u=e?parseInt(l.replace(`local_`,``),10):null,d=t?l.replace(`builtin_`,``):null,f=e?j?.filament.find(e=>e.id===u):null,h=t?N?.find(e=>e.filament_id===d):null,g=!e&&!t&&!s?D?.filament.find(e=>e.setting_id===l):null;if(!e&&!t&&!s&&!g)throw Error(`Selected preset not found`);if(e&&!f)throw Error(`Selected local preset not found`);if(t&&!h)throw Error(`Selected builtin preset not found`);if(s&&!c)throw Error(`Selected Orca Cloud preset not found`);let _=e?f.name:t?h.name:s?c.name:g.name,v=uU(_),y=p.current?.slot_id??-1,b=m||r.trayColor?.slice(0,6)||`FFFFFF`,x=_.replace(/@.+$/,``).trim(),S,C,w=v.material.toUpperCase(),T={PLA:`GFL99`,"PLA-CF":`GFL98`,"PLA SILK":`GFL96`,"PLA HIGH SPEED":`GFL95`,PETG:`GFG99`,"PETG HF":`GFG96`,"PETG-CF":`GFG98`,PCTG:`GFG97`,ABS:`GFB99`,ASA:`GFB98`,PC:`GFC99`,PA:`GFN99`,"PA-CF":`GFN98`,NYLON:`GFN99`,TPU:`GFU99`,PVA:`GFS99`,HIPS:`GFS98`,PE:`GFP99`,PP:`GFP97`};if(e){let e=(lU.includes(w)?w:f?.filament_type||v.material||``).toUpperCase();S=T[e]||T[e.replace(/[-\s]?CF$/,``)]||T[e.replace(/\+$/,``)]||T[e.split(/[-\s]/)[0]]||``,C=``}else if(s){let e=``;try{let t=(await Z.orcaCloudGetProfile(a)).setting?.filament_id;typeof t==`string`&&t&&(e=t)}catch(e){console.warn(`Failed to fetch Orca Cloud profile for filament_id:`,e)}if(S=e,!S){let e=(lU.includes(w)?w:v.material||``).toUpperCase();S=T[e]||T[e.replace(/[-\s]?CF$/,``)]||T[e.replace(/\+$/,``)]||T[e.split(/[-\s]/)[0]]||``}C=``}else if(t)S=d,C=``;else{if(S=cU(l),C=l,!l.startsWith(`GFS`))try{let e=await Z.getCloudSettingDetail(l),t=e.setting?.filament_id,n=e.filament_id||(typeof t==`string`?t:``);n&&(S=n)}catch(e){console.warn(`Failed to fetch preset detail for filament_id:`,e)}/^(PFUS|PFSP|PFCN)/.test(S)&&(console.warn(`Cloud preset ${l} carries no filament_id in either place; sending no tray_info_idx so the printer keeps a resolvable one.`),S=``)}let E=e&&f?.nozzle_temp_min?f.nozzle_temp_min:190,O=e&&f?.nozzle_temp_max?f.nozzle_temp_max:230;if(!e||t||s||!f?.nozzle_temp_min&&!f?.nozzle_temp_max){let t=(e?lU.includes(w)?w:f?.filament_type||v.material||``:v.material).toUpperCase();t.includes(`PLA`)?(E=190,O=230):t.includes(`PETG`)?(E=220,O=260):t.includes(`ABS`)||t.includes(`ASA`)?(E=240,O=280):t.includes(`TPU`)?(E=200,O=240):t===`PCTG`?(E=220,O=260):t.includes(`PC`)?(E=260,O=300):(t.includes(`PA`)||t.includes(`NYLON`))&&(E=250,O=290)}let k=p.current?.k_value?parseFloat(p.current.k_value):0,M=e?lU.includes(w)?w:f?.filament_type||v.material||`PLA`:s&&lU.includes(w)?w:v.material||`PLA`,P=await Z.configureAmsSlot(n,r.amsId,r.trayId,{tray_info_idx:S,tray_type:M,tray_sub_brands:x,tray_color:b+`FF`,nozzle_temp_min:E,nozzle_temp_max:O,cali_idx:y,nozzle_diameter:i,setting_id:C,kprofile_filament_id:p.current?.filament_id,kprofile_setting_id:p.current?.setting_id||void 0,k_value:k}),F=e?`local_${u}`:t?`builtin_${d}`:l,I=e?`local`:t?`builtin`:s?`orca_cloud`:`cloud`;try{await Z.saveSlotPreset(n,r.amsId,r.trayId,F,x,I)}catch(e){console.warn(`Failed to save slot preset mapping:`,e)}return P},onSuccess:()=>{S(!0),o?.(),E(()=>{S(!1),t()},1500)}}),te=q({mutationFn:async()=>Z.resetAmsSlot(n,r.amsId,r.trayId),onSuccess:()=>{S(!0),o?.(),E(()=>{S(!1),t()},1500)}}),ne=(0,y.useMemo)(()=>{let e=v.toLowerCase(),t=[],n=new Set,i=r.savedPresetId,o=r.trayInfoIdx;if(A?.filament)for(let r of A.filament){let i=`orca_${r.setting_id}`;if(n.add(r.setting_id),n.add(i),!(e&&!r.name.toLowerCase().includes(e))){if(a){let e=zH(r.name,R??{});if(e&&!jH(e,a))continue}t.push({id:i,name:r.name,source:`orca_cloud`,isUser:!0})}}if(D?.filament)for(let r of D.filament){if(n.has(r.setting_id))continue;n.add(r.setting_id);let s=i===r.setting_id||o&&(r.setting_id===o||cU(r.setting_id)===o);if(!(e&&!r.name.toLowerCase().includes(e))){if(!s&&a){let e=zH(r.name,R??{});if(e&&!jH(e,a))continue}t.push({id:r.setting_id,name:r.name,source:`cloud`,isUser:mke(r.setting_id)})}}if(j?.filament){let n=r.savedPresetId;for(let r of j.filament){let i=`local_${r.id}`;if(!(e&&!r.name.toLowerCase().includes(e))){if(n!==i&&V){let e=null;if(r.compatible_printers)try{let t=JSON.parse(r.compatible_printers);Array.isArray(t)&&(e=t.filter(e=>typeof e==`string`))}catch{e=null}if(RH({name:r.name,compatible_printers:e},`filament`,V,B)===`mismatch`)continue}t.push({id:i,name:r.name,source:`local`,isUser:!1})}}}if(N)for(let r of N){if(n.has(r.filament_id))continue;let i=r.filament_id.startsWith(`GF`)?`GFS`+r.filament_id.slice(2):r.filament_id;n.has(i)||(!e||r.name.toLowerCase().includes(e))&&t.push({id:`builtin_${r.filament_id}`,name:r.name,source:`builtin`,isUser:!1})}return t.sort((e,t)=>{let n={local:0,orca_cloud:1,cloud:2,builtin:3};return e.source===t.source?e.isUser&&!t.isUser?-1:!e.isUser&&t.isUser?1:e.name.localeCompare(t.name):n[e.source]-n[t.source]})},[A?.filament,D?.filament,j?.filament,N,v,a,r.savedPresetId,r.trayInfoIdx,V,B,R]),re=(0,y.useMemo)(()=>{if(!l)return null;let e=null,t=``;if(l.startsWith(`local_`)){let t=parseInt(l.replace(`local_`,``),10);e=j?.filament.find(e=>e.id===t)?.name||null}else if(l.startsWith(`builtin_`)){let n=l.replace(`builtin_`,``);e=N?.find(e=>e.filament_id===n)?.name||null,t=nU(n)}else{let n=l.startsWith(`orca_`)?l.replace(`orca_`,``):l,r=A?.filament.find(e=>e.setting_id===n);if(r)e=r.name;else if(D?.filament){let n=D.filament.find(e=>e.setting_id===l);e=n?.name||null,n&&(t=nU(n.setting_id))}}if(!e)return null;let n=e.replace(/@.+$/,``).trim();n.startsWith(`# `)&&(n=n.slice(2).trim());let r=uU(n);return{fullName:n,material:r.material,brand:r.brand,filamentId:t}},[l,D?.filament,j?.filament,N,A?.filament]),ie=re?.fullName||``,ae=(0,y.useMemo)(()=>{if(!L||!re)return[];let{fullName:e,brand:t}=re,n=e.replace(/^(Bambu\s*(Lab)?|eSUN|Polymaker|Overture|Sunlu|Hatchbox)\s*/i,``).trim();return L.filter(e=>{let r=(e.material||``).toUpperCase(),i=e.manufacturer.toUpperCase();if(!(r===n.toUpperCase()||r.includes(n.toUpperCase())||n.toUpperCase().includes(r)))return!1;if(t){let e=t.toUpperCase();if(!i.includes(e)&&!e.includes(i))return!1}return!0})},[L,re]),oe=(0,y.useMemo)(()=>new Set((F?.profiles??[]).map(e=>e.extruder_id??0)).size>1,[F?.profiles]),se=(0,y.useMemo)(()=>{if(!F?.profiles)return[];if(!re){let e=r.caliIdx;if(e!=null&&e>0){let t=fU(F.profiles,e,r.extruderId);if(t)return[t]}return[]}let{fullName:e,material:t,brand:n,filamentId:i}=re,a=e.toUpperCase(),o=t.toUpperCase(),s=n.toUpperCase()===`GENERIC`?``:n.toUpperCase(),c=i;if(!o||o.length<2)return[];let l=F.profiles.filter(e=>{if(c){let t=nU(e.filament_id);if(t&&t===c)return!0}let t=e.name.toUpperCase();if(s)return!(!t.includes(s)||!t.includes(o));if(t.includes(a)||t.includes(o))return!0;let n={NYLON:[`PA`,`PA-CF`,`PA6`],PA:[`NYLON`]}[o]||[];for(let e of n)if(t.includes(e))return!0;return!1}),u=r.extruderId===void 0?l:l.filter(e=>(e.extruder_id??0)===r.extruderId),d=new Map;for(let e of u){let t=dU(e);d.has(t)||d.set(t,e)}let f=Array.from(d.values()),p=r.caliIdx;if(p!=null&&p>0&&!f.some(e=>e.slot_id===p)){let e=fU(F.profiles,p,r.extruderId);e&&f.unshift(e)}return f},[F?.profiles,re,r.extruderId,r.caliIdx]),H=(0,y.useMemo)(()=>{if(!F?.profiles)return[];let e=new Set(se.map(e=>dU(e))),t=new Map;for(let n of F.profiles){let r=dU(n);e.has(r)||t.has(r)||t.set(r,n)}return Array.from(t.values()).sort((e,t)=>e.name.localeCompare(t.name))},[F?.profiles,se]),ce=se.length>0||H.length>0,le=(0,y.useCallback)(e=>{if(!e){f(null);return}f(se.find(t=>dU(t)===e)||H.find(t=>dU(t)===e)||null)},[se,H]);(0,y.useEffect)(()=>{if(e){if(z?.slicer_filament)u(z.slicer_filament);else if(r.savedPresetId)u(r.savedPresetId);else if(r.trayInfoIdx&&D?.filament){let e=D.filament.find(e=>e.setting_id===r.trayInfoIdx);e||=D.filament.find(e=>cU(e.setting_id)===r.trayInfoIdx),e&&u(e.setting_id)}else if(r.trayInfoIdx&&N?.length){let e=r.trayInfoIdx,t=N.find(t=>t.filament_id===e);t&&u(`builtin_${t.filament_id}`)}if(r.trayColor){let e=r.trayColor.slice(0,6);e&&h(e)}}else u(``),f(null),h(``),_(``),b(``),S(!1),T.current=``},[e,z?.slicer_filament,r.savedPresetId,r.trayInfoIdx,r.trayColor,D?.filament,N]),(0,y.useEffect)(()=>{if(se.length>0){if(z?.cali_idx!=null){let e=fU(se,z.cali_idx,z.extruder??r.extruderId);if(e){f(e);return}}if(r.caliIdx!=null&&r.caliIdx>0){let e=fU(se,r.caliIdx,r.extruderId);if(e){f(e);return}}f(se[0])}else f(null)},[l,se,z?.cali_idx,z?.extruder,r.caliIdx,r.extruderId]);let ue=(0,y.useCallback)(e=>{e.key===`Escape`&&t()},[t]);(0,y.useEffect)(()=>{if(e)return document.addEventListener(`keydown`,ue),()=>document.removeEventListener(`keydown`,ue)},[e,ue]);let de=O&&!k||M||P||I;if((0,y.useEffect)(()=>{if(!de&&l&&l!==T.current){let e=requestAnimationFrame(()=>{let e=document.querySelector(`[class*="fixed inset-0 z-50"]`)?.querySelector(`[data-preset-id="${CSS.escape(l)}"]`);e&&(T.current=l,e.scrollIntoView({block:`nearest`}))});return()=>cancelAnimationFrame(e)}},[l,de]),!e)return null;let fe=l&&!ee.isPending,pe=m||r.trayColor||`FFFFFF`;return(0,G.jsxs)(`div`,{className:`fixed inset-0 z-50 flex ${s?``:`items-center justify-center`}`,children:[!s&&(0,G.jsx)(`div`,{className:`absolute inset-0 bg-black/60 backdrop-blur-sm`,onClick:t}),(0,G.jsxs)(`div`,{className:s?`relative w-full h-full bg-bambu-dark-secondary flex flex-col`:`relative w-full max-w-lg mx-4 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl`,children:[(0,G.jsxs)(`div`,{className:`flex items-center justify-between p-4 border-b border-bambu-dark-tertiary shrink-0`,children:[(0,G.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,G.jsx)(eu,{className:`w-5 h-5 text-bambu-blue`}),(0,G.jsx)(`h2`,{className:`text-lg font-semibold text-white`,children:c(`configureAmsSlot.title`)}),s&&(0,G.jsxs)(`div`,{className:`flex items-center gap-2 ml-4 text-sm text-bambu-gray`,children:[(0,G.jsx)(`span`,{className:`text-white/30`,children:`|`}),r.trayColor&&(0,G.jsx)(`span`,{className:`w-4 h-4 rounded-full border border-black/20`,style:Tf(r.trayColor)}),(0,G.jsx)(`span`,{className:`text-white/70`,children:c(`configureAmsSlot.slotLabel`,{ams:fp(r.amsId,r.trayCount),slot:r.trayId+1})}),r.traySubBrands&&(0,G.jsxs)(`span`,{children:[`(`,r.traySubBrands,`)`]})]})]}),(0,G.jsx)(`button`,{onClick:t,className:`p-1 text-bambu-gray hover:text-white rounded transition-colors`,children:(0,G.jsx)(ed,{className:`w-5 h-5`})})]}),(0,G.jsxs)(`div`,{className:`p-4 overflow-y-auto ${s?`flex-1 min-h-0`:`space-y-4 max-h-[60vh]`}`,children:[x&&(0,G.jsx)(`div`,{className:`absolute inset-0 bg-bambu-dark-secondary/95 z-10 flex items-center justify-center rounded-xl`,children:(0,G.jsxs)(`div`,{className:`text-center space-y-3`,children:[(0,G.jsx)(bs,{className:`w-16 h-16 text-bambu-green mx-auto`}),(0,G.jsx)(`p`,{className:`text-lg font-semibold text-white`,children:c(`configureAmsSlot.slotConfigured`)}),(0,G.jsx)(`p`,{className:`text-sm text-bambu-gray`,children:c(`configureAmsSlot.settingsSentToPrinter`)})]})}),!s&&(0,G.jsxs)(`div`,{className:`p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary`,children:[(0,G.jsx)(`p`,{className:`text-xs text-bambu-gray mb-1`,children:c(`configureAmsSlot.configuringSlot`)}),(0,G.jsxs)(`div`,{className:`flex items-center gap-2`,children:[r.trayColor&&(0,G.jsx)(`span`,{className:`w-4 h-4 rounded-full border border-black/20`,style:Tf(r.trayColor)}),(0,G.jsx)(`span`,{className:`text-white font-medium`,children:c(`configureAmsSlot.slotLabel`,{ams:fp(r.amsId,r.trayCount),slot:r.trayId+1})}),r.traySubBrands&&(0,G.jsxs)(`span`,{className:`text-bambu-gray`,children:[`(`,r.traySubBrands,`)`]})]})]}),de?(0,G.jsx)(`div`,{className:`flex justify-center py-8`,children:(0,G.jsx)(Y,{className:`w-6 h-6 text-bambu-green animate-spin`})}):s?(0,G.jsxs)(`div`,{className:`flex gap-4 h-full`,children:[(0,G.jsxs)(`div`,{className:`w-1/2 flex flex-col min-h-0`,children:[(0,G.jsxs)(`label`,{className:`block text-sm text-bambu-gray mb-2`,children:[c(`configureAmsSlot.filamentProfile`),` `,(0,G.jsx)(`span`,{className:`text-red-600 dark:text-red-400`,children:`*`})]}),(0,G.jsx)(`input`,{type:`text`,placeholder:c(`configureAmsSlot.searchPresets`),value:v,onChange:e=>b(e.target.value),className:`w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder:text-bambu-gray focus:border-bambu-green focus:outline-none mb-2 shrink-0`}),(0,G.jsx)(`div`,{className:`flex-1 min-h-0 overflow-y-auto space-y-1`,children:ne.length===0?(0,G.jsx)(`p`,{className:`text-center py-4 text-bambu-gray`,children:D?.filament?.length===0&&!j?.filament?.length?c(`configureAmsSlot.noPresetsAvailable`):c(`configureAmsSlot.noMatchingPresets`)}):ne.map(e=>(0,G.jsx)(`button`,{"data-preset-id":e.id,onClick:()=>u(e.id),className:`group w-full p-2 rounded-lg border text-left transition-colors ${l===e.id?`bg-bambu-green/20 border-bambu-green`:`bg-bambu-dark border-bambu-dark-tertiary hover:border-bambu-gray`}`,children:(0,G.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,G.jsx)(`span`,{className:`text-white text-sm truncate group-hover:whitespace-normal group-hover:break-all`,title:e.name,children:e.name}),(0,G.jsxs)(`div`,{className:`flex items-center gap-1 flex-shrink-0`,children:[e.source===`local`&&(0,G.jsx)(`span`,{className:`text-xs px-1.5 py-0.5 rounded bg-green-100 dark:bg-green-500/20 text-green-700 dark:text-green-400`,children:c(`profiles.localProfiles.badge`)}),e.source===`orca_cloud`&&(0,G.jsx)(`span`,{className:`text-xs px-1.5 py-0.5 rounded bg-purple-100 dark:bg-purple-500/20 text-purple-700 dark:text-purple-400`,children:c(`configureAmsSlot.orcaCloud`)}),e.source===`cloud`&&(0,G.jsx)(`span`,{className:`text-xs px-1.5 py-0.5 rounded bg-bambu-blue/20 text-bambu-blue`,children:c(`configureAmsSlot.bambuCloud`)}),e.source===`builtin`&&(0,G.jsx)(`span`,{className:`text-xs px-1.5 py-0.5 rounded bg-amber-100 dark:bg-amber-500/20 text-amber-700 dark:text-amber-400`,children:c(`configureAmsSlot.builtin`)})]})]})},e.id))})]}),(0,G.jsxs)(`div`,{className:`w-1/2 flex flex-col gap-4 min-h-0 overflow-y-auto`,children:[(0,G.jsxs)(`div`,{children:[(0,G.jsxs)(`label`,{className:`block text-sm text-bambu-gray mb-2`,children:[c(`configureAmsSlot.kProfileLabel`),ie&&(0,G.jsx)(`span`,{className:`ml-2 text-xs text-bambu-blue`,children:c(`configureAmsSlot.filteringFor`,{material:ie})})]}),ce?(0,G.jsxs)(`div`,{className:`relative`,children:[(0,G.jsxs)(`select`,{value:d?dU(d):``,onChange:e=>le(e.target.value),className:`w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none appearance-none pr-10`,children:[(0,G.jsx)(`option`,{value:``,children:c(`configureAmsSlot.noKProfile`)}),se.map(e=>(0,G.jsxs)(`option`,{value:dU(e),children:[e.name,` (K=`,e.k_value,`)`,pU(e,oe,c),pU(e,oe,c)]},dU(e))),H.length>0&&(0,G.jsx)(`optgroup`,{label:c(`configureAmsSlot.otherKProfiles`),children:H.map(e=>(0,G.jsxs)(`option`,{value:dU(e),children:[e.name,` (K=`,e.k_value,`)`,pU(e,oe,c),pU(e,oe,c),pU(e,oe,c)]},dU(e)))})]}),(0,G.jsx)(ds,{className:`absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none`})]}):l?(0,G.jsx)(`p`,{className:`text-sm text-bambu-gray italic py-2`,children:c(`configureAmsSlot.noMatchingKProfiles`)}):(0,G.jsx)(`span`,{className:`inline-block text-xs px-2 py-1 rounded bg-amber-100 dark:bg-amber-500/20 text-amber-700 dark:text-amber-400 border border-amber-300 dark:border-amber-500/30`,children:c(`configureAmsSlot.selectFilamentFirst`)}),d&&(0,G.jsx)(`p`,{className:`text-xs text-bambu-green mt-1`,children:c(`configureAmsSlot.kFromCalibration`,{value:d.k_value})})]}),(0,G.jsxs)(`div`,{children:[(0,G.jsx)(`label`,{className:`block text-sm text-bambu-gray mb-2`,children:c(`configureAmsSlot.customColorLabel`)}),ae.length>0&&(0,G.jsxs)(`div`,{className:`mb-3`,children:[(0,G.jsx)(`p`,{className:`text-xs text-bambu-gray mb-1.5`,children:c(`configureAmsSlot.presetColors`,{name:re?.fullName})}),(0,G.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,children:ae.map(e=>(0,G.jsxs)(`button`,{onClick:()=>{h(e.hex_color.replace(`#`,``).toUpperCase()),_(e.color_name)},className:`h-7 px-2 rounded-md border-2 transition-all flex items-center gap-1.5 ${m===e.hex_color.replace(`#`,``).toUpperCase()?`border-bambu-green scale-105`:`border-white/20 hover:border-white/40`}`,title:e.color_name,children:[(0,G.jsx)(`span`,{className:`w-4 h-4 rounded-full border border-black/20 flex-shrink-0`,style:{backgroundColor:e.hex_color}}),(0,G.jsx)(`span`,{className:`text-xs text-white/80 whitespace-nowrap`,children:e.color_name})]},e.id))})]}),(0,G.jsxs)(`div`,{className:`flex flex-wrap gap-1.5 mb-2`,children:[mU.map(e=>(0,G.jsx)(`button`,{onClick:()=>{h(e.hex),_(e.name)},className:`w-7 h-7 rounded-md border-2 transition-all ${m===e.hex?`border-bambu-green scale-110`:`border-white/20 hover:border-white/40`}`,style:{backgroundColor:`#${e.hex}`},title:e.name},e.hex)),(0,G.jsx)(`button`,{onClick:()=>w(!C),className:`w-7 h-7 rounded-md border-2 border-white/20 hover:border-white/40 flex items-center justify-center text-white/60 hover:text-white/80 transition-all text-xs`,title:c(C?`configureAmsSlot.showLessColors`:`configureAmsSlot.showMoreColors`),children:C?`−`:`+`})]}),C&&(0,G.jsx)(`div`,{className:`flex flex-wrap gap-1.5 mb-2`,children:hU.map(e=>(0,G.jsx)(`button`,{onClick:()=>{h(e.hex),_(e.name)},className:`w-7 h-7 rounded-md border-2 transition-all ${m===e.hex?`border-bambu-green scale-110`:`border-white/20 hover:border-white/40`}`,style:{backgroundColor:`#${e.hex}`},title:e.name},e.hex))}),(0,G.jsxs)(`div`,{className:`flex gap-2 items-center`,children:[(0,G.jsx)(`div`,{className:`w-10 h-10 rounded-lg border-2 border-white/20 flex-shrink-0`,style:Tf(pe)}),(0,G.jsx)(`input`,{type:`text`,placeholder:c(`configureAmsSlot.colorPlaceholder`),value:g,onChange:e=>{let t=e.target.value;_(t);let n=gU(t);if(n)h(n);else{let e=t.replace(/[^0-9A-Fa-f]/g,``).toUpperCase();e.length===6?h(e):e.length===3&&h(e.split(``).map(e=>e+e).join(``))}},className:`flex-1 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder:text-bambu-gray focus:border-bambu-green focus:outline-none text-sm`}),m&&(0,G.jsx)(`button`,{onClick:()=>{h(``),_(``)},className:`px-2 py-1 text-xs text-bambu-gray hover:text-white bg-bambu-dark-tertiary rounded`,title:c(`configureAmsSlot.clearCustomColor`),children:c(`configureAmsSlot.clear`)})]}),m&&(0,G.jsx)(`p`,{className:`text-xs text-bambu-gray mt-1.5`,children:c(`configureAmsSlot.hexLabel`,{hex:m})})]})]})]}):(0,G.jsxs)(G.Fragment,{children:[(0,G.jsxs)(`div`,{children:[(0,G.jsxs)(`label`,{className:`block text-sm text-bambu-gray mb-2`,children:[c(`configureAmsSlot.filamentProfile`),` `,(0,G.jsx)(`span`,{className:`text-red-600 dark:text-red-400`,children:`*`})]}),(0,G.jsxs)(`div`,{className:`relative`,children:[(0,G.jsx)(`input`,{type:`text`,placeholder:c(`configureAmsSlot.searchPresets`),value:v,onChange:e=>b(e.target.value),className:`w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder:text-bambu-gray focus:border-bambu-green focus:outline-none mb-2`}),(0,G.jsx)(`div`,{className:`max-h-48 overflow-y-auto space-y-1`,children:ne.length===0?(0,G.jsx)(`p`,{className:`text-center py-4 text-bambu-gray`,children:D?.filament?.length===0&&!j?.filament?.length?c(`configureAmsSlot.noPresetsAvailable`):c(`configureAmsSlot.noMatchingPresets`)}):ne.map(e=>(0,G.jsx)(`button`,{"data-preset-id":e.id,onClick:()=>u(e.id),className:`group w-full p-2 rounded-lg border text-left transition-colors ${l===e.id?`bg-bambu-green/20 border-bambu-green`:`bg-bambu-dark border-bambu-dark-tertiary hover:border-bambu-gray`}`,children:(0,G.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,G.jsx)(`span`,{className:`text-white text-sm truncate group-hover:whitespace-normal group-hover:break-all`,title:e.name,children:e.name}),(0,G.jsxs)(`div`,{className:`flex items-center gap-1 flex-shrink-0`,children:[e.source===`local`&&(0,G.jsx)(`span`,{className:`text-xs px-1.5 py-0.5 rounded bg-green-100 dark:bg-green-500/20 text-green-700 dark:text-green-400`,children:c(`profiles.localProfiles.badge`)}),e.source===`orca_cloud`&&(0,G.jsx)(`span`,{className:`text-xs px-1.5 py-0.5 rounded bg-purple-100 dark:bg-purple-500/20 text-purple-700 dark:text-purple-400`,children:c(`configureAmsSlot.orcaCloud`)}),e.source===`cloud`&&(0,G.jsx)(`span`,{className:`text-xs px-1.5 py-0.5 rounded bg-bambu-blue/20 text-bambu-blue`,children:c(`configureAmsSlot.bambuCloud`)}),e.source===`builtin`&&(0,G.jsx)(`span`,{className:`text-xs px-1.5 py-0.5 rounded bg-amber-100 dark:bg-amber-500/20 text-amber-700 dark:text-amber-400`,children:c(`configureAmsSlot.builtin`)})]})]})},e.id))})]})]}),(0,G.jsxs)(`div`,{children:[(0,G.jsxs)(`label`,{className:`block text-sm text-bambu-gray mb-2`,children:[c(`configureAmsSlot.kProfileLabel`),ie&&(0,G.jsx)(`span`,{className:`ml-2 text-xs text-bambu-blue`,children:c(`configureAmsSlot.filteringFor`,{material:ie})})]}),ce?(0,G.jsxs)(`div`,{className:`relative`,children:[(0,G.jsxs)(`select`,{value:d?dU(d):``,onChange:e=>le(e.target.value),className:`w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none appearance-none pr-10`,children:[(0,G.jsx)(`option`,{value:``,children:c(`configureAmsSlot.noKProfile`)}),se.map(e=>(0,G.jsxs)(`option`,{value:dU(e),children:[e.name,` (K=`,e.k_value,`)`,pU(e,oe,c)]},dU(e))),H.length>0&&(0,G.jsx)(`optgroup`,{label:c(`configureAmsSlot.otherKProfiles`),children:H.map(e=>(0,G.jsxs)(`option`,{value:dU(e),children:[e.name,` (K=`,e.k_value,`)`,pU(e,oe,c),pU(e,oe,c),pU(e,oe,c)]},dU(e)))})]}),(0,G.jsx)(ds,{className:`absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none`})]}):l?(0,G.jsx)(`p`,{className:`text-sm text-bambu-gray italic py-2`,children:c(`configureAmsSlot.noMatchingKProfiles`)}):(0,G.jsx)(`span`,{className:`inline-block text-xs px-2 py-1 rounded bg-amber-100 dark:bg-amber-500/20 text-amber-700 dark:text-amber-400 border border-amber-300 dark:border-amber-500/30`,children:c(`configureAmsSlot.selectFilamentFirst`)}),d&&(0,G.jsx)(`p`,{className:`text-xs text-bambu-green mt-1`,children:c(`configureAmsSlot.kFromCalibration`,{value:d.k_value})})]}),(0,G.jsxs)(`div`,{children:[(0,G.jsx)(`label`,{className:`block text-sm text-bambu-gray mb-2`,children:c(`configureAmsSlot.customColorLabel`)}),ae.length>0&&(0,G.jsxs)(`div`,{className:`mb-3`,children:[(0,G.jsx)(`p`,{className:`text-xs text-bambu-gray mb-1.5`,children:c(`configureAmsSlot.presetColors`,{name:re?.fullName})}),(0,G.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,children:ae.map(e=>(0,G.jsxs)(`button`,{onClick:()=>{h(e.hex_color.replace(`#`,``).toUpperCase()),_(e.color_name)},className:`h-7 px-2 rounded-md border-2 transition-all flex items-center gap-1.5 ${m===e.hex_color.replace(`#`,``).toUpperCase()?`border-bambu-green scale-105`:`border-white/20 hover:border-white/40`}`,title:e.color_name,children:[(0,G.jsx)(`span`,{className:`w-4 h-4 rounded-full border border-black/20 flex-shrink-0`,style:{backgroundColor:e.hex_color}}),(0,G.jsx)(`span`,{className:`text-xs text-white/80 whitespace-nowrap`,children:e.color_name})]},e.id))})]}),(0,G.jsxs)(`div`,{className:`flex flex-wrap gap-1.5 mb-2`,children:[mU.map(e=>(0,G.jsx)(`button`,{onClick:()=>{h(e.hex),_(e.name)},className:`w-7 h-7 rounded-md border-2 transition-all ${m===e.hex?`border-bambu-green scale-110`:`border-white/20 hover:border-white/40`}`,style:{backgroundColor:`#${e.hex}`},title:e.name},e.hex)),(0,G.jsx)(`button`,{onClick:()=>w(!C),className:`w-7 h-7 rounded-md border-2 border-white/20 hover:border-white/40 flex items-center justify-center text-white/60 hover:text-white/80 transition-all text-xs`,title:c(C?`configureAmsSlot.showLessColors`:`configureAmsSlot.showMoreColors`),children:C?`−`:`+`})]}),C&&(0,G.jsx)(`div`,{className:`flex flex-wrap gap-1.5 mb-2`,children:hU.map(e=>(0,G.jsx)(`button`,{onClick:()=>{h(e.hex),_(e.name)},className:`w-7 h-7 rounded-md border-2 transition-all ${m===e.hex?`border-bambu-green scale-110`:`border-white/20 hover:border-white/40`}`,style:{backgroundColor:`#${e.hex}`},title:e.name},e.hex))}),(0,G.jsxs)(`div`,{className:`flex gap-2 items-center`,children:[(0,G.jsx)(`div`,{className:`w-10 h-10 rounded-lg border-2 border-white/20 flex-shrink-0`,style:Tf(pe)}),(0,G.jsx)(`input`,{type:`text`,placeholder:c(`configureAmsSlot.colorPlaceholder`),value:g,onChange:e=>{let t=e.target.value;_(t);let n=gU(t);if(n)h(n);else{let e=t.replace(/[^0-9A-Fa-f]/g,``).toUpperCase();e.length===6?h(e):e.length===3&&h(e.split(``).map(e=>e+e).join(``))}},className:`flex-1 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder:text-bambu-gray focus:border-bambu-green focus:outline-none text-sm`}),m&&(0,G.jsx)(`button`,{onClick:()=>{h(``),_(``)},className:`px-2 py-1 text-xs text-bambu-gray hover:text-white bg-bambu-dark-tertiary rounded`,title:c(`configureAmsSlot.clearCustomColor`),children:c(`configureAmsSlot.clear`)})]}),m&&(0,G.jsx)(`p`,{className:`text-xs text-bambu-gray mt-1.5`,children:c(`configureAmsSlot.hexLabel`,{hex:m})})]})]})]}),(0,G.jsxs)(`div`,{className:`flex justify-between p-4 border-t border-bambu-dark-tertiary shrink-0`,children:[(0,G.jsx)(Q,{variant:`secondary`,onClick:()=>te.mutate(),disabled:te.isPending||ee.isPending,className:`text-red-600 dark:text-red-400 hover:text-red-700 dark:hover:text-red-300 hover:bg-red-50 dark:hover:bg-red-500/10`,children:te.isPending?(0,G.jsxs)(G.Fragment,{children:[(0,G.jsx)(Y,{className:`w-4 h-4 animate-spin`}),c(`configureAmsSlot.resetting`)]}):(0,G.jsxs)(G.Fragment,{children:[(0,G.jsx)(Hl,{className:`w-4 h-4`}),c(`configureAmsSlot.resetSlot`)]})}),(0,G.jsxs)(`div`,{className:`flex gap-2`,children:[(0,G.jsx)(Q,{variant:`secondary`,onClick:t,children:c(`configureAmsSlot.cancel`)}),(0,G.jsx)(Q,{onClick:()=>ee.mutate(),disabled:!fe,children:ee.isPending?(0,G.jsxs)(G.Fragment,{children:[(0,G.jsx)(Y,{className:`w-4 h-4 animate-spin`}),c(`configureAmsSlot.configuring`)]}):(0,G.jsxs)(G.Fragment,{children:[(0,G.jsx)(eu,{className:`w-4 h-4`}),c(`configureAmsSlot.configureSlot`)]})})]})]}),(ee.isError||te.isError)&&(0,G.jsx)(`div`,{className:`mx-4 mb-4 p-2 bg-red-100 dark:bg-red-500/20 border border-red-300 dark:border-red-500/50 rounded text-sm text-red-700 dark:text-red-400`,children:ee.error?.message||te.error?.message})]})]})}function vU({className:e=`w-4 h-4`}){return(0,G.jsx)(`svg`,{viewBox:`0 0 1945 1370`,fill:`none`,className:e,"aria-hidden":`true`,children:(0,G.jsxs)(`g`,{transform:`translate(-754.293 -471.685)`,children:[(0,G.jsxs)(`g`,{transform:`translate(0.18191 255.976)`,children:[(0,G.jsx)(`g`,{transform:`matrix(1.05469 0 0 0.241063 -153.484 1120.2)`,children:(0,G.jsx)(`rect`,{x:`922.048`,y:`1195.15`,width:`1721.5`,height:`470.135`,stroke:`currentColor`,strokeOpacity:`0.99`,strokeWidth:`168.84`,strokeLinecap:`round`,strokeLinejoin:`round`})}),(0,G.jsx)(`g`,{transform:`matrix(0.983656 0 0 1.0767 -62.2035 141.539)`,children:(0,G.jsx)(`path`,{d:`M2741.42,1175.93L895.832,1175.93L1125.16,621.902L2512.09,621.902L2741.42,1175.93Z`,fill:`currentColor`,fillOpacity:`0.05`,stroke:`currentColor`,strokeOpacity:`0.99`,strokeWidth:`125.26`,strokeLinecap:`round`,strokeLinejoin:`round`})})]}),(0,G.jsx)(`g`,{transform:`translate(21.1916 0.684817)`,children:(0,G.jsx)(`path`,{d:`M1981.31,567.518C1954.86,567.518 1933.39,546.047 1933.39,519.601C1933.39,493.156 1954.86,471.685 1981.31,471.685L2146.61,471.685C2173.07,471.685 2194.53,493.138 2194.53,519.601L2194.53,688.741C2194.53,715.187 2173.05,736.658 2146.61,736.658C2120.16,736.658 2098.69,715.187 2098.69,688.741L2098.69,567.518L1981.31,567.518ZM2098.69,1252.54C2098.69,1226.1 2120.16,1204.62 2146.61,1204.62C2173.05,1204.62 2194.53,1226.1 2194.53,1252.54L2194.53,1421.68C2194.53,1448.14 2173.07,1469.6 2146.61,1469.6L1981.31,1469.6C1954.86,1469.6 1933.39,1448.13 1933.39,1421.68C1933.39,1395.24 1954.86,1373.76 1981.31,1373.76L2098.69,1373.76L2098.69,1252.54ZM1430.29,1373.76C1456.74,1373.76 1478.21,1395.24 1478.21,1421.68C1478.21,1448.13 1456.74,1469.6 1430.29,1469.6L1264.99,1469.6C1238.53,1469.6 1217.07,1448.14 1217.07,1421.68L1217.07,1252.54C1217.07,1226.1 1238.55,1204.62 1264.99,1204.62C1291.44,1204.62 1312.91,1226.1 1312.91,1252.54L1312.91,1373.76L1430.29,1373.76ZM1312.91,688.741C1312.91,715.187 1291.44,736.658 1264.99,736.658C1238.55,736.658 1217.07,715.187 1217.07,688.741L1217.07,519.601C1217.07,493.138 1238.53,471.685 1264.99,471.685L1430.29,471.685C1456.74,471.685 1478.21,493.156 1478.21,519.601C1478.21,546.047 1456.74,567.518 1430.29,567.518L1312.91,567.518L1312.91,688.741Z`,fill:`currentColor`,fillOpacity:`0.99`})})]})})}function yU({folderId:e,onClose:t,onUploadComplete:n,onFileUploaded:r,autoUpload:i,validateFile:a,accept:o,initialFiles:s}){let{t:c}=U(),[l,u]=(0,y.useState)([]),[d,f]=(0,y.useState)(!1),[p,m]=(0,y.useState)(!1),[h,g]=(0,y.useState)(!0),[_,v]=(0,y.useState)(!1),[b,x]=(0,y.useState)(!0),[S,C]=(0,y.useState)(null),w=(0,y.useRef)(null),T=e=>{e.preventDefault(),f(!0)},E=e=>{e.preventDefault(),f(!1)},D=e=>{e.preventDefault(),f(!1),j(Array.from(e.dataTransfer.files))},O=e=>{e.target.files&&j(Array.from(e.target.files))},k=(e,t)=>{u(n=>n.map(n=>n.file===e?{...n,...t}:n))},A=async i=>{m(!0);for(let t of i)if(t.status===`pending`){k(t.file,{status:`uploading`});try{if(t.isZip){let n=await Z.extractZipFile(t.file,e,h,_,b);k(t.file,{status:n.errors.length>0&&n.extracted===0?`error`:`success`,extractedCount:n.extracted,error:n.errors.length>0?c(`fileManager.zipFilesFailed`,`{{count}} files failed`,{count:n.errors.length}):void 0})}else{let n=await Z.uploadLibraryFile(t.file,e,b);k(t.file,{status:`success`});let i=r?.(n);if(i){C(i),u([]),m(!1);return}}}catch(e){k(t.file,{status:`error`,error:e instanceof Error?e.message:c(`fileManager.uploadFailed`,`Upload failed`)})}}m(!1),n(),u(e=>(e.some(e=>e.status===`error`)||t(),e))},j=e=>{if(C(null),a)for(let t of e){let e=a(t);if(e){C(e);return}}let t=e.map(e=>({file:e,status:`pending`,isZip:e.name.toLowerCase().endsWith(`.zip`),is3mf:e.name.toLowerCase().endsWith(`.3mf`)}));u(e=>[...e,...t]),i&&e.length>0&&A(t)},M=e=>{u(t=>t.filter((t,n)=>n!==e))},N=(0,y.useRef)(!1);(0,y.useEffect)(()=>{N.current||!s||s.length===0||(N.current=!0,j(s))},[]);let P=l.some(e=>e.isZip&&e.status===`pending`),F=l.some(e=>e.file.name.toLowerCase().endsWith(`.stl`)&&e.status===`pending`),I=l.some(e=>e.is3mf&&e.status===`pending`),L=l.filter(e=>e.status===`pending`).length,R=l.length>0&&L===0&&!p;return(0,G.jsx)(`div`,{className:`fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4`,children:(0,G.jsxs)(`div`,{className:`bg-bambu-dark-secondary rounded-lg w-full max-w-lg border border-bambu-dark-tertiary`,children:[(0,G.jsxs)(`div`,{className:`p-4 border-b border-bambu-dark-tertiary flex items-center justify-between`,children:[(0,G.jsx)(`h2`,{className:`text-lg font-semibold text-white`,children:c(`fileManager.uploadFiles`)}),(0,G.jsx)(`button`,{onClick:t,className:`p-1 hover:bg-bambu-dark rounded`,children:(0,G.jsx)(ed,{className:`w-5 h-5 text-bambu-gray`})})]}),(0,G.jsxs)(`div`,{className:`p-4 space-y-4`,children:[(0,G.jsxs)(`div`,{onDragOver:T,onDragLeave:E,onDrop:D,onClick:()=>w.current?.click(),className:`border-2 border-dashed rounded-lg p-8 text-center cursor-pointer transition-colors ${d?`border-bambu-green bg-bambu-green/10`:`border-bambu-dark-tertiary hover:border-bambu-green/50`}`,children:[(0,G.jsx)(zu,{className:`w-10 h-10 mx-auto mb-3 ${d?`text-bambu-green`:`text-bambu-gray`}`}),(0,G.jsx)(`p`,{className:`text-white font-medium`,children:c(d?`fileManager.dropFilesHere`:`fileManager.dragDropFiles`)}),(0,G.jsx)(`p`,{className:`text-sm text-bambu-gray mt-1`,children:c(`fileManager.orClickToBrowse`)}),(0,G.jsx)(`p`,{className:`text-xs text-bambu-gray/70 mt-2`,children:c(`fileManager.allFileTypesSupported`)})]}),(0,G.jsx)(`input`,{ref:w,type:`file`,multiple:!0,accept:o,className:`hidden`,onChange:O}),P&&(0,G.jsx)(`div`,{className:`p-3 bg-blue-50 dark:bg-blue-500/10 border border-blue-300 dark:border-blue-500/30 rounded-lg`,children:(0,G.jsxs)(`div`,{className:`flex items-start gap-3`,children:[(0,G.jsx)(Mo,{className:`w-5 h-5 text-blue-600 dark:text-blue-400 mt-0.5 flex-shrink-0`}),(0,G.jsxs)(`div`,{className:`flex-1`,children:[(0,G.jsx)(`p`,{className:`text-sm text-blue-700 dark:text-blue-300 font-medium`,children:c(`fileManager.zipFilesDetected`)}),(0,G.jsx)(`p`,{className:`text-xs text-blue-700/80 dark:text-blue-300/70 mt-1`,children:c(`fileManager.zipExtractOptions`)}),(0,G.jsxs)(`label`,{className:`flex items-center gap-2 mt-2 cursor-pointer`,children:[(0,G.jsx)(`input`,{type:`checkbox`,checked:h,onChange:e=>g(e.target.checked),className:`w-4 h-4 rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green`}),(0,G.jsx)(`span`,{className:`text-sm text-white`,children:c(`fileManager.preserveZipStructure`)})]}),(0,G.jsxs)(`label`,{className:`flex items-center gap-2 mt-2 cursor-pointer`,children:[(0,G.jsx)(`input`,{type:`checkbox`,checked:_,onChange:e=>v(e.target.checked),className:`w-4 h-4 rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green`}),(0,G.jsx)(`span`,{className:`text-sm text-white`,children:c(`fileManager.createFolderFromZip`)})]})]})]})}),I&&(0,G.jsx)(`div`,{className:`p-3 bg-purple-50 dark:bg-purple-500/10 border border-purple-300 dark:border-purple-500/30 rounded-lg`,children:(0,G.jsxs)(`div`,{className:`flex items-start gap-3`,children:[(0,G.jsx)(Il,{className:`w-5 h-5 text-purple-600 dark:text-purple-400 mt-0.5 flex-shrink-0`}),(0,G.jsxs)(`div`,{className:`flex-1`,children:[(0,G.jsx)(`p`,{className:`text-sm text-purple-700 dark:text-purple-300 font-medium`,children:c(`fileManager.threemfDetected`)}),(0,G.jsx)(`p`,{className:`text-xs text-purple-700/80 dark:text-purple-300/70 mt-1`,children:c(`fileManager.threemfExtractionInfo`)})]})]})}),(F||P)&&(0,G.jsx)(`div`,{className:`p-3 bg-bambu-green/10 border border-bambu-green/30 rounded-lg`,children:(0,G.jsxs)(`div`,{className:`flex items-start gap-3`,children:[(0,G.jsx)(Bc,{className:`w-5 h-5 text-bambu-green mt-0.5 flex-shrink-0`}),(0,G.jsxs)(`div`,{className:`flex-1`,children:[(0,G.jsx)(`p`,{className:`text-sm text-bambu-green font-medium`,children:c(`fileManager.stlThumbnailGeneration`)}),(0,G.jsx)(`p`,{className:`text-xs text-bambu-green/70 mt-1`,children:c(P&&!F?`fileManager.zipMayContainStl`:`fileManager.thumbnailsCanBeGenerated`)}),(0,G.jsxs)(`label`,{className:`flex items-center gap-2 mt-2 cursor-pointer`,children:[(0,G.jsx)(`input`,{type:`checkbox`,checked:b,onChange:e=>x(e.target.checked),className:`w-4 h-4 rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green`}),(0,G.jsx)(`span`,{className:`text-sm text-white`,children:c(`fileManager.generateThumbnailsForStl`)})]})]})]})}),l.length>0&&(0,G.jsx)(`div`,{className:`max-h-48 overflow-y-auto space-y-2`,children:l.map((e,t)=>(0,G.jsxs)(`div`,{className:`flex items-center gap-3 p-2 bg-bambu-dark rounded-lg`,children:[e.isZip?(0,G.jsx)(Mo,{className:`w-4 h-4 text-blue-600 dark:text-blue-400 flex-shrink-0`}):(0,G.jsx)(dc,{className:`w-4 h-4 text-bambu-gray flex-shrink-0`}),(0,G.jsxs)(`div`,{className:`flex-1 min-w-0`,children:[(0,G.jsx)(`p`,{className:`text-sm text-white truncate`,children:e.file.name}),(0,G.jsxs)(`p`,{className:`text-xs text-bambu-gray`,children:[(e.file.size/1024/1024).toFixed(2),` MB`,e.isZip&&e.status===`pending`&&(0,G.jsxs)(`span`,{className:`text-blue-700 dark:text-blue-400 ml-2`,children:[`• `,c(`fileManager.willBeExtracted`)]}),e.extractedCount!==void 0&&(0,G.jsxs)(`span`,{className:`text-green-700 dark:text-green-400 ml-2`,children:[`• `,c(`fileManager.filesExtracted`,{count:e.extractedCount})]})]}),e.status===`error`&&e.error&&(0,G.jsx)(`p`,{className:`text-xs text-red-700 dark:text-red-400 mt-1 break-words`,children:e.error})]}),e.status===`pending`&&(0,G.jsx)(`button`,{onClick:()=>M(t),className:`p-1 hover:bg-bambu-dark-tertiary rounded`,children:(0,G.jsx)(ed,{className:`w-4 h-4 text-bambu-gray`})}),e.status===`uploading`&&(0,G.jsx)(Y,{className:`w-4 h-4 text-bambu-green animate-spin`}),e.status===`success`&&(0,G.jsx)(ys,{className:`w-4 h-4 text-green-500`}),e.status===`error`&&(0,G.jsx)(`span`,{title:e.error,children:(0,G.jsx)(Ts,{className:`w-4 h-4 text-red-500`})})]},t))}),S&&(0,G.jsx)(`div`,{className:`p-3 bg-red-50 dark:bg-red-500/10 border border-red-300 dark:border-red-500/30 rounded-lg`,children:(0,G.jsxs)(`div`,{className:`flex items-start gap-3`,children:[(0,G.jsx)(Ts,{className:`w-5 h-5 text-red-600 dark:text-red-400 mt-0.5 flex-shrink-0`}),(0,G.jsx)(`p`,{className:`text-sm text-red-700 dark:text-red-300`,children:S})]})})]}),(0,G.jsxs)(`div`,{className:`p-4 border-t border-bambu-dark-tertiary flex justify-end gap-2`,children:[(0,G.jsx)(Q,{variant:`secondary`,onClick:t,children:c(`common.cancel`)}),!R&&(0,G.jsx)(Q,{onClick:()=>A(l),disabled:L===0||p,children:p?(0,G.jsxs)(G.Fragment,{children:[(0,G.jsx)(Y,{className:`w-4 h-4 mr-2 animate-spin`}),c(`fileManager.uploading`)]}):(0,G.jsxs)(G.Fragment,{children:[(0,G.jsx)(zu,{className:`w-4 h-4 mr-2`}),c(`common.upload`),` `,L>0?`(${L})`:``]})})]})]})})}function bU(e){if(!e)return null;let t=[e.brand,e.material,e.subtype].filter(Boolean);return t.length>0?t.join(` `):null}function xU(e,t){let n=[],r=e?.ams_extruder_map,i=!!e?.nozzles?.[1]?.nozzle_diameter||r&&Object.keys(r).length>0||(e?.vt_tray?.length??0)>1;e?.ams?.forEach(e=>{let i=e.tray.length===1;e.tray.forEach(a=>{if(a.tray_type){let o=sp(a.tray_color),s=wp(e.id,a.id,!1),c=t?.get(s);n.push({type:a.tray_type,color:o,colorName:c?.color_name?.trim()||bf(o,a.tray_sub_brands),amsId:e.id,trayId:a.id,isHt:i,isExternal:!1,label:Cp(e.id,a.id,i,!1),globalTrayId:s,trayInfoIdx:a.tray_info_idx||``,traySubBrands:a.tray_sub_brands||``,spoolName:bU(c)??void 0,extruderId:r?.[String(e.id)],remain:a.remain??-1})}})});for(let r of e?.vt_tray??[])if(r.tray_type){let a=sp(r.tray_color),o=r.id??254,s=(e?.vt_tray?.length??0)>1,c=t?.get(o);n.push({type:r.tray_type,color:a,colorName:c?.color_name?.trim()||bf(a,r.tray_sub_brands),amsId:-1,trayId:o-254,isHt:!1,isExternal:!0,label:s?o===254?`Ext-L`:`Ext-R`:`External`,globalTrayId:o,trayInfoIdx:r.tray_info_idx||``,traySubBrands:r.tray_sub_brands||``,spoolName:bU(c)??void 0,extruderId:i?255-o:void 0,remain:r.remain??-1})}return n}function SU(e,t,n,r){let i=xU(t);if(i.length!==0)return TU(wU(e,i,{},n,r,t?.fila_switch?.installed===!0))}function gke(e,t){return(0,y.useMemo)(()=>xU(e,t),[e,t])}function CU(e,t){let n=cp(t);return n?cp(e)===n||_p(e,t):!0}function wU(e,t,n,r,i,a=!1){if(!e?.filaments||e.filaments.length===0)return[];let o=new Set(Object.values(n));return e.filaments.map(e=>{let s=e.slot_id||0;if(s>0&&n[s]!==void 0){let r=n[s],i=t.find(e=>e.globalTrayId===r);if(i){let t=gp(i.type,e.type),n=CU(i.color,e.color),r;return r=t&&n?`match`:t?`type_only`:`mismatch`,{...e,loaded:i,hasFilament:!0,typeMatch:t,colorMatch:n,status:r,isManual:!0}}}let c=e.tray_info_idx||``,l=t.filter(e=>!o.has(e.globalTrayId));e.nozzle_id!=null&&!a&&(l=l.filter(t=>t.extruderId===e.nozzle_id)),r&&(l=[...l].sort((e,t)=>Np(Mp(e,i),Mp(t,i))));let u,d,f,p;if(c){let t=l.filter(e=>e.trayInfoIdx===c);t.length===1?u=t[0]:t.length>1&&(r&&t.sort((e,t)=>Np(Mp(e,i),Mp(t,i))),d=t.find(t=>gp(t.type,e.type)&&cp(t.color)===cp(e.color)),d||(f=Sp(t.filter(t=>gp(t.type,e.type)),e.color,e=>e.color)),!d&&!f&&(p=t.find(t=>gp(t.type,e.type))))}!u&&!d&&!f&&!p&&(d=l.find(t=>gp(t.type,e.type)&&cp(t.color)===cp(e.color)),d||(f=Sp(l.filter(t=>gp(t.type,e.type)),e.color,e=>e.color)),!d&&!f&&(p=l.find(t=>gp(t.type,e.type))));let m=u||d||f||p||void 0;m&&o.add(m.globalTrayId);let h=!!m,g=h,_=h&&CU(m.color,e.color),v;return v=h?_?`match`:`type_only`:`mismatch`,{...e,loaded:m,hasFilament:h,typeMatch:g,colorMatch:_,status:v,isManual:!1}})}function TU(e){if(e.length===0)return;let t=Math.max(...e.map(e=>e.slot_id||0));if(t<=0)return;let n=Array(t).fill(-1);return e.forEach(e=>{e.slot_id&&e.slot_id>0&&(n[e.slot_id-1]=e.loaded?.globalTrayId??-1)}),n}function EU(e,t,n,r,i,a){let o=gke(t,a),s=t?.fila_switch?.installed===!0,c=(0,y.useMemo)(()=>wU(e,o,n,r,i,s),[e,o,n,r,s,i]);return{loadedFilaments:o,filamentComparison:c,amsMapping:(0,y.useMemo)(()=>o.length===0?void 0:TU(c),[c,o.length]),hasTypeMismatch:c.some(e=>e.status===`mismatch`),hasColorMismatch:c.some(e=>e.status===`type_only`)}}function _ke(e,t,n,r,i){if(!e||e.length===0)return{exactMatches:0,typeOnlyMatches:0,missingTypes:0,totalSlots:0,status:`full`};let a=0,o=0,s=0,c=new Set(Object.values(n));for(let l of e){let e=l.slot_id||0;if(e>0&&n[e]!==void 0){let r=n[e],i=t.find(e=>e.globalTrayId===r);if(i){let e=gp(i.type,l.type),t=cp(i.color)===cp(l.color)||_p(i.color,l.color);e&&t?a++:e?o++:s++;continue}}let u=t.filter(e=>!c.has(e.globalTrayId));if(l.nozzle_id!=null){let e=u.filter(e=>e.extruderId===l.nozzle_id);e.length>0&&(u=e)}r&&(u=[...u].sort((e,t)=>Np(Mp(e,i),Mp(t,i))));let d=u.find(e=>gp(e.type,l.type)&&cp(e.color)===cp(l.color)),f=d?void 0:Sp(u.filter(e=>gp(e.type,l.type)),l.color,e=>e.color),p=d||f?void 0:u.find(e=>gp(e.type,l.type)),m=d??f??p;m&&c.add(m.globalTrayId),d||f?a++:p?o++:s++}let l=e.length,u=`full`;return s>0?u=`missing`:o>0&&(u=`partial`),{exactMatches:a,typeOnlyMatches:o,missingTypes:s,totalSlots:l,status:u}}function vke(e,t,n,r,i){if(!e?.filaments||e.filaments.length===0)return;let a=xU(t);if(a.length===0)return;let o=new Set(Object.values(n)),s=[];for(let t of e.filaments){let e=t.slot_id||0;if(e>0&&n[e]!==void 0){s.push({slot_id:e,globalTrayId:n[e]});continue}let c=a.filter(e=>!o.has(e.globalTrayId));if(t.nozzle_id!=null){let e=c.filter(e=>e.extruderId===t.nozzle_id);e.length>0&&(c=e)}r&&(c=[...c].sort((e,t)=>Np(Mp(e,i),Mp(t,i))));let l=c.find(e=>gp(e.type,t.type)&&cp(e.color)===cp(t.color)),u=l?void 0:Sp(c.filter(e=>gp(e.type,t.type)),t.color,e=>e.color),d=l||u?void 0:c.find(e=>gp(e.type,t.type)),f=l??u??d;f&&o.add(f.globalTrayId),s.push({slot_id:e,globalTrayId:f?.globalTrayId??-1})}let c=Math.max(...s.map(e=>e.slot_id||0));if(c<=0)return;let l=Array(c).fill(-1);return s.forEach(e=>{e.slot_id&&e.slot_id>0&&(l[e.slot_id-1]=e.globalTrayId)}),l}var DU={useDefault:!0,manualMappings:{},autoConfigured:!1};function yke(e,t,n,r,i,a,o,s){let c=xo({queries:e.map(t=>({queryKey:[`printer-status`,t],queryFn:()=>Z.getPrinterStatus(t),enabled:e.length>0,staleTime:5e3}))}),l=(0,y.useMemo)(()=>e.map((e,a)=>{let l=c[a],u=l?.data,d=t?.find(t=>t.id===e)?.name||`Printer ${e}`,f=xU(u),p=i[e]||DU,m=s?.get(e),h=Pp(o,u?.ams_filament_backup),g=SU(n,u,h,m),_=p.useDefault?r:p.manualMappings,v=vke(n,u,_,h,m),y=_ke(n?.filaments,f,_,h,m);return{printerId:e,printerName:d,status:u,isLoading:l?.isLoading??!1,loadedFilaments:f,autoMapping:g,finalMapping:v,matchStatus:y.status,exactMatches:y.exactMatches,typeOnlyMatches:y.typeOnlyMatches,missingTypes:y.missingTypes,totalSlots:y.totalSlots,config:p,inventoryByTrayId:m}}),[e,c,t,n,i,r,o,s]),u=c.some(e=>e.isLoading),d=(e,t)=>{a(n=>({...n,[e]:{...n[e]||DU,...t}}))},f=e=>{let t=l.find(t=>t.printerId===e);if(!t||!t.status||!n?.filaments)return;let r=SU(n,t.status,Pp(o,t.status?.ams_filament_backup),s?.get(e));if(!r)return;let i={};r.forEach((e,t)=>{e!==-1&&(i[t+1]=e)}),d(e,{useDefault:!1,manualMappings:i,autoConfigured:!0})};return{printerResults:l,isLoading:u,perPrinterConfigs:i,updatePrinterConfig:d,autoConfigureAll:()=>{for(let t of e)f(t)},autoConfigurePrinter:f,getFinalMapping:e=>l.find(t=>t.printerId===e)?.finalMapping,allPrintersReady:l.every(e=>e.matchStatus!==`missing`)}}var OU=`/img/bed`,bke={"cool plate":{icon:`${OU}/bed_cool.png`,label:`Cool Plate`},"pc plate":{icon:`${OU}/bed_cool.png`,label:`Cool Plate`},"cool plate (supertack)":{icon:`${OU}/bed_cool_supertack.png`,label:`Cool Plate SuperTack`},"supertack plate":{icon:`${OU}/bed_cool_supertack.png`,label:`Cool Plate SuperTack`},"bambu cool plate supertack":{icon:`${OU}/bed_cool_supertack.png`,label:`Cool Plate SuperTack`},"engineering plate":{icon:`${OU}/bed_engineering.png`,label:`Engineering Plate`},"high temp plate":{icon:`${OU}/bed_high_templ.png`,label:`High Temp Plate`},"textured pei plate":{icon:`${OU}/bed_pei.png`,label:`Textured PEI Plate`},"pei plate":{icon:`${OU}/bed_pei.png`,label:`PEI Plate`},"smooth pei plate":{icon:`${OU}/bed_pei_cool.png`,label:`Smooth PEI Plate`}};function kU(e){return e?bke[e.trim().toLowerCase()]??null:null}function xke(e,t){if(t==null)return;let n=e?.slicer_ams_mapping;if(!(!n||typeof n!=`object`)&&n.printer_id===t&&!(!Array.isArray(n.mapping)||n.mapping.length===0))return n.mapping}function Ske(e){let t=e.trim().split(/\s+/);return t.length<=1?e.trim():t.slice(1).join(` `)}function AU(e){let{data:t}=K({queryKey:[`builtin-filaments`],queryFn:()=>Z.getBuiltinFilaments(),staleTime:300*1e3}),{data:n}=K({queryKey:[`filament-id-map`],queryFn:()=>Z.getFilamentIdMap(),staleTime:300*1e3}),r=(0,y.useMemo)(()=>{let e={};for(let n of t||[])n.filament_id&&(e[n.filament_id]=n.name);for(let[t,r]of Object.entries(n||{}))t&&r&&(e[t]=r);return e},[t,n]),i=(0,y.useMemo)(()=>(e||[]).map(e=>{let t=e.tray_info_idx&&r[e.tray_info_idx]||e.type;return{resolvedName:t,materialHint:Ske(t),color:e.color}}),[e,r]),a=xo({queries:i.map(({color:e,materialHint:t})=>({queryKey:[`color-by-material`,e,t],queryFn:()=>Z.getColorByMaterial(e,t),enabled:!!e,staleTime:300*1e3}))});return i.map(({resolvedName:e,color:t},n)=>({resolvedName:e,colorLabel:(a[n]?.data?.color_name??null)||bf(t)}))}var jU=Array.from({length:6},(e,t)=>t+1),Cke=0;function MU(e){let t=new Map,n;for(let r of e??[]){if(r.id===Cke){n=r;continue}let e=r.id-15;e>=1&&e<=6&&t.set(e,r)}let r=jU.filter(e=>!t.has(e));return r.length===1&&n&&(n.nozzle_diameter||n.nozzle_type)&&t.set(r[0],n),t}function NU(e,t){if(!e||!e.nozzle_diameter&&!e.nozzle_type)return!1;let n=Number.parseFloat(e.nozzle_diameter),r=Number.parseFloat(t.nozzle_diameter);if(!Number.isFinite(n)||!Number.isFinite(r)||Math.abs(n-r)>.005)return!1;let i=(t.volume_type||``).trim().toLowerCase();if(i&&e.nozzle_type){let t=e.nozzle_type.toUpperCase().startsWith(`HH`);if(i.startsWith(`high flow`)!==t)return!1}return!0}function wke(e,t,n){let r=MU(e);return jU.map(e=>{let i=r.get(e),a=NU(i,t),o;return a||(o=i?n(`printModal.rackWrongNozzle`,{has:`${i.nozzle_diameter||`?`} ${i.nozzle_type||``}`.trim(),needs:`${t.nozzle_diameter} ${t.volume_type}`.trim()}):n(`printModal.rackEmptyPosition`)),{position:e,diameter:i?.nozzle_diameter??``,nozzleType:i?.nozzle_type??``,filamentColor:i?.filament_color??``,eligible:a,reason:o}})}function Tke(e,t,n={}){let r=MU(e),i={},a=new Set,o=[...t.keys()].filter(e=>t.get(e).on_rack).sort((e,t)=>e-t);for(let e of o){let o=n[e];if(o!=null){if(a.has(o)||!NU(r.get(o),t.get(e)))return null;i[e]=o,a.add(o)}}for(let e of o){if(i[e]!=null)continue;let n=t.get(e),o=jU.filter(e=>!a.has(e)&&NU(r.get(e),n));if(o.length===0)return null;let s=PU(n.filament_color),c=(s?o.find(e=>PU(r.get(e)?.filament_color)===s):void 0)??o[0];i[e]=c,a.add(c)}return i}function PU(e){return(e??``).trim().replace(/^#/,``).slice(0,6).toUpperCase()}function FU({printerId:e,filamentReqs:t,manualMappings:n,onManualMappingChange:r,onEstimatedCostChange:i,budgetAvailable:a,quantity:o=1,currencySymbol:s,defaultCostPerKg:c,defaultExpanded:l=!1,forceColorMatch:u,onForceColorMatchChange:d,plateLabel:f,archiveAmsMapping:p,nozzleRackChoice:m,onNozzleRackChoiceChange:h}){let{t:g}=U(),_=oo(),[v,b]=(0,y.useState)(!1),[x,S]=(0,y.useState)(l),[C,w]=(0,y.useState)(!1),T=(0,y.useRef)([]);(0,y.useEffect)(()=>{w(!1),T.current=[]},[p,f,e]);let E=()=>{if(!p||!t?.filaments)return;if(C){let e={...n};for(let t of T.current)delete e[t];r(e),T.current=[],w(!1);return}let e={...n},i=[];for(let n of t.filaments){let t=n.slot_id-1;n.slot_id>0&&t>=0&&t=0&&(e[n.slot_id]=p[t],i.push(n.slot_id))}r(e),T.current=i,w(!0)},{data:D}=K({queryKey:[`printer-status`,e],queryFn:()=>Z.getPrinterStatus(e),enabled:!!e}),{data:O}=K({queryKey:[`spool-assignments`,e],queryFn:()=>Z.getAssignments(e),enabled:!!e}),{data:k}=K({queryKey:[`settings`],queryFn:Z.getSettings}),{data:A}=K({queryKey:[`printer-inventory-remain`,e],queryFn:()=>Z.getInventoryRemain(e),enabled:!!e,staleTime:30*1e3,refetchOnMount:`always`}),j=(0,y.useMemo)(()=>{if(!A?.inventory_remain_g)return;let e=new Map;return Object.entries(A.inventory_remain_g).forEach(([t,n])=>{let r=Number(t);Number.isNaN(r)||e.set(r,n)}),e},[A]),M=(0,y.useMemo)(()=>{let e=A?.slot_materials;if(!e?.length)return;let t=new Map;return e.forEach(e=>{e.spool&&t.set(e.global_tray_id,e.spool)}),t.size>0?t:void 0},[A]),{loadedFilaments:N,filamentComparison:P,hasTypeMismatch:F,hasColorMismatch:I}=EU(t,D,n,Pp(k?.prefer_lowest_filament,D?.ams_filament_backup),j,M),L=AU(t?.filaments),R=(0,y.useMemo)(()=>{let e=new Map;for(let t of O||[]){let n=t.ams_id===255,r=wp(t.ams_id,t.tray_id,n);e.set(r,t.spool?.cost_per_kg??null)}return e},[O]),z=(0,y.useMemo)(()=>{let e=new Map;for(let t of O||[]){let n=t.ams_id===255,r=wp(t.ams_id,t.tray_id,n),i=t.spool;if(!i){e.set(r,null);continue}e.set(r,Math.max(0,Math.round((i.label_weight??0)-(i.weight_used??0))))}return e},[O]),B=(0,y.useMemo)(()=>{let e=0;for(let t of P){let n=t.loaded?.globalTrayId;if(n==null)continue;let r=R.get(n)??null??c;r>0&&(e+=t.used_grams/1e3*r)}return e},[P,R,c]),V=(0,y.useRef)(i);(0,y.useEffect)(()=>{V.current=i},[i]),(0,y.useEffect)(()=>{V.current?.(B>0?B:null)},[B]);let ee=(0,y.useMemo)(()=>Array.from(R.values()).some(e=>e!=null&&e>0),[R]),te=B*Math.max(1,o),ne=a!=null&&te>a,re=t?.filaments&&t.filaments.length>0,ie=t?.filaments?.some(e=>e.nozzle_id!=null)??!1,ae=(0,y.useMemo)(()=>{let e=new Map;for(let n of t?.filaments??[])n.group_id!=null&&n.group&&e.set(n.group_id,n.group);return e},[t]),oe=(D?.nozzle_rack?.some(e=>e.id>=16)??!1)&&[...ae.values()].some(e=>e.on_rack),se=(0,y.useMemo)(()=>oe?Tke(D?.nozzle_rack,ae,m??{})??m??{}:{},[oe,D?.nozzle_rack,ae,m]),H=(e,t)=>{h&&h({...se,[e]:t})},ce=D?.fila_switch?.installed===!0,le=D?.ams_switch_inlet,ue=e=>ce&&le?.[String(e)]||null,de=(0,y.useMemo)(()=>{if(!ce)return null;let e=new Set;for(let t of P){if(!t.loaded||t.loaded.isExternal)return null;let n=ue(t.loaded.amsId);if(!n)return null;e.add(n)}return P.length<2||e.size!==1?null:[...e][0]},[ce,le,P]);if(!re||!D)return null;let fe=F?`#f97316`:I?`#facc15`:`#00ae42`,pe=(e,t)=>{if(e>0)if(t===``){let t={...n};delete t[e],r(t)}else r({...n,[e]:parseInt(t,10)})};return(0,G.jsxs)(`div`,{className:`mb-4`,children:[(0,G.jsxs)(`button`,{type:`button`,onClick:()=>S(!x),className:`flex items-center gap-2 text-sm text-bambu-gray hover:text-white transition-colors w-full`,children:[(0,G.jsx)(Es,{className:`w-4 h-4`,fill:fe,stroke:`none`}),(0,G.jsx)(`span`,{children:f?`${g(`printModal.filamentMapping`)} — ${f}`:g(`printModal.filamentMapping`)}),F?(0,G.jsxs)(`span`,{className:`text-xs text-orange-700 dark:text-orange-400`,children:[`(`,g(`printModal.statusTypeNotFound`),`)`]}):I?(0,G.jsxs)(`span`,{className:`text-xs text-yellow-700 dark:text-yellow-400`,children:[`(`,g(`printModal.statusColorMismatch`),`)`]}):(0,G.jsxs)(`span`,{className:`text-xs text-bambu-green`,children:[`(`,g(`printModal.statusReady`),`)`]}),x?(0,G.jsx)(ms,{className:`w-4 h-4 ml-auto`}):(0,G.jsx)(ds,{className:`w-4 h-4 ml-auto`})]}),x&&(0,G.jsxs)(`div`,{className:`mt-2 bg-bambu-dark rounded-lg p-3 space-y-2`,children:[(0,G.jsxs)(`div`,{className:`flex items-center justify-between mb-2`,children:[(0,G.jsx)(`span`,{className:`text-xs text-bambu-gray`,children:g(`printModal.clickToChangeSlot`)}),(0,G.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[p&&(0,G.jsxs)(`button`,{type:`button`,onClick:E,title:g(`printModal.useArchiveMappingTooltip`),className:`flex items-center gap-1 px-2 py-0.5 text-xs rounded border transition-colors ${C?`border-bambu-green bg-bambu-green/10 text-bambu-green`:`border-bambu-gray/30 hover:border-bambu-gray hover:bg-bambu-dark-tertiary text-bambu-gray hover:text-white`}`,children:[(0,G.jsx)(us,{className:`w-3 h-3`}),(0,G.jsx)(`span`,{children:g(`printModal.useArchiveMapping`)})]}),(0,G.jsxs)(`button`,{type:`button`,onClick:async()=>{b(!0);try{await Z.refreshPrinterStatus(e),await new Promise(e=>setTimeout(e,500)),await _.refetchQueries({queryKey:[`printer-status`,e]})}finally{b(!1)}},className:`flex items-center gap-1 px-2 py-0.5 text-xs rounded border border-bambu-gray/30 hover:border-bambu-gray hover:bg-bambu-dark-tertiary transition-colors text-bambu-gray hover:text-white`,disabled:v,children:[(0,G.jsx)(Bl,{className:`w-3 h-3 ${v?`animate-spin`:``}`}),(0,G.jsx)(`span`,{children:g(`printModal.reRead`)})]})]})]}),de&&(0,G.jsxs)(`div`,{className:`flex items-start gap-1.5 rounded border border-yellow-500/40 bg-yellow-500/10 px-2 py-1.5 text-xs text-yellow-700 dark:text-yellow-400`,children:[(0,G.jsx)(Fu,{className:`w-3 h-3 mt-0.5 shrink-0`}),(0,G.jsx)(`span`,{children:g(`printModal.ftsSameInletHint`,{inlet:de})})]}),P.map((e,t)=>{let n=e.slot_id??0,r=n>0&&d!=null,{resolvedName:i,colorLabel:a}=L[t]??{resolvedName:e.type,colorLabel:bf(e.color)},[o,s]=xf({name:a,hex:e.color},{name:e.loaded?.colorName,hex:e.loaded?.color});return(0,G.jsxs)(`div`,{className:`space-y-1`,children:[(0,G.jsxs)(`div`,{className:`grid items-center gap-2 text-xs`,style:{gridTemplateColumns:oe?`16px minmax(210px, 1.4fr) auto 2fr 16px`:`16px minmax(70px, 1fr) auto 2fr 16px`},children:[(0,G.jsx)(`span`,{title:g(`printModal.requiredTooltip`,{name:i,color:o}),children:(0,G.jsx)(Es,{className:`w-3 h-3`,fill:e.color,stroke:e.color})}),(0,G.jsxs)(`span`,{className:`text-white flex items-center gap-1 min-w-0`,children:[oe&&e.group_id!=null&&e.group?e.group.on_rack?(0,G.jsx)(`select`,{value:se[e.group_id]??``,onChange:t=>H(e.group_id,Number(t.target.value)),disabled:!h,title:g(`printModal.rackPositionTooltip`),"aria-label":g(`printModal.rackPosition`),className:`shrink-0 bg-bambu-dark-tertiary text-white text-[10px] font-bold rounded px-1 py-0.5 border border-bambu-dark-tertiary focus:border-bambu-green outline-none disabled:opacity-60`,children:wke(D?.nozzle_rack,e.group,g).map(e=>(0,G.jsxs)(`option`,{value:e.position,disabled:!e.eligible,title:e.reason,children:[`R`,e.position,e.diameter?` · ${e.diameter}`:``]},e.position))}):(0,G.jsx)(`span`,{className:`inline-flex items-center justify-center w-3.5 h-3.5 rounded text-[9px] font-bold leading-none bg-bambu-gray/20 text-bambu-gray shrink-0`,title:g(`printModal.leftNozzleTooltip`),children:g(`printModal.leftNozzle`)}):ie&&e.nozzle_id!=null?(0,G.jsx)(`span`,{className:`inline-flex items-center justify-center w-3.5 h-3.5 rounded text-[9px] font-bold leading-none bg-bambu-gray/20 text-bambu-gray shrink-0`,title:e.nozzle_id===1?g(`printModal.leftNozzleTooltip`):g(`printModal.rightNozzleTooltip`),children:e.nozzle_id===1?g(`printModal.leftNozzle`):g(`printModal.rightNozzle`)}):null,(0,G.jsx)(`span`,{className:`truncate min-w-0`,title:i,children:i}),(0,G.jsxs)(`span`,{className:`text-bambu-gray shrink-0 whitespace-nowrap`,children:[`(`,e.used_grams,`g)`]})]}),(0,G.jsx)(`span`,{className:`text-bambu-gray`,children:`→`}),(0,G.jsxs)(`select`,{value:e.loaded?.globalTrayId??``,onChange:e=>pe(n,e.target.value),className:`flex-1 px-2 py-1 rounded border text-xs bg-bambu-dark-secondary focus:outline-none focus:ring-1 focus:ring-bambu-green ${e.status===`match`?`border-bambu-green/50 text-bambu-green`:e.status===`type_only`?`border-yellow-500 dark:border-yellow-400/50 text-yellow-700 dark:text-yellow-400`:`border-orange-500 dark:border-orange-400/50 text-orange-700 dark:text-orange-400`} ${e.isManual?`ring-1 ring-blue-400/50`:``}`,title:e.isManual?g(`printModal.manuallySelected`):g(`printModal.autoMatched`),children:[(0,G.jsxs)(`option`,{value:``,className:`bg-bambu-dark text-bambu-gray`,children:[`-- `,g(`printModal.selectSlot`),` --`]}),N.map(e=>{let t=z.get(e.globalTrayId),n=t==null?``:g(`printModal.slotRemainingShort`,{grams:t,defaultValue:` - ${t}g left`}),r=ue(e.amsId),i=r==null?``:` [${lp[r]}]`;return(0,G.jsxs)(`option`,{value:e.globalTrayId,className:`bg-bambu-dark text-white`,children:[e.label,`: `,e.spoolName||e.traySubBrands||e.type,` (`,e.colorName,`)`,n,i]},e.globalTrayId)})]}),e.status===`match`?(0,G.jsx)(us,{className:`w-3 h-3 text-bambu-green`}):e.status===`type_only`?(0,G.jsx)(`span`,{title:o&&s?g(`printModal.sameTypeDifferentColorDetail`,{required:o,loaded:s}):g(`printModal.sameTypeDifferentColor`),children:(0,G.jsx)(Fu,{className:`w-3 h-3 text-yellow-600 dark:text-yellow-400`})}):(0,G.jsx)(`span`,{title:g(`printModal.filamentTypeNotLoaded`),children:(0,G.jsx)(Fu,{className:`w-3 h-3 text-orange-600 dark:text-orange-400`})})]}),r&&(0,G.jsxs)(`label`,{className:`inline-flex items-center gap-1.5 text-xs text-bambu-gray cursor-pointer select-none pl-5`,children:[(0,G.jsx)(`input`,{type:`checkbox`,checked:u?.[n]??!1,onChange:e=>d(n,e.target.checked),className:`accent-bambu-green w-3 h-3`}),(0,G.jsx)(Sl,{className:`w-3 h-3`}),g(`printModal.forceColorMatch`)]})]},t)}),(0,G.jsxs)(`div`,{className:`text-xs text-bambu-gray`,children:[g(`printModal.totalCost`),` `,(0,G.jsx)(`span`,{className:`text-white`,children:B>0||ee?`${s}${B.toFixed(2)}`:`N/A`}),o>1&&B>0&&(0,G.jsx)(`span`,{className:`ml-2`,children:g(`printModal.totalCostForQuantity`,`total: {{cost}}`,{cost:`${s}${te.toFixed(2)}`})})]}),ne&&(0,G.jsx)(`p`,{className:`text-xs text-red-400 mt-2`,children:g(`printModal.insufficientBudget`,`Insufficient budget for this cost center.`)}),F&&(0,G.jsx)(`p`,{className:`text-xs text-orange-700 dark:text-orange-400 mt-2`,children:g(`printModal.requiredTypeNotInPrinter`)})]})]})}function IU({filamentReqs:e,availableFilaments:t,overrides:n,onChange:r,forceColorMatch:i,onForceColorMatchChange:a,plateLabel:o,showHint:s=!0}){let{t:c}=U(),l=AU(e?.filaments),u=(0,y.useMemo)(()=>{let e={};for(let n of t){let t=hp(n.type);e[t]||(e[t]=[]),e[t].push(n)}return e},[t]),d=e?.filaments;if(!d||d.length===0||t.length===0)return null;let f=(e,t)=>{if(t===``){let t={...n};delete t[e],r(t)}else{let[i,a]=t.split(`|`);r({...n,[e]:{type:i,color:a}})}};return(0,G.jsxs)(`div`,{className:`mb-4`,children:[(0,G.jsx)(`div`,{className:`flex items-center gap-2 text-sm text-bambu-gray mb-2`,children:(0,G.jsx)(`span`,{children:o?`${c(`printModal.filamentOverride`)} — ${o}`:c(`printModal.filamentOverride`)})}),s&&(0,G.jsx)(`p`,{className:`text-xs text-bambu-gray mb-2`,children:c(`printModal.filamentOverrideHint`)}),(0,G.jsx)(`div`,{className:`bg-bambu-dark rounded-lg p-3 space-y-2`,children:d.map((e,t)=>{let r=n[e.slot_id],o=!!r,s=u[hp(e.type)]||[],d=e.nozzle_id==null?s:s.filter(t=>t.extruder_id==null||t.extruder_id===e.nozzle_id),{resolvedName:p,colorLabel:m}=l[t]??{resolvedName:e.type,colorLabel:bf(e.color)};return(0,G.jsxs)(`div`,{className:`space-y-1`,children:[(0,G.jsxs)(`div`,{className:`grid items-center gap-2 text-xs`,style:{gridTemplateColumns:`16px minmax(70px, 1fr) auto 2fr 20px`},children:[(0,G.jsx)(`span`,{title:`${c(`printModal.originalFilament`)}: ${p} - ${m}`,children:(0,G.jsx)(Es,{className:`w-3 h-3`,fill:e.color,stroke:e.color})}),(0,G.jsxs)(`span`,{className:`text-white truncate`,children:[p,` `,(0,G.jsxs)(`span`,{className:`text-bambu-gray`,children:[`(`,e.used_grams,`g)`]})]}),(0,G.jsx)(`span`,{className:`text-bambu-gray`,children:`→`}),(0,G.jsxs)(`select`,{value:o?`${r.type}|${r.color}`:``,onChange:t=>f(e.slot_id,t.target.value),disabled:d.length===0,className:`flex-1 px-2 py-1 rounded border text-xs bg-bambu-dark-secondary focus:outline-none focus:ring-1 focus:ring-bambu-green ${o?`border-blue-500/50 dark:border-blue-400/50 text-blue-700 dark:text-blue-400`:`border-bambu-gray/30 text-bambu-gray`}`,children:[(0,G.jsxs)(`option`,{value:``,className:`bg-bambu-dark text-bambu-gray`,children:[c(`printModal.originalFilament`),`: `,p,` (`,m,`)`]}),d.map((e,t)=>(0,G.jsxs)(`option`,{value:`${e.type}|${e.color}`,className:`bg-bambu-dark text-white`,children:[e.tray_sub_brands||e.type,` (`,bf(e.color,e.tray_sub_brands),`)`]},`${e.type}-${e.color}-${e.tray_sub_brands}-${t}`))]}),o?(0,G.jsx)(`button`,{type:`button`,onClick:()=>f(e.slot_id,``),className:`text-bambu-gray hover:text-white transition-colors`,title:c(`printModal.resetToOriginal`),children:(0,G.jsx)(Hl,{className:`w-3 h-3`})}):(0,G.jsx)(`span`,{className:`w-3`})]}),(0,G.jsxs)(`label`,{className:`inline-flex items-center gap-1.5 text-xs text-bambu-gray cursor-pointer select-none pl-5`,children:[(0,G.jsx)(`input`,{type:`checkbox`,checked:i?.[e.slot_id]??!1,onChange:t=>a?.(e.slot_id,t.target.checked),className:`accent-bambu-green w-3 h-3`}),(0,G.jsx)(Sl,{className:`w-3 h-3`}),c(`printModal.forceColorMatch`)]})]},e.slot_id)})})]})}function Eke({plates:e,isMultiPlate:t,selectedPlates:n,onToggle:r,onSelectAll:i,onDeselectAll:a,multiSelect:o,quantities:s,onQuantityChange:c}){let{t:l}=U();if(!t||e.length<=1)return null;let u=n.size===e.length,d=!!s&&!!c,f=d?e.reduce((e,t)=>n.has(t.index)?e+(s[t.index]??1):e,0):0;return(0,G.jsxs)(`div`,{className:`mb-4`,children:[(0,G.jsxs)(`div`,{className:`flex items-center gap-2 mb-2`,children:[(0,G.jsx)(Kc,{className:`w-4 h-4 text-bambu-gray`}),(0,G.jsxs)(`span`,{className:`text-sm text-bambu-gray`,children:[`Select Plate`,o?`s`:``,` to Print`]}),n.size===0&&(0,G.jsxs)(`span`,{className:`text-xs text-orange-700 dark:text-orange-400 flex items-center gap-1`,children:[(0,G.jsx)(Fu,{className:`w-3 h-3`}),`Selection required`]}),o&&i&&a&&(0,G.jsx)(`button`,{type:`button`,onClick:u?a:i,className:`ml-auto text-xs px-2 py-0.5 rounded-full border transition-colors ${u?`border-bambu-green bg-bambu-green/10 text-bambu-green`:`border-bambu-dark-tertiary text-bambu-gray hover:border-bambu-gray`}`,children:u?l(`queue.deselectAll`):l(`queue.selectAllPlates`,{count:e.length})})]}),(0,G.jsx)(`div`,{className:`grid grid-cols-2 gap-2`,children:e.map(e=>{let t=n.has(e.index);return(0,G.jsxs)(`div`,{className:`flex items-center gap-2 p-2 rounded-lg border transition-colors ${t?`border-bambu-green bg-bambu-green/10`:`border-bambu-dark-tertiary bg-bambu-dark hover:border-bambu-gray`}`,children:[(0,G.jsxs)(`button`,{type:`button`,onClick:()=>r(e.index),className:`flex items-center gap-2 text-left min-w-0 flex-1`,children:[o&&(t?(0,G.jsx)(gu,{className:`w-4 h-4 text-bambu-green flex-shrink-0`}):(0,G.jsx)(vu,{className:`w-4 h-4 text-bambu-gray flex-shrink-0`})),e.has_thumbnail&&e.thumbnail_url!=null?(0,G.jsx)(`img`,{src:fd(e.thumbnail_url),alt:`Plate ${e.index}`,className:`w-10 h-10 rounded object-cover bg-bambu-dark-tertiary`}):(0,G.jsx)(`div`,{className:`w-10 h-10 rounded bg-bambu-dark-tertiary flex items-center justify-center`,children:(0,G.jsx)(Kc,{className:`w-5 h-5 text-bambu-gray`})}),(0,G.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,G.jsx)(`p`,{className:`text-sm text-white font-medium truncate`,children:e.name||`Plate ${e.index}`}),(0,G.jsxs)(`p`,{className:`text-xs text-bambu-gray truncate`,children:[e.objects.length>0?e.objects.slice(0,3).join(`, `)+(e.objects.length>3?`...`:``):`${e.filaments.length} filament${e.filaments.length===1?``:`s`}`,e.print_time_seconds==null?``:` • ${np(e.print_time_seconds)}`]}),(()=>{let t=kU(e.bed_type);return t?(0,G.jsxs)(`p`,{className:`text-xs text-bambu-gray flex items-center gap-1 mt-0.5 truncate`,title:t.label,children:[(0,G.jsx)(`img`,{src:t.icon,alt:``,className:`w-3.5 h-3.5 object-contain flex-shrink-0`}),(0,G.jsx)(`span`,{className:`truncate`,children:t.label})]}):null})()]}),!o&&t&&(0,G.jsx)(us,{className:`w-4 h-4 text-bambu-green flex-shrink-0`})]}),d&&t&&(0,G.jsxs)(`div`,{className:`flex items-center gap-1 flex-shrink-0`,children:[(0,G.jsx)(`span`,{className:`text-xs text-bambu-gray`,"aria-hidden":`true`,children:`×`}),(0,G.jsx)(`input`,{type:`number`,min:1,max:999,value:s[e.index]??1,"aria-label":l(`queue.plateQuantityLabel`,{plate:e.name||l(`queue.plateNumber`,{index:e.index})}),onChange:t=>c(e.index,Math.max(1,Math.min(999,parseInt(t.target.value)||1))),className:`w-14 px-1.5 py-1 text-sm bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-center focus:outline-none focus:ring-1 focus:ring-bambu-green`})]})]},e.index)})}),d&&f>n.size&&(0,G.jsx)(`p`,{className:`text-xs text-bambu-gray mt-2`,children:l(`queue.plateQuantityTotal`,{count:f})})]})}var Dke=new Set([`IDLE`,`FINISH`,`FAILED`]);function Oke({printerResult:e,filamentReqs:t,onUpdateConfig:n}){let r=oo(),[i,a]=(0,y.useState)(!1),o=(t,r)=>{if(t<=0)return;let i={...e.config.manualMappings};r===``?delete i[t]:i[t]=parseInt(r,10),n({useDefault:!1,manualMappings:i,autoConfigured:!1})},s=async()=>{a(!0);try{await Z.refreshPrinterStatus(e.printerId),await new Promise(e=>setTimeout(e,500)),await r.refetchQueries({queryKey:[`printer-status`,e.printerId]})}finally{a(!1)}},c=t.map(t=>{let n=t.slot_id||0,i=e.config.manualMappings[n],a,o=!1;if(i!==void 0)a=e.loadedFilaments.find(e=>e.globalTrayId===i),o=!0;else{let n=new Set(Object.values(e.config.manualMappings)),i=r.getQueryData([`settings`]);a=Fp(t,e.loadedFilaments,n,Pp(i?.prefer_lowest_filament,e.status?.ams_filament_backup),e.inventoryByTrayId)}let s=`mismatch`;if(a){let e=gp(a.type,t.type),n=cp(a.color)===cp(t.color)||_p(a.color,t.color);e&&n?s=`match`:e&&(s=`type_only`)}return{req:t,loaded:a,status:s,isManual:o}});return(0,G.jsxs)(`div`,{className:`mt-2 bg-bambu-dark rounded-lg p-3 space-y-2`,children:[(0,G.jsxs)(`div`,{className:`flex items-center justify-between mb-2`,children:[(0,G.jsx)(`span`,{className:`text-xs text-bambu-gray`,children:`Custom slot mapping`}),(0,G.jsxs)(`button`,{type:`button`,onClick:s,className:`flex items-center gap-1 px-2 py-0.5 text-xs rounded border border-bambu-gray/30 hover:border-bambu-gray hover:bg-bambu-dark-tertiary transition-colors text-bambu-gray hover:text-white`,disabled:i,children:[(0,G.jsx)(Bl,{className:`w-3 h-3 ${i?`animate-spin`:``}`}),(0,G.jsx)(`span`,{children:`Re-read`})]})]}),c.map(({req:t,loaded:n,status:r,isManual:i},a)=>(0,G.jsxs)(`div`,{className:`grid items-center gap-2 text-xs`,style:{gridTemplateColumns:`16px minmax(70px, 1fr) auto 2fr 16px`},children:[(0,G.jsx)(`span`,{title:`Required: ${t.type} - ${bf(t.color)}`,children:(0,G.jsx)(Es,{className:`w-3 h-3`,fill:t.color,stroke:t.color})}),(0,G.jsxs)(`span`,{className:`text-white flex items-center gap-1 min-w-0`,children:[(0,G.jsx)(`span`,{className:`truncate min-w-0`,title:t.type,children:t.type}),(0,G.jsxs)(`span`,{className:`text-bambu-gray shrink-0 whitespace-nowrap`,children:[`(`,t.used_grams,`g)`]})]}),(0,G.jsx)(`span`,{className:`text-bambu-gray`,children:`→`}),(0,G.jsxs)(`select`,{value:n?.globalTrayId??``,onChange:e=>o(t.slot_id||0,e.target.value),className:`flex-1 px-2 py-1 rounded border text-xs bg-bambu-dark-secondary focus:outline-none focus:ring-1 focus:ring-bambu-green ${r===`match`?`border-bambu-green/50 text-bambu-green`:r===`type_only`?`border-yellow-500 dark:border-yellow-400/50 text-yellow-700 dark:text-yellow-400`:`border-orange-500 dark:border-orange-400/50 text-orange-700 dark:text-orange-400`} ${i?`ring-1 ring-blue-400/50`:``}`,title:i?`Manually selected`:`Auto-matched`,children:[(0,G.jsx)(`option`,{value:``,className:`bg-bambu-dark text-bambu-gray`,children:`-- Select slot --`}),Ip(e.loadedFilaments,t.nozzle_id).map(e=>(0,G.jsxs)(`option`,{value:e.globalTrayId,className:`bg-bambu-dark text-white`,children:[e.label,`: `,e.traySubBrands||e.type,` (`,e.colorName,`)`]},e.globalTrayId))]}),r===`match`?(0,G.jsx)(us,{className:`w-3 h-3 text-bambu-green`}):r===`type_only`?(0,G.jsx)(`span`,{title:`Same type, different color`,children:(0,G.jsx)(Fu,{className:`w-3 h-3 text-yellow-600 dark:text-yellow-400`})}):(0,G.jsx)(`span`,{title:`Filament type not loaded`,children:(0,G.jsx)(Fu,{className:`w-3 h-3 text-orange-600 dark:text-orange-400`})})]},a))]})}function kke({printers:e,selectedPrinterIds:t,onMultiSelect:n,isLoading:r=!1,allowMultiple:i=!1,showInactive:a=!1,disableBusy:o=!1,printerMappingResults:s,filamentReqs:c,onAutoConfigurePrinter:l,onUpdatePrinterConfig:u,assignmentMode:d=`printer`,onAssignmentModeChange:f,targetModel:p,onTargetModelChange:m,targetLocation:h,onTargetLocationChange:g,slicedForModel:_}){let[v,b]=(0,y.useState)(!1),x=a?e:e.filter(e=>e.is_active),S=xo({queries:x.map(e=>({queryKey:[`printerStatus`,e.id],queryFn:()=>Z.getPrinterStatus(e.id),staleTime:5e3}))}),C=(0,y.useMemo)(()=>{let e=new Map;return x.forEach((t,n)=>{let r=S[n];r?.data&&e.set(t.id,r.data)}),e},[x,S]),w=e=>{let t=C.get(e);return t?t.connected?!Dke.has(t.state??``):!0:!1},T=e=>{let t=C.get(e);if(!t)return null;if(!t.connected)return`Offline`;let n=t.state;return n?n===`RUNNING`?t.stg_cur_name||`Printing`:n===`PREPARE`?`Preparing`:n===`PAUSE`?`Paused`:n===`IDLE`?`Idle`:n===`FINISH`?`Finished`:n===`FAILED`?`Failed`:n:null},E=(0,y.useMemo)(()=>{if(d!==`printer`||!_||v)return x;let e=x.filter(e=>e.model===_);return e.length>0?e:x},[x,d,_,v]),D=x.length-E.length,O=(0,y.useMemo)(()=>{let e=x.map(e=>e.model).filter(e=>!!e);return[...new Set(e)].sort()},[x]),k=(0,y.useMemo)(()=>{if(!p)return[];let e=x.filter(e=>e.model===p&&e.location).map(e=>e.location).filter(e=>!!e);return[...new Set(e)].sort()},[x,p]),A=f&&m&&O.length>0,j=i&&t.length>1&&s&&c?.filaments&&c.filaments.length>0&&l&&u;if(r)return(0,G.jsx)(`div`,{className:`flex justify-center py-8`,children:(0,G.jsx)(Y,{className:`w-6 h-6 text-bambu-green animate-spin`})});if(E.length===0)return(0,G.jsxs)(`div`,{className:`flex items-center gap-2 text-red-700 dark:text-red-400 text-sm mb-4`,children:[(0,G.jsx)(_s,{className:`w-4 h-4`}),`No `,a?``:`active `,`printers available`]});let M=e=>{o&&w(e)||(i?t.includes(e)?n(t.filter(t=>t!==e)):n([...t,e]):n([e]))},N=()=>{n((o?E.filter(e=>!w(e.id)):E).map(e=>e.id))},P=()=>{n([])},F=(e,t,n)=>{n.stopPropagation(),!(!l||!u)&&(t?l(e):u(e,{useDefault:!0,manualMappings:{},autoConfigured:!1}))},I=e=>t.includes(e),L=t.length,R=e=>s?.find(t=>t.printerId===e);return(0,G.jsxs)(`div`,{className:`space-y-2 mb-6`,children:[A&&(0,G.jsxs)(`div`,{className:`flex gap-2 mb-4`,children:[(0,G.jsxs)(`button`,{type:`button`,onClick:()=>{f(`printer`),m(null)},className:`flex-1 flex items-center justify-center gap-2 px-3 py-2 rounded-lg border transition-colors ${d===`printer`?`border-bambu-green bg-bambu-green/10 text-white`:`border-bambu-dark-tertiary bg-bambu-dark text-bambu-gray hover:border-bambu-gray`}`,children:[(0,G.jsx)(Il,{className:`w-4 h-4`}),(0,G.jsx)(`span`,{className:`text-sm`,children:`Specific Printer`})]}),(0,G.jsxs)(`button`,{type:`button`,onClick:()=>{f(`model`),n([]),m(_&&O.includes(_)?_:null)},className:`flex-1 flex items-center justify-center gap-2 px-3 py-2 rounded-lg border transition-colors ${d===`model`?`border-bambu-green bg-bambu-green/10 text-white`:`border-bambu-dark-tertiary bg-bambu-dark text-bambu-gray hover:border-bambu-gray`}`,children:[(0,G.jsx)(Vu,{className:`w-4 h-4`}),(0,G.jsxs)(`span`,{className:`text-sm`,children:[`Any `,(d===`model`?p:null)||_||`Model`]})]})]}),d===`model`&&A&&(0,G.jsxs)(`div`,{className:`space-y-3 mb-4`,children:[(0,G.jsxs)(`div`,{children:[(0,G.jsxs)(`label`,{className:`block text-xs text-bambu-gray mb-1`,children:[`Target Model`,_&&(0,G.jsxs)(`span`,{className:`ml-2 text-bambu-gray/70`,children:[`(sliced for `,_,`)`]})]}),(0,G.jsxs)(`select`,{value:p||``,onChange:e=>{m(e.target.value||null),g&&g(null)},className:`w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none text-sm`,children:[(0,G.jsx)(`option`,{value:``,children:`Select a model...`}),O.map(e=>{let t=hm(_,e);return(0,G.jsxs)(`option`,{value:e,disabled:!t,children:[e,t?``:` — incompatible with ${_} G-code`]},e)})]})]}),_&&p&&p!==_&&(hm(_,p)?(0,G.jsxs)(`div`,{className:`p-3 bg-yellow-50 dark:bg-yellow-500/10 border border-yellow-300 dark:border-yellow-500/30 rounded-lg flex items-center gap-2`,children:[(0,G.jsx)(Fu,{className:`w-4 h-4 text-yellow-600 dark:text-yellow-400 flex-shrink-0`}),(0,G.jsxs)(`span`,{className:`text-sm text-yellow-700 dark:text-yellow-400`,children:[`File was sliced for `,_,`, but will be dispatched to a `,p,` printer`]})]}):(0,G.jsxs)(`div`,{className:`p-3 bg-red-50 dark:bg-red-500/10 border border-red-300 dark:border-red-500/30 rounded-lg flex items-center gap-2`,children:[(0,G.jsx)(_s,{className:`w-4 h-4 text-red-600 dark:text-red-400 flex-shrink-0`}),(0,G.jsxs)(`span`,{className:`text-sm text-red-700 dark:text-red-400`,children:[`File was sliced for `,_,` and cannot be dispatched to `,p,` printers — select a compatible model`]})]})),p&&k.length>0&&g&&(0,G.jsxs)(`div`,{children:[(0,G.jsx)(`label`,{className:`block text-xs text-bambu-gray mb-1`,children:`Location Filter (optional)`}),(0,G.jsxs)(`select`,{value:h||``,onChange:e=>g(e.target.value||null),className:`w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none text-sm`,children:[(0,G.jsx)(`option`,{value:``,children:`Any location`}),k.map(e=>(0,G.jsx)(`option`,{value:e,children:e},e))]})]}),p&&(0,G.jsxs)(`p`,{className:`text-xs text-bambu-gray`,children:[`Scheduler will assign to first available idle `,p,` printer`,h?` in ${h}`:``]})]}),d===`printer`&&i&&E.length>1&&(0,G.jsxs)(`div`,{className:`flex items-center justify-between text-xs text-bambu-gray mb-2`,children:[(0,G.jsx)(`span`,{children:L===0?`Select printers`:`${L} printer${L===1?``:`s`} selected`}),(0,G.jsxs)(`div`,{className:`flex gap-2`,children:[L0&&(0,G.jsx)(`button`,{type:`button`,onClick:P,className:`text-bambu-gray hover:text-white transition-colors`,children:`Clear`})]})]}),d===`printer`&&E.map(e=>{let t=I(e.id),n=R(e.id),r=n&&!n.config.useDefault,a=w(e.id),s=o&&a,d=T(e.id);return(0,G.jsxs)(`div`,{children:[(0,G.jsxs)(`button`,{type:`button`,onClick:()=>M(e.id),disabled:s,className:`w-full flex items-center gap-3 p-3 rounded-lg border transition-colors ${s?`border-bambu-dark-tertiary bg-bambu-dark opacity-50 cursor-not-allowed`:t?`border-bambu-green bg-bambu-green/10`:`border-bambu-dark-tertiary bg-bambu-dark hover:border-bambu-gray`} ${e.is_active?``:`opacity-60`}`,children:[(0,G.jsx)(`div`,{className:`p-2 rounded-lg ${s?`bg-bambu-dark-tertiary`:t?`bg-bambu-green/20`:`bg-bambu-dark-tertiary`}`,children:(0,G.jsx)(Il,{className:`w-5 h-5 ${s?`text-bambu-gray/50`:t?`text-bambu-green`:`text-bambu-gray`}`})}),(0,G.jsxs)(`div`,{className:`text-left flex-1`,children:[(0,G.jsxs)(`p`,{className:`font-medium ${s?`text-bambu-gray`:`text-white`}`,children:[e.name,!e.is_active&&(0,G.jsx)(`span`,{className:`text-bambu-gray text-xs ml-2`,children:`(inactive)`})]}),(0,G.jsxs)(`p`,{className:`text-xs text-bambu-gray`,children:[e.model||`Unknown model`,` • `,e.ip_address]})]}),d&&(0,G.jsx)(`span`,{className:`text-xs px-2 py-0.5 rounded-full ${a?`bg-yellow-100 dark:bg-yellow-500/20 text-yellow-700 dark:text-yellow-400`:`bg-bambu-green/20 text-bambu-green`}`,children:d}),i&&(0,G.jsx)(`div`,{className:`w-5 h-5 rounded border-2 flex items-center justify-center transition-colors ${s?`border-bambu-gray/30`:t?`bg-bambu-green border-bambu-green`:`border-bambu-gray/50`}`,children:t&&(0,G.jsx)(us,{className:`w-3 h-3 text-white`})})]}),t&&j&&n&&(0,G.jsxs)(`div`,{className:`ml-4 mt-2 mb-3`,children:[(0,G.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,G.jsxs)(`label`,{className:`flex items-center gap-2 cursor-pointer`,onClick:e=>e.stopPropagation(),children:[(0,G.jsx)(`input`,{type:`checkbox`,checked:r,onChange:t=>F(e.id,t.target.checked,t),className:`w-3.5 h-3.5 rounded border-bambu-gray/30 bg-bambu-dark-secondary text-bambu-green focus:ring-bambu-green focus:ring-offset-0`}),(0,G.jsx)(`span`,{className:`text-xs text-bambu-gray`,children:`Custom mapping`})]}),(0,G.jsxs)(`span`,{className:`text-xs ml-2 ${n.matchStatus===`full`?`text-bambu-green`:n.matchStatus===`partial`?`text-yellow-700 dark:text-yellow-400`:`text-orange-700 dark:text-orange-400`}`,children:[`(`,n.exactMatches,`/`,n.totalSlots,` matched)`]}),n.isLoading&&(0,G.jsx)(Bl,{className:`w-3 h-3 text-bambu-gray animate-spin`}),r&&(0,G.jsxs)(`button`,{type:`button`,onClick:t=>{t.stopPropagation(),l(e.id)},className:`ml-auto flex items-center gap-1 px-2 py-0.5 text-xs rounded border border-bambu-gray/30 hover:border-bambu-gray hover:bg-bambu-dark-tertiary transition-colors text-bambu-gray hover:text-white`,children:[(0,G.jsx)(qu,{className:`w-3 h-3`}),`Auto`]})]}),r&&(0,G.jsx)(Oke,{printerResult:n,filamentReqs:c.filaments,onUpdateConfig:t=>u(e.id,t)})]})]},e.id)}),d===`printer`&&D>0&&!v&&(0,G.jsxs)(`button`,{type:`button`,onClick:()=>b(!0),className:`text-xs text-bambu-gray hover:text-white transition-colors mt-2 flex items-center gap-1`,children:[(0,G.jsx)(Fu,{className:`w-3 h-3 text-yellow-600 dark:text-yellow-400`}),D,` other printer`,D>1?`s`:``,` hidden (different model) —`,(0,G.jsx)(`span`,{className:`underline`,children:`show all`})]}),d===`printer`&&v&&_&&(0,G.jsx)(`button`,{type:`button`,onClick:()=>b(!1),className:`text-xs text-bambu-gray hover:text-white transition-colors mt-2`,children:(0,G.jsxs)(`span`,{className:`underline`,children:[`Show only `,_,` printers`]})}),d===`printer`&&L===0&&(0,G.jsxs)(`p`,{className:`text-xs text-orange-700 dark:text-orange-400 mt-1 flex items-center gap-1`,children:[(0,G.jsx)(_s,{className:`w-3 h-3`}),`Select at least one printer`]}),d===`model`&&!p&&(0,G.jsxs)(`p`,{className:`text-xs text-orange-700 dark:text-orange-400 mt-1 flex items-center gap-1`,children:[(0,G.jsx)(_s,{className:`w-3 h-3`}),`Select a target printer model`]})]})}var LU=[`off`,`auto`,`on`],RU={off:`bg-red-500 text-white`,auto:`bg-blue-500 text-white`,on:`bg-bambu-green text-white`},Ake=[`off`,`on`];function jke({options:e,onChange:t,defaultExpanded:n=!1,showDualNozzleOptions:r=!1}){let{t:i}=U(),[a,o]=(0,y.useState)(n),s=[{key:`bed_levelling`,label:i(`settings.defaultBedLevelling`),desc:i(`settings.defaultBedLevellingDesc`),tristate:!0},{key:`flow_cali`,label:i(`settings.defaultFlowCali`),desc:i(`settings.defaultFlowCaliDesc`),tristate:!0},{key:`vibration_cali`,label:i(`settings.defaultVibrationCali`),desc:i(`settings.defaultVibrationCaliDesc`)},{key:`layer_inspect`,label:i(`settings.defaultLayerInspect`),desc:i(`settings.defaultLayerInspectDesc`)},{key:`timelapse`,label:i(`settings.defaultTimelapse`),desc:i(`settings.defaultTimelapseDesc`)},{key:`nozzle_offset_cali`,label:i(`settings.defaultNozzleOffsetCali`),desc:i(`settings.defaultNozzleOffsetCaliDesc`),dualNozzleOnly:!0,tristate:!0}].filter(e=>!e.dualNozzleOnly||r),c=(n,r)=>{t({...e,[n]:r})},l=(n,r)=>{t({...e,[n]:r})},u=n=>{t({...e,preheat_override:n,...n===`off`?{preheat_chamber_target_override:null}:{}})},d=n=>{if(n===``){t({...e,preheat_chamber_target_override:null});return}let r=parseInt(n,10);Number.isNaN(r)||t({...e,preheat_chamber_target_override:Math.max(0,Math.min(65,r))})};return(0,G.jsxs)(`div`,{className:`mb-4`,children:[(0,G.jsxs)(`button`,{type:`button`,onClick:()=>o(!a),className:`flex items-center gap-2 text-sm text-bambu-gray hover:text-white transition-colors w-full`,children:[(0,G.jsx)(tu,{className:`w-4 h-4`}),(0,G.jsx)(`span`,{children:i(`queue.bulkEdit.printOptions`)}),a?(0,G.jsx)(ms,{className:`w-4 h-4 ml-auto`}):(0,G.jsx)(ds,{className:`w-4 h-4 ml-auto`})]}),a&&(0,G.jsxs)(`div`,{className:`mt-2 bg-bambu-dark rounded-lg p-3 space-y-2`,children:[s.map(({key:t,label:n,desc:r,tristate:a})=>a?(0,G.jsxs)(`div`,{className:`flex items-center justify-between gap-3`,children:[(0,G.jsxs)(`div`,{children:[(0,G.jsx)(`span`,{className:`text-sm text-white`,children:n}),(0,G.jsx)(`p`,{className:`text-xs text-bambu-gray`,children:r})]}),(0,G.jsx)(`div`,{className:`flex gap-1 shrink-0`,children:LU.map(n=>(0,G.jsx)(`button`,{type:`button`,onClick:()=>l(t,n),className:`px-2.5 py-1 text-xs rounded transition-colors ${e[t]===n?RU[n]:`bg-bambu-dark-tertiary text-bambu-gray hover:text-white`}`,children:i(`settings.calibrationMode_${n}`)},n))})]},t):(0,G.jsxs)(`div`,{className:`flex items-center justify-between gap-3`,children:[(0,G.jsxs)(`div`,{children:[(0,G.jsx)(`span`,{className:`text-sm text-white`,children:n}),(0,G.jsx)(`p`,{className:`text-xs text-bambu-gray`,children:r})]}),(0,G.jsx)(`div`,{className:`flex gap-1 shrink-0`,children:Ake.map(n=>(0,G.jsx)(`button`,{type:`button`,onClick:()=>c(t,n===`on`),className:`px-2.5 py-1 text-xs rounded transition-colors ${(e[t]?`on`:`off`)===n?RU[n]:`bg-bambu-dark-tertiary text-bambu-gray hover:text-white`}`,children:i(`settings.calibrationMode_${n}`)},n))})]},t)),(0,G.jsxs)(`div`,{className:`pt-2 mt-1 border-t border-bambu-dark-tertiary/60`,children:[(0,G.jsxs)(`div`,{className:`flex items-center gap-2 mb-1.5`,children:[(0,G.jsx)(pc,{className:`w-3.5 h-3.5 text-amber-600 dark:text-amber-400`}),(0,G.jsx)(`span`,{className:`text-sm text-white`,children:i(`settings.preheatTitle`,`Preheat & Heat Soak`)})]}),(0,G.jsx)(`p`,{className:`text-xs text-bambu-gray mb-2`,children:i(`settings.preheatPerItemDesc`,`Heat the bed and chamber before this print starts. Defaults to the global Settings → Workflow toggle.`)}),(0,G.jsx)(`div`,{className:`flex gap-1.5 mb-2`,children:[`inherit`,`on`,`off`].map(t=>(0,G.jsx)(`button`,{type:`button`,onClick:()=>u(t),className:`flex-1 px-2 py-1.5 text-xs rounded transition-colors ${e.preheat_override===t?`bg-bambu-green text-white`:`bg-bambu-dark-tertiary text-bambu-gray hover:text-white`}`,children:i(`settings.preheatOverride_${t}`,t===`inherit`?`Inherit`:t===`on`?`On`:`Off`)},t))}),e.preheat_override!==`off`&&(0,G.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,G.jsx)(`label`,{className:`text-xs text-bambu-gray flex-1`,children:i(`settings.preheatTargetOverride`,`Chamber target override (°C, blank = filament default)`)}),(0,G.jsx)(`input`,{type:`number`,min:0,max:65,step:1,value:e.preheat_chamber_target_override??``,onChange:e=>d(e.target.value),placeholder:`—`,className:`w-16 px-2 py-1 bg-bambu-dark-tertiary border border-bambu-dark-tertiary rounded text-white text-xs text-right focus:outline-none focus:border-bambu-green`})]})]})]})]})}function Mke({options:e,onChange:t,dateFormat:n=`system`,timeFormat:r=`system`,canControlPrinter:i=!0,showStagger:a=!1,printerCount:o=0,hasGcodeSnippets:s=!1}){let{t:c}=U(),[l,u]=(0,y.useState)(``),[d,f]=(0,y.useState)(``),[p,m]=(0,y.useState)(!0),[h,g]=(0,y.useState)(!0),_=(0,y.useRef)(null),v=(0,y.useRef)(!1);(0,y.useEffect)(()=>{if(e.scheduleType!==`scheduled`){v.current=!1;return}if(!v.current){v.current=!0;let i;e.scheduledTime?(i=new Date(e.scheduledTime),isNaN(i.getTime())&&(i=new Date,i.setHours(i.getHours()+1,0,0,0))):(i=new Date,i.setHours(i.getHours()+1,0,0,0),t({...e,scheduledTime:Jf(i)})),u(Hf(i,n)),f(Uf(i,r)),m(!0),g(!0)}},[e.scheduleType,e.scheduledTime,n,r,t,e]);let b=n=>{t({...e,scheduleType:n,requireManualStart:n===`queue`?e.requireManualStart:!1})},x=(r,i)=>{let a=Kf(r,n),o=qf(i);m(!!a),g(!!o),a&&o&&(a.setHours(o.hours,o.minutes,0,0),a>new Date&&t({...e,scheduledTime:Jf(a)}))},S=e=>{u(e),x(e,d)},C=e=>{f(e),x(l,e)};return(0,G.jsxs)(`div`,{className:`space-y-4`,children:[(0,G.jsxs)(`div`,{children:[(0,G.jsx)(`label`,{className:`block text-sm text-bambu-gray mb-2`,children:c(`printModal.whenToPrint`)}),(0,G.jsxs)(`div`,{className:`flex gap-2`,children:[(0,G.jsxs)(`button`,{type:`button`,className:`flex-1 px-2 py-2 rounded-lg border text-sm flex items-center justify-center gap-1.5 transition-colors ${e.scheduleType===`asap`?`bg-bambu-green border-bambu-green text-white`:`bg-bambu-dark border-bambu-dark-tertiary text-bambu-gray hover:text-white`}`,onClick:()=>b(`asap`),children:[(0,G.jsx)(ks,{className:`w-4 h-4`}),c(`printModal.asap`)]}),(0,G.jsxs)(`button`,{type:`button`,className:`flex-1 px-2 py-2 rounded-lg border text-sm flex items-center justify-center gap-1.5 transition-colors ${e.scheduleType===`queue`?`bg-bambu-green border-bambu-green text-white`:`bg-bambu-dark border-bambu-dark-tertiary text-bambu-gray hover:text-white`}`,onClick:()=>b(`queue`),children:[(0,G.jsx)(Xc,{className:`w-4 h-4`}),c(`printModal.queue`)]}),(0,G.jsxs)(`button`,{type:`button`,className:`flex-1 px-2 py-2 rounded-lg border text-sm flex items-center justify-center gap-1.5 transition-colors ${e.scheduleType===`scheduled`?`bg-bambu-green border-bambu-green text-white`:`bg-bambu-dark border-bambu-dark-tertiary text-bambu-gray hover:text-white`}`,onClick:()=>b(`scheduled`),children:[(0,G.jsx)(rs,{className:`w-4 h-4`}),c(`printModal.schedule`)]})]})]}),e.scheduleType===`scheduled`&&(0,G.jsxs)(`div`,{children:[(0,G.jsx)(`label`,{className:`block text-sm text-bambu-gray mb-1`,children:c(`printModal.dateTime`)}),(0,G.jsxs)(`div`,{className:`flex gap-2`,children:[(0,G.jsxs)(`div`,{className:`flex-1 relative`,children:[(0,G.jsx)(`input`,{type:`text`,className:`w-full px-3 py-2 pr-10 bg-bambu-dark border rounded-lg text-white focus:outline-none ${p?`border-bambu-dark-tertiary focus:border-bambu-green`:`border-red-500`}`,value:l,onChange:e=>S(e.target.value),placeholder:Bf(n)}),(0,G.jsx)(`button`,{type:`button`,onClick:()=>{_.current?.showPicker()},className:`absolute right-2 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white`,title:c(`printModal.openCalendar`),children:(0,G.jsx)(rs,{className:`w-4 h-4`})}),(0,G.jsx)(`input`,{ref:_,type:`datetime-local`,className:`absolute top-0 left-0 w-0 h-0 opacity-0 pointer-events-none`,value:e.scheduledTime,onChange:i=>{let a=i.target.value;if(a){let i=new Date(a);isNaN(i.getTime())||(u(Hf(i,n)),f(Uf(i,r)),m(!0),g(!0),t({...e,scheduledTime:a}))}},tabIndex:-1})]}),(0,G.jsx)(`div`,{className:`w-32`,children:(0,G.jsx)(`input`,{type:`text`,className:`w-full px-3 py-2 bg-bambu-dark border rounded-lg text-white focus:outline-none ${h?`border-bambu-dark-tertiary focus:border-bambu-green`:`border-red-500`}`,value:d,onChange:e=>C(e.target.value),placeholder:Vf(r)})})]}),(!p||!h)&&(0,G.jsx)(`p`,{className:`mt-1 text-xs text-red-700 dark:text-red-400`,children:c(`printModal.invalidDateTime`)})]}),e.scheduleType===`queue`&&(0,G.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,G.jsx)(`input`,{type:`checkbox`,id:`requireManualStart`,checked:e.requireManualStart,onChange:n=>t({...e,requireManualStart:n.target.checked}),className:`rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green`}),(0,G.jsxs)(`label`,{htmlFor:`requireManualStart`,className:`text-sm flex items-center gap-1 text-bambu-gray`,children:[(0,G.jsx)(jc,{className:`w-3.5 h-3.5`}),c(`printModal.requireManualStart`)]})]}),(0,G.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,G.jsx)(`input`,{type:`checkbox`,id:`requirePrevious`,checked:e.requirePreviousSuccess,onChange:n=>t({...e,requirePreviousSuccess:n.target.checked}),className:`rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green`}),(0,G.jsx)(`label`,{htmlFor:`requirePrevious`,className:`text-sm text-bambu-gray`,children:c(`printModal.requirePreviousSuccess`)})]}),(0,G.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,G.jsx)(`input`,{type:`checkbox`,id:`autoOffAfter`,checked:e.autoOffAfter,onChange:n=>t({...e,autoOffAfter:n.target.checked}),disabled:!i,className:`rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green disabled:opacity-50`}),(0,G.jsxs)(`label`,{htmlFor:`autoOffAfter`,className:`text-sm flex items-center gap-1 ${i?`text-bambu-gray`:`text-bambu-gray/50`}`,children:[(0,G.jsx)(Fl,{className:`w-3.5 h-3.5`}),c(`printModal.autoOffAfter`)]})]}),s&&(0,G.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,G.jsx)(`input`,{type:`checkbox`,id:`gcodeInjection`,checked:e.gcodeInjection,onChange:n=>t({...e,gcodeInjection:n.target.checked}),className:`rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green`}),(0,G.jsxs)(`label`,{htmlFor:`gcodeInjection`,className:`text-sm flex items-center gap-1 text-bambu-gray`,children:[(0,G.jsx)(Ns,{className:`w-3.5 h-3.5`}),c(`printModal.gcodeInjection`,`Inject auto-print G-code`)]})]}),a&&e.scheduleType!==`queue`&&(0,G.jsxs)(`div`,{className:`space-y-3`,children:[(0,G.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,G.jsx)(`input`,{type:`checkbox`,id:`staggerEnabled`,checked:e.staggerEnabled,onChange:n=>t({...e,staggerEnabled:n.target.checked}),className:`rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green`}),(0,G.jsxs)(`label`,{htmlFor:`staggerEnabled`,className:`text-sm flex items-center gap-1 text-bambu-gray`,children:[(0,G.jsx)(Kc,{className:`w-3.5 h-3.5`}),c(`printModal.staggerPrinterStarts`,`Stagger printer starts`)]})]}),e.staggerEnabled&&(0,G.jsxs)(`div`,{className:`ml-6 space-y-3`,children:[(0,G.jsxs)(`div`,{className:`flex gap-3`,children:[(0,G.jsxs)(`div`,{className:`flex-1`,children:[(0,G.jsx)(`label`,{className:`block text-xs text-bambu-gray mb-1`,children:c(`printModal.staggerGroupSize`,`Group size`)}),(0,G.jsx)(`input`,{type:`number`,min:1,max:o,value:e.staggerGroupSize,onChange:n=>t({...e,staggerGroupSize:Math.max(1,parseInt(n.target.value)||1)}),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`})]}),(0,G.jsxs)(`div`,{className:`flex-1`,children:[(0,G.jsx)(`label`,{className:`block text-xs text-bambu-gray mb-1`,children:c(`printModal.staggerInterval`,`Interval (min)`)}),(0,G.jsx)(`input`,{type:`number`,min:1,max:60,value:e.staggerIntervalMinutes,onChange:n=>t({...e,staggerIntervalMinutes:Math.max(1,parseInt(n.target.value)||1)}),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`})]})]}),o>0&&(()=>{let t=Math.ceil(o/e.staggerGroupSize),n=o%e.staggerGroupSize,r=(t-1)*e.staggerIntervalMinutes;return(0,G.jsxs)(`p`,{className:`text-xs text-bambu-gray`,children:[c(`printModal.staggerPreview`,`{{printers}} printers → {{groups}} groups of {{size}}, starting every {{interval}} min`,{printers:o,groups:t,size:e.staggerGroupSize,interval:e.staggerIntervalMinutes}),n!==0&&e.staggerGroupSize1?` (${c(`printModal.staggerTotal`,`total: {{minutes}} min`,{minutes:r})})`:``]})})()]})]}),(0,G.jsx)(`p`,{className:`text-xs text-bambu-gray`,children:e.scheduleType===`asap`?c(`printModal.helpAsap`):e.scheduleType===`scheduled`?c(`printModal.helpSchedule`):c(`printModal.helpQueue`)})]})}function zU({candidates:e,onReorder:t,plateByFile:n,onPlateChange:r,readOnly:i=!1,readOnlyNote:a}){let{t:o}=U(),s=xo({queries:i?[]:e.map(e=>({queryKey:[`library-file-plates`,e.id],queryFn:()=>Z.getLibraryFilePlates(e.id),staleTime:6e4}))}),c=(0,y.useMemo)(()=>{let t={};return e.forEach((e,n)=>{let r=s[n]?.data;r?.is_multi_plate&&r.plates.length>1&&(t[e.id]=r.plates.map(e=>({index:e.index,name:e.name})))}),t},[e,s]),l=(n,r)=>{if(r<0||r>=e.length)return;let i=[...e],[a]=i.splice(n,1);i.splice(r,0,a),t(i)};return(0,G.jsxs)(`div`,{className:`mb-4`,children:[(0,G.jsxs)(`div`,{className:`flex items-center gap-2 mb-2`,children:[(0,G.jsx)(Il,{className:`w-4 h-4 text-bambu-gray`}),(0,G.jsx)(`span`,{className:`text-sm text-bambu-gray`,children:o(`printModal.variants.title`)})]}),(0,G.jsx)(`p`,{className:`text-xs text-bambu-gray mb-2`,children:i?a??o(`printModal.variants.help`):o(`printModal.variants.help`)}),(0,G.jsx)(`div`,{className:`space-y-2`,children:e.map((t,a)=>{let s=c[t.id],u=t.sliced_for_model;return(0,G.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2 rounded border border-bambu-dark-tertiary p-2`,children:[(0,G.jsxs)(`span`,{className:`text-xs font-mono text-bambu-gray w-5 shrink-0`,children:[a+1,`.`]}),(0,G.jsx)(`span`,{className:`px-2 py-0.5 rounded-full bg-bambu-green/10 text-bambu-green text-xs shrink-0`,children:u||o(`printModal.variants.unknownModel`)}),(0,G.jsx)(`span`,{className:`text-sm text-white truncate min-w-0 flex-1`,title:t.filename,children:t.filename}),s&&(0,G.jsxs)(`label`,{className:`flex items-center gap-1 text-xs text-bambu-gray shrink-0`,children:[(0,G.jsx)(Kc,{className:`w-3 h-3`}),(0,G.jsx)(`select`,{className:`bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-1 py-0.5 text-xs text-white`,value:n[t.id]??s[0].index,onChange:e=>r(t.id,Number(e.target.value)),"aria-label":o(`printModal.variants.plateFor`,{filename:t.filename}),children:s.map(e=>(0,G.jsx)(`option`,{value:e.index,children:e.name||o(`printModal.plateN`,{n:e.index})},e.index))})]}),!i&&(0,G.jsxs)(`div`,{className:`flex items-center gap-1 shrink-0`,children:[(0,G.jsx)(`button`,{type:`button`,onClick:()=>l(a,a-1),disabled:a===0,className:`p-1 rounded text-bambu-gray hover:text-white disabled:opacity-30`,"aria-label":o(`printModal.variants.moveUp`),children:(0,G.jsx)(Bo,{className:`w-3.5 h-3.5`})}),(0,G.jsx)(`button`,{type:`button`,onClick:()=>l(a,a+1),disabled:a===e.length-1,className:`p-1 rounded text-bambu-gray hover:text-white disabled:opacity-30`,"aria-label":o(`printModal.variants.moveDown`),children:(0,G.jsx)(Po,{className:`w-3.5 h-3.5`})})]})]},t.id)})})]})}function Nke({costCenters:e,selectedCostCenterId:t,onChange:n}){let{t:r}=U();if(e.length===0)return null;let i=e.find(e=>e.id===t);return(0,G.jsxs)(`div`,{className:`space-y-1`,children:[(0,G.jsx)(`label`,{htmlFor:`printCostCenter`,className:`text-sm text-bambu-gray`,children:r(`printModal.costCenter`,`Cost center`)}),(0,G.jsx)(`select`,{id:`printCostCenter`,value:t??``,onChange:e=>n(e.target.value?Number(e.target.value):null),className:`w-full px-3 py-2 text-sm bg-bambu-dark border border-bambu-dark-tertiary rounded text-white focus:outline-none focus:ring-1 focus:ring-bambu-green`,children:e.map(e=>(0,G.jsxs)(`option`,{value:e.id,children:[e.name,e.is_private?` (${r(`printModal.personalDefault`,`Personal`)})`:``]},e.id))}),i?.budget_mode===`none`&&(0,G.jsx)(`p`,{className:`text-xs text-bambu-gray`,children:r(`printModal.unlimitedNoBudget`,`Unlimited – no budget limit is set.`)})]})}var BU={bed_levelling:`auto`,flow_cali:`auto`,vibration_cali:!0,layer_inspect:!1,timelapse:!1,nozzle_offset_cali:`auto`,preheat_override:`inherit`,preheat_chamber_target_override:null},VU={scheduleType:`asap`,scheduledTime:``,requireManualStart:!1,requirePreviousSuccess:!1,autoOffAfter:!1,gcodeInjection:!1,staggerEnabled:!1,staggerGroupSize:2,staggerIntervalMinutes:5};function HU({mode:e,archiveId:t,libraryFileId:n,archiveName:r,queueItem:i,initialSelectedPrinterIds:a,onClose:o,onSuccess:s,projectId:c,cleanupLibraryAfterDispatch:l,variantFiles:u}){let{t:d}=U(),f=oo(),{showToast:p}=Bd(),{hasPermission:m,user:h}=Dd(),g=!!n&&!t,_=e===`edit-queue-item`,v=e===`create`&&(u?.length??0)>1,b=e===`edit-queue-item`&&(i?.variants?.length??0)>1?i.variants.map(e=>({id:e.library_file_id,filename:e.filename,sliced_for_model:e.target_model})):[],x=b.length>0,[S,C]=(0,y.useState)(u??[]),[w,T]=(0,y.useState)({}),[E,D]=(0,y.useState)(()=>e===`edit-queue-item`&&i?.printer_id?[i.printer_id]:a?.length?a:[]),[O,k]=(0,y.useState)(()=>e===`edit-queue-item`&&i?.plate_id!=null?new Set([i.plate_id]):new Set),A=O.size===1?[...O][0]:null,[j,M]=(0,y.useState)(1),[N,P]=(0,y.useState)({}),[F,I]=(0,y.useState)(()=>e===`edit-queue-item`&&i?{bed_levelling:i.bed_levelling??BU.bed_levelling,flow_cali:i.flow_cali??BU.flow_cali,vibration_cali:i.vibration_cali??BU.vibration_cali,layer_inspect:i.layer_inspect??BU.layer_inspect,timelapse:i.timelapse??BU.timelapse,nozzle_offset_cali:i.nozzle_offset_cali??BU.nozzle_offset_cali,preheat_override:i.preheat_override??BU.preheat_override,preheat_chamber_target_override:i.preheat_chamber_target_override??BU.preheat_chamber_target_override}:BU),[L,R]=(0,y.useState)(()=>{if(e===`edit-queue-item`&&i){let e=`queue`;i.scheduled_time&&!Ap(i.scheduled_time)&&(e=`scheduled`);let t=``;return i.scheduled_time&&!Ap(i.scheduled_time)&&(t=Jf(Xf(i.scheduled_time)??new Date)),{scheduleType:e,scheduledTime:t,requireManualStart:i.manual_start,requirePreviousSuccess:i.require_previous_success,autoOffAfter:i.auto_off_after,gcodeInjection:i.gcode_injection??!1,staggerEnabled:!1,staggerGroupSize:VU.staggerGroupSize,staggerIntervalMinutes:VU.staggerIntervalMinutes}}return VU}),[z,B]=(0,y.useState)(()=>{if(e===`edit-queue-item`&&i?.ams_mapping&&Array.isArray(i.ams_mapping)){let e={};return i.ams_mapping.forEach((t,n)=>{t!==-1&&(e[n+1]=t)}),e}return{}}),[V,ee]=(0,y.useState)({}),[te,ne]=(0,y.useState)(()=>v||e===`edit-queue-item`&&i?.target_model?`model`:`printer`),[re,ie]=(0,y.useState)(()=>e===`edit-queue-item`&&i?.target_model?i.target_model:null),[ae,oe]=(0,y.useState)(()=>e===`edit-queue-item`&&i?.target_location?i.target_location:null),[se,H]=(0,y.useState)(()=>e===`edit-queue-item`?i?.cost_center_id??null:null),[ce,le]=(0,y.useState)(i?.estimated_cost??null),[ue,de]=(0,y.useState)({}),[fe,pe]=(0,y.useState)(()=>{if(e===`edit-queue-item`&&i?.filament_overrides){let e={};for(let t of i.filament_overrides)e[t.slot_id]={type:t.type,color:t.color};return e}return{}}),[me,he]=(0,y.useState)(()=>{if(e===`edit-queue-item`&&i?.filament_overrides){let e={};for(let t of i.filament_overrides)e[t.slot_id]=t.force_color_match===!0;return e}return{}}),[ge]=(0,y.useState)(()=>e===`edit-queue-item`&&i?.printer_id?[i.printer_id]:[]),[_e]=(0,y.useState)(()=>e===`edit-queue-item`&&i?i.plate_id:null),[ve,ye]=(0,y.useState)(!1),[be,xe]=(0,y.useState)({current:0,total:0}),[Se,Ce]=(0,y.useState)(null),[we,Te]=(0,y.useState)(new Set),Ee=E.length,De=E.length>0?E[0]:null,{data:Oe}=K({queryKey:[`settings`],queryFn:Z.getSettings}),ke=(0,y.useRef)(!1);(0,y.useEffect)(()=>{!Oe||ke.current||e===`edit-queue-item`||(ke.current=!0,I({bed_levelling:Oe.default_bed_levelling??BU.bed_levelling,flow_cali:Oe.default_flow_cali??BU.flow_cali,vibration_cali:Oe.default_vibration_cali??BU.vibration_cali,layer_inspect:Oe.default_layer_inspect??BU.layer_inspect,timelapse:Oe.default_timelapse??BU.timelapse,nozzle_offset_cali:Oe.default_nozzle_offset_cali??BU.nozzle_offset_cali,preheat_override:BU.preheat_override,preheat_chamber_target_override:BU.preheat_chamber_target_override}))},[Oe,e]);let Ae=(0,y.useRef)(!1);(0,y.useEffect)(()=>{!Oe||Ae.current||e===`edit-queue-item`||(Ae.current=!0,R(e=>({...e,staggerGroupSize:Oe.stagger_group_size??e.staggerGroupSize,staggerIntervalMinutes:Oe.stagger_interval_minutes??e.staggerIntervalMinutes})))},[Oe,e]);let je=Af(Oe?.currency||`USD`),Me=Oe?.default_filament_cost??0,Ne=Oe?.billing_enabled===!0,{data:Pe,isLoading:Fe}=K({queryKey:[`printers`],queryFn:Z.getPrinters}),{data:Ie,isLoading:Le}=K({queryKey:[`finance`,`cost-centers`,`mine`],queryFn:Z.getMyCostCenters,enabled:!!h&&Ne}),Re=(0,y.useMemo)(()=>(Ie||[]).filter(e=>e.can_print&&e.is_active),[Ie]),ze=(0,y.useMemo)(()=>Re.find(e=>e.id===se)??null,[Re,se]);(0,y.useEffect)(()=>{Re.length!==0&&(se!=null&&Re.some(e=>e.id===se)||H(Re.find(e=>e.is_private)?.id??Re[0].id))},[Re,se]);let Be=xo({queries:E.map(e=>({queryKey:[`printer-inventory-remain`,e],queryFn:()=>Z.getInventoryRemain(e),staleTime:30*1e3,refetchOnMount:`always`,enabled:E.length>0}))}),Ve=(0,y.useMemo)(()=>{let e=new Map;return E.forEach((t,n)=>{let r=Be[n]?.data?.inventory_remain_g;if(!r)return;let i=new Map;Object.entries(r).forEach(([e,t])=>{let n=Number(e);Number.isNaN(n)||i.set(n,t)}),e.set(t,i)}),e},[E,Be]),He=(0,y.useMemo)(()=>{let e=new Map;return E.forEach((t,n)=>{let r=Be[n]?.data?.slot_materials;if(!r)return;let i=new Map;r.forEach(e=>i.set(e.global_tray_id,e)),e.set(t,i)}),e},[E,Be]),{data:Ue}=K({queryKey:[`archive`,t],queryFn:()=>Z.getArchive(t),enabled:!!t&&!g}),{data:We}=K({queryKey:[`library-file`,n],queryFn:()=>Z.getLibraryFile(n),enabled:g&&!!n}),Ge=Ue?.sliced_for_model||We?.sliced_for_model||null,Ke=(0,y.useMemo)(()=>g?void 0:xke(Ue?.extra_data,De),[g,Ue?.extra_data,De]),{data:qe,isError:Je}=K({queryKey:[`archive-plates`,t],queryFn:()=>Z.getArchivePlates(t),enabled:!!t&&!g,retry:!1}),{data:Ye}=K({queryKey:[`library-file-plates`,n],queryFn:()=>Z.getLibraryFilePlates(n),enabled:g&&!!n}),Xe=g?Ye:qe,{data:Ze,isError:Qe}=K({queryKey:[`archive-filaments`,t,A],queryFn:()=>Z.getArchiveFilamentRequirements(t,A??void 0),enabled:!!t&&!g&&(A!==null||!Xe?.is_multi_plate),retry:!1}),{data:$e}=K({queryKey:[`library-file-filaments`,n,A],queryFn:()=>Z.getLibraryFileFilamentRequirements(n,A??void 0),enabled:g&&!!n&&(A!==null||!Xe?.is_multi_plate)}),et=!g&&(Je||Qe),tt=g?$e:Ze,{data:nt}=K({queryKey:[`available-filaments`,re,ae],queryFn:()=>Z.getAvailableFilaments(re,ae??void 0),enabled:te===`model`&&!!re}),rt=(0,y.useMemo)(()=>Array.from(new Set(S.map(e=>e.sliced_for_model).filter(e=>!!e))),[S]),it=xo({queries:v?rt.map(e=>({queryKey:[`available-filaments`,e,ae],queryFn:()=>Z.getAvailableFilaments(e,ae??void 0)})):[]}),at=(0,y.useMemo)(()=>{let e=new Set,t=[];for(let n of it)for(let r of n.data??[]){let n=`${r.type}|${r.color}|${r.tray_info_idx}`;e.has(n)||(e.add(n),t.push(r))}return t},[it]),ot=v?at:nt,{data:st,isLoading:ct}=K({queryKey:[`printer-status`,De],queryFn:()=>Z.getPrinterStatus(De),enabled:!!De}),lt=Pp(Oe?.prefer_lowest_filament,st?.ams_filament_backup),ut=async()=>{if(L.scheduleType!==`asap`||te!==`printer`||E.length===0)return!1;try{return(await Promise.all(E.map(e=>f.fetchQuery({queryKey:[`printer-status`,e],queryFn:()=>Z.getPrinterStatus(e),staleTime:0})))).some(e=>!_m(e))}catch{return!0}},{amsMapping:dt}=EU(tt,st,z,lt,De?Ve.get(De):void 0),ft=(0,y.useMemo)(()=>[...O].sort((e,t)=>e-t),[O]),pt=O.size>1,mt=xo({queries:(pt?ft:[]).map(e=>({queryKey:g?[`library-file-filaments`,n,e]:[`archive-filaments`,t,e],queryFn:()=>g?Z.getLibraryFileFilamentRequirements(n,e):Z.getArchiveFilamentRequirements(t,e),enabled:g?!!n:!!t,retry:!1}))}),ht=mt.some(e=>e.isPending),gt=mt.some(e=>e.isError),_t=(0,y.useMemo)(()=>{let e=new Map;return ft.forEach((t,n)=>{let r=mt[n]?.data;r&&e.set(t,r)}),e},[ft,mt.map(e=>e.dataUpdatedAt).join(`|`)]),[vt,yt]=(0,y.useState)({}),[bt,xt]=(0,y.useState)(()=>{if(e===`edit-queue-item`&&i?.nozzle_rack_choice){let e={};for(let[t,n]of Object.entries(i.nozzle_rack_choice)){let r=Number(t);Number.isInteger(r)&&Number.isInteger(n)&&(e[r]=n)}return e}return{}}),[St,Ct]=(0,y.useState)({}),wt=(0,y.useMemo)(()=>{let e=new Map;if(!pt||!De||E.length!==1)return e;let t=xU(st),n=st?.fila_switch?.installed===!0,r=Ve.get(De);for(let i of ft){let a=_t.get(i);if(!a)continue;let o=wU(a,t,vt[i]??{},lt,r,n);e.set(i,TU(o))}return e},[pt,De,st,Ve,ft,_t,vt,lt,E.length]),Tt=yke(E,Pe,tt,z,V,ee,Oe?.prefer_lowest_filament,Ve);(0,y.useEffect)(()=>{Xe?.plates&&Xe.plates.length>=1&&O.size===0&&k(new Set([Xe.plates[0].index]))},[Xe,O.size]),(0,y.useEffect)(()=>{if(e===`edit-queue-item`)return;let t=Pe?.filter(e=>e.is_active)||[];t.length===1&&E.length===0&&D([t[0].id])},[e,Pe,E.length]),(0,y.useEffect)(()=>{e===`edit-queue-item`?(JSON.stringify(E.sort())!==JSON.stringify(ge.sort())||A!==_e)&&(B({}),yt({}),ee({}),Te(new Set)):(B({}),yt({}),ee({}),Te(new Set))},[e,E,A,ge,_e]);let[Et,Dt]=(0,y.useState)(re),[Ot,kt]=(0,y.useState)(A);(0,y.useEffect)(()=>{(re!==Et||A!==Ot)&&(Dt(re),kt(A),(e!==`edit-queue-item`||Et!==null)&&(pe({}),he({})))},[re,A,Et,Ot,e]),(0,y.useEffect)(()=>{te!==`model`||re||!Ge||Pe?.some(e=>e.is_active&&e.model===Ge)&&ie(Ge)},[te,re,Ge,Pe]),(0,y.useEffect)(()=>{if(!Oe?.per_printer_mapping_expanded||E.length<=1)return;let e=E.filter(e=>{if(we.has(e))return!1;let t=Tt.printerResults.find(t=>t.printerId===e);return t&&t.status&&!t.isLoading});e.length>0&&(Te(t=>{let n=new Set(t);return e.forEach(e=>n.add(e)),n}),e.forEach(e=>{Tt.autoConfigurePrinter(e)}))},[Oe?.per_printer_mapping_expanded,E,we,Tt]),(0,y.useEffect)(()=>{let e=e=>{e.key===`Escape`&&!ve&&o()};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[o,ve]);let At=Xe?.is_multi_plate??!1,jt=Xe?.plates??[],Mt=(0,y.useMemo)(()=>{if(!Se||Se.length===0)return``;let e=Se.map(e=>e.pooled?d(`printModal.insufficientFilamentLinePooled`,{printer:e.printerName,slot:e.slotLabel,required:Math.round(e.requiredGrams),remaining:Math.round(e.remainingGrams)}):d(`printModal.insufficientFilamentLine`,{printer:e.printerName,slot:e.slotLabel,required:Math.round(e.requiredGrams),remaining:Math.round(e.remainingGrams)}));return[d(`printModal.insufficientFilamentMessage`),...e].join(` `)},[Se,d]),Nt=q({mutationFn:e=>Z.addToQueue(e)}),Pt=q({mutationFn:e=>Z.updateQueueItem(i.id,e),onSuccess:()=>{f.invalidateQueries({queryKey:[`queue`]}),p(`Queue item updated`),s?.(),o()},onError:e=>{p(e.message||`Failed to update queue item`,`error`)}}),Ft=(e,t)=>{if(pt)return t===null||E.length!==1?void 0:wt.get(t);if(E.length>1){let t=V[e];if(t&&!t.useDefault)return Tt.getFinalMapping(e)}return dt},It=async(i,a)=>{if(i?.preventDefault(),Ne&&ze==null){p(d(`printModal.noPrintableCostCenters`),`error`);return}if(!a?.skipFilamentCheck&&!Oe?.disable_filament_warnings&&!_&&te===`printer`){let e=[],t=pt?ft.map(e=>({plateId:e,reqs:_t.get(e)?.filaments??[]})):[{plateId:A,reqs:tt?.filaments??[]}];if(t.some(e=>e.reqs.length>0)&&He.size>0)for(let n of E){let r=E.length>1?Tt.printerResults.find(e=>e.printerId===n)?.status:st,i=xU(r),a=new Map(i.map(e=>[e.globalTrayId,e.label])),o=He.get(n),s=Pe?.find(e=>e.id===n)?.name??`Printer ${n}`;if(!o||o.size===0)continue;let c=new Map;for(let e of t){let t=Ft(n,e.plateId);t&&e.reqs.forEach(e=>{if(!e.slot_id||e.slot_id<=0)return;let n=t[e.slot_id-1];!Number.isFinite(n)||n<0||c.set(n,(c.get(n)??0)+e.used_grams)})}let l=r?.ams_filament_backup===!0,u=e=>`${e.material_key}#${e.extruder}`,d=new Map,f=new Map,p=new Map;if(l){o.forEach(e=>{let t=u(e);d.set(t,(d.get(t)??0)+e.remaining_g),f.set(t,(f.get(t)??0)+1)});for(let[e,t]of c){let n=o.get(e);if(!n)continue;let r=u(n);p.set(r,(p.get(r)??0)+t)}}for(let[t,n]of c){let r=o.get(t);if(!r)continue;let i=a.get(t)??`Tray ${t}`;if(l){let t=u(r),n=d.get(t)??0,a=p.get(t)??0;if(n>=a)continue;e.push({printerName:s,slotLabel:i,requiredGrams:a,remainingGrams:n,pooled:(f.get(t)??1)>1});continue}r.remaining_g>=n||e.push({printerName:s,slotLabel:i,requiredGrams:n,remainingGrams:r.remaining_g})}}if(e.length>0){Ce(e);return}}if(te===`printer`&&E.length===0){p(`Please select at least one printer`,`error`);return}if(!v&&te===`model`&&!re){p(`Please select a target printer model`,`error`);return}if(!v&&te===`model`&&!hm(Ge,re)){p(`File was sliced for ${Ge} and cannot be dispatched to ${re} printers`,`error`);return}ye(!0);let u=O.size>1?jt.filter(e=>O.has(e.index)):[null],m=te===`model`?u.length:E.length*u.length;xe({current:0,total:m});let h={success:0,failed:0,errors:[]},y=e=>{let t=[];if(e?.filaments)for(let n of e.filaments){let e=fe[n.slot_id],r=me[n.slot_id]??!1,i=e?.type??n.type,a=e?.color??n.color;(e||r)&&t.push({slot_id:n.slot_id,type:i,color:a,color_name:bf(a),force_color_match:r})}else for(let[e,{type:n,color:r}]of Object.entries(fe)){let i=parseInt(e,10),a=me[i]??!1;t.push({slot_id:i,type:n,color:r,color_name:bf(r),force_color_match:a})}return t.length>0?t:void 0},b=y(tt),x=e=>pt&&e!==null?y(_t.get(e)):b;if(v){try{await Z.addToQueue({variants:S.map(e=>({library_file_id:e.id,plate_id:w[e.id]??null,filament_overrides:b})),target_location:ae,require_previous_success:L.requirePreviousSuccess,auto_off_after:L.autoOffAfter,gcode_injection:L.gcodeInjection,manual_start:L.scheduleType===`queue`&&L.requireManualStart,scheduled_time:L.scheduleType===`scheduled`&&L.scheduledTime?new Date(L.scheduledTime).toISOString():void 0,quantity:j,...F,project_id:c??void 0}),p(d(`printModal.variants.queued`,{count:S.length}),`success`),f.invalidateQueries({queryKey:[`queue`]}),s?.(),o()}catch(e){p(e instanceof Error?e.message:String(e),`error`)}finally{ye(!1)}return}let C=u.map((e,t)=>{let n=e?e.index:A;return{plate_id:n,plate_name:e&&e.name||null,quantity_target:Vt(n),sort_order:t}}),T=C.reduce((e,t)=>e+t.quantity_target,0),D=e===`create`&&(u.length>1||T>1)&&(te===`model`||E.length===1),k=null;if(D)try{let e=(r||``).replace(/\.gcode\.3mf$/i,``).replace(/\.3mf$/i,``),i=u.length>1?`${e||`Batch`} · ${u.length} plates`:`${e||`Batch`} ×${T}`;k=(await Z.createBatch({name:i,archive_id:g?void 0:t,library_file_id:g?n:void 0,plates:C})).id}catch{k=null}let M=new Map,N=(e,t,n=1)=>{if(L.scheduleType!==`asap`)return;let r=t===null?`unassigned`:`printer:${t}`,i=(M.get(r)??0)+1;e.insert_at_top=!0,e.insert_position=i,M.set(r,i+n-1)},P=e=>{let t=e!=null&&pt?St[e]:bt;return t&&Object.keys(t).length>0?t:void 0},I=(e,r)=>{let i=r===void 0?A:r,o=i!=null&&pt?ue[i]??null:ce;return{printer_id:te===`printer`?e:null,target_model:te===`model`?re:null,target_location:te===`model`?ae:null,filament_overrides:te===`model`?x(i):void 0,archive_id:g?void 0:t,library_file_id:g?n:void 0,require_previous_success:L.requirePreviousSuccess,auto_off_after:L.autoOffAfter,gcode_injection:L.gcodeInjection,manual_start:L.scheduleType===`queue`&&L.requireManualStart,skip_filament_check:a?.skipFilamentCheck===!0?!0:void 0,ams_mapping:e?Ft(e,i):void 0,nozzle_rack_choice:e?P(i):void 0,plate_id:i,scheduled_time:L.scheduleType===`scheduled`&&L.scheduledTime?new Date(L.scheduledTime).toISOString():void 0,...F,project_id:c??void 0,cost_center_id:Ne?se:void 0,estimated_cost:Ne&&se!=null?o:void 0,batch_id:k??void 0,cleanup_library_after_dispatch:l}};if(te===`model`){let t=0;for(let n of u){t++,xe({current:t,total:m});let r=n?n.index:A;try{if(e===`edit-queue-item`&&!n){let e={printer_id:null,target_model:re,target_location:ae,filament_overrides:b||null,require_previous_success:L.requirePreviousSuccess,auto_off_after:L.autoOffAfter,gcode_injection:L.gcodeInjection,manual_start:L.scheduleType===`queue`&&L.requireManualStart,ams_mapping:void 0,plate_id:r,scheduled_time:L.scheduleType===`scheduled`&&L.scheduledTime?new Date(L.scheduledTime).toISOString():null,...F,cost_center_id:Ne?se:void 0,estimated_cost:Ne&&se!=null?ce:void 0};await Pt.mutateAsync(e)}else{let e=I(null,r),t=Vt(r);t>1&&(e.quantity=t),N(e,null,t),await Nt.mutateAsync(e)}h.success++}catch(e){h.failed++;let t=n?n.name||`Plate ${n.index}`:``;h.errors.push(t?`${t}: ${e.message}`:e.message)}}}else{let e=L.staggerEnabled&&!_&&E.length>1,t=e?L.scheduleType===`scheduled`&&L.scheduledTime?new Date(L.scheduledTime).getTime():Date.now():0,n=0;for(let r of u){let i=r?r.index:A;for(let a=0;a1&&(n.quantity=r),N(n,o,r),e){let e=Math.floor(a/L.staggerGroupSize);if(e>0){let r=e*L.staggerIntervalMinutes*6e4;n.scheduled_time=new Date(t+r).toISOString()}}await Nt.mutateAsync(n)}h.success++}catch(e){h.failed++;let t=Pe?.find(e=>e.id===o)?.name||`Printer ${o}`,n=r?r.name||`Plate ${r.index}`:``,i=n?`${t} (${n})`:t;h.errors.push(`${i}: ${e.message}`)}}}}ye(!1),h.failed===0?(_?e===`edit-queue-item`&&p(`Queue item updated`):h.success===1?p(await ut()?d(`queue.printQueuedWillStartWhenIdle`):te===`model`?`Queued for any ${re}`:d(`queue.printQueued`)):p(await ut()?d(`queue.printQueuedWillStartWhenIdle`):d(`queue.itemsQueued`,{count:h.success})),f.invalidateQueries({queryKey:[`queue`]}),s?.(),o()):h.success===0?p(`Failed: ${h.errors[0]}`,`error`):(p(`${h.success} succeeded, ${h.failed} failed`,`error`),f.invalidateQueries({queryKey:[`queue`]}))},Lt=ve||Pt.isPending,Rt=(0,y.useMemo)(()=>!(Lt||Ne&&(Le||ze==null)||te===`printer`&&E.length===0||!v&&te===`model`&&!re||!v&&te===`model`&&!hm(Ge,re)||At&&O.size===0||ht||gt||te===`printer`&&E.length===1&&ct),[E.length,te,re,Ge,At,O.size,Lt,ht,gt,ct,v,Ne,Le,ze]),zt=te===`printer`&&E.length>1?1:j,Bt=e===`create`&&At&&jt.length>1,Vt=e=>!Bt||e==null?zt:te===`printer`&&E.length>1?1:Math.max(1,N[e]??1);(0,y.useEffect)(()=>{e===`create`&&L.gcodeInjection&&!Oe?.gcode_snippets&&R(e=>({...e,gcodeInjection:!1}))},[e,Oe?.gcode_snippets,L.gcodeInjection]);let Ht=_?{title:d(`queue.editQueueItem`),icon:Ol,submitText:d(`common.save`),submitIcon:Ol,loadingText:be.total>1?d(`queue.savingProgress`,{current:be.current,total:be.total}):d(`common.saving`)}:{title:d(`common.print`),icon:Il,submitText:d(`common.print`),submitIcon:Il,loadingText:be.total>1?d(`queue.addingProgress`,{current:be.current,total:be.total}):d(`queue.adding`)},Ut=Ht.icon,Wt=Ht.submitIcon,Gt=De&&O.size<=1&&(g||(At?A!==null:!0));(0,y.useEffect)(()=>{(!Gt||et||E.length!==1)&&le(null)},[et,E.length,Gt]);let Kt=!!De&&pt&&E.length===1,qt=te===`model`&&(v||!!re)&&!!ot&&ot.length>0,Jt=(0,y.useMemo)(()=>new Set([`H2D`,`H2DPRO`,`H2C`,`X2D`]),[]),Yt=(0,y.useMemo)(()=>te===`model`?re?Jt.has(re.toUpperCase().replace(/[\s-]/g,``)):!1:!Pe||E.length===0?!1:E.some(e=>Pe.find(t=>t.id===e)?.nozzle_count===2),[te,re,Pe,E,Jt]);return(0,G.jsxs)(`div`,{className:`fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4`,onClick:ve?void 0:o,children:[(0,G.jsx)(Md,{className:`w-full max-w-4xl max-h-[90vh] overflow-y-auto`,onClick:e=>e.stopPropagation(),children:(0,G.jsxs)(Pd,{className:`p-0`,children:[(0,G.jsxs)(`div`,{className:`flex items-center justify-between p-4 border-b border-bambu-dark-tertiary`,children:[(0,G.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,G.jsx)(Ut,{className:`w-5 h-5 text-bambu-green`}),(0,G.jsx)(`h2`,{className:`text-lg font-semibold text-white`,children:Ht.title})]}),(0,G.jsx)(Q,{variant:`ghost`,size:`sm`,onClick:o,disabled:ve,children:(0,G.jsx)(ed,{className:`w-5 h-5`})})]}),(0,G.jsxs)(`form`,{onSubmit:It,className:`p-4 space-y-4`,children:[(0,G.jsxs)(`p`,{className:`text-sm text-bambu-gray`,children:[(0,G.jsx)(`span`,{className:`block text-bambu-gray mb-1`,children:`Print Job`}),(0,G.jsx)(`span`,{className:`text-white font-medium truncate block`,children:r})]}),(()=>{if(!jt.length)return null;let e=kU((A==null?jt[0]:jt.find(e=>e.index===A))?.bed_type);return e?(0,G.jsxs)(`p`,{className:`flex items-center gap-1.5 text-xs text-bambu-gray -mt-2`,title:e.label,children:[(0,G.jsx)(`img`,{src:e.icon,alt:``,className:`w-4 h-4 object-contain flex-shrink-0`}),(0,G.jsx)(`span`,{className:`truncate`,children:e.label})]}):null})(),(0,G.jsx)(Eke,{plates:jt,isMultiPlate:At,selectedPlates:O,onToggle:e=>{k(t=>{let n=new Set(t);return _?(n.clear(),n.add(e)):n.has(e)?n.delete(e):n.add(e),n})},onSelectAll:_?void 0:()=>k(new Set(jt.map(e=>e.index))),onDeselectAll:_?void 0:()=>k(new Set),multiSelect:!_,quantities:Bt?N:void 0,onQuantityChange:Bt?(e,t)=>P(n=>({...n,[e]:t})):void 0}),v&&(0,G.jsx)(zU,{candidates:S,onReorder:C,plateByFile:w,onPlateChange:(e,t)=>T(n=>({...n,[e]:t}))}),x&&(0,G.jsx)(zU,{candidates:b,readOnly:!0,readOnlyNote:d(`printModal.variants.editNote`),onReorder:()=>{},plateByFile:{},onPlateChange:()=>{}}),!v&&!x&&!a?.length&&(0,G.jsx)(kke,{printers:Pe||[],selectedPrinterIds:E,onMultiSelect:D,isLoading:Fe,allowMultiple:!0,showInactive:e===`edit-queue-item`,disableBusy:!1,printerMappingResults:Tt.printerResults,filamentReqs:pt?void 0:tt,onAutoConfigurePrinter:Tt.autoConfigurePrinter,onUpdatePrinterConfig:Tt.updatePrinterConfig,assignmentMode:te,onAssignmentModeChange:ne,targetModel:re,onTargetModelChange:ie,targetLocation:ae,onTargetLocationChange:oe,slicedForModel:Ge}),qt&&!pt&&tt&&(0,G.jsx)(IU,{filamentReqs:tt,availableFilaments:ot,overrides:fe,onChange:pe,forceColorMatch:me,onForceColorMatchChange:(e,t)=>he(n=>({...n,[e]:t}))}),qt&&pt&&ft.map((e,t)=>{let n=jt.find(t=>t.index===e),r=_t.get(e);return r?(0,G.jsx)(IU,{plateLabel:n?.name||d(`printModal.plateN`,`Plate {{n}}`,{n:e}),showHint:t===0,filamentReqs:r,availableFilaments:nt,overrides:fe,onChange:pe,forceColorMatch:me,onForceColorMatchChange:(e,t)=>he(n=>({...n,[e]:t}))},e):null}),Ge&&te===`printer`&&E.length===1&&(()=>{let e=Pe?.find(e=>e.id===E[0]);return e&&e.model&&Ge!==e.model?(0,G.jsxs)(`div`,{className:`p-3 mb-2 bg-yellow-50 dark:bg-yellow-500/10 border border-yellow-300 dark:border-yellow-500/30 rounded-lg flex items-center gap-2`,children:[(0,G.jsx)(Fu,{className:`w-4 h-4 text-yellow-600 dark:text-yellow-400 flex-shrink-0`}),(0,G.jsxs)(`span`,{className:`text-sm text-yellow-700 dark:text-yellow-400`,children:[`File was sliced for `,Ge,`, but printing on `,e.model]})]}):null})(),et&&(0,G.jsxs)(`div`,{className:`flex items-start gap-2 p-3 mb-2 bg-orange-50 dark:bg-orange-500/10 border border-orange-300 dark:border-orange-500/30 rounded-lg text-sm`,children:[(0,G.jsx)(_s,{className:`w-4 h-4 text-orange-600 dark:text-orange-400 mt-0.5 flex-shrink-0`}),(0,G.jsx)(`p`,{className:`text-orange-700 dark:text-orange-400`,children:`Archive data unavailable. The source file may have been deleted. Filament mapping is disabled.`})]}),gt&&(0,G.jsxs)(`div`,{className:`flex items-start gap-2 p-3 mb-2 bg-orange-50 dark:bg-orange-500/10 border border-orange-300 dark:border-orange-500/30 rounded-lg text-sm`,children:[(0,G.jsx)(_s,{className:`w-4 h-4 text-orange-600 dark:text-orange-400 mt-0.5 flex-shrink-0`}),(0,G.jsx)(`p`,{className:`text-orange-700 dark:text-orange-400`,children:d(`printModal.plateFilamentsUnreadable`,`The filaments of a selected plate could not be read, so it can't be mapped. Deselect it to queue the others.`)})]}),Gt&&!et&&E.length===1&&(0,G.jsx)(FU,{printerId:De,filamentReqs:tt,manualMappings:z,onManualMappingChange:B,onEstimatedCostChange:le,budgetAvailable:Ne?ze?.budget_available??null:null,quantity:zt,defaultExpanded:!!a?.length||(Oe?.per_printer_mapping_expanded??!1),currencySymbol:je,defaultCostPerKg:Me,forceColorMatch:me,onForceColorMatchChange:(e,t)=>he(n=>({...n,[e]:t})),archiveAmsMapping:Ke,nozzleRackChoice:bt,onNozzleRackChoiceChange:xt}),Kt&&!et&&ft.map(e=>{let t=jt.find(t=>t.index===e),n=_t.get(e);return n?(0,G.jsx)(FU,{printerId:De,plateLabel:t?.name||d(`printModal.plateN`,`Plate {{n}}`,{n:e}),filamentReqs:n,manualMappings:vt[e]??{},onManualMappingChange:t=>yt(n=>({...n,[e]:t})),onEstimatedCostChange:t=>de(n=>({...n,[e]:t})),budgetAvailable:Ne?ze?.budget_available??null:null,quantity:Vt(e),defaultExpanded:!1,currencySymbol:je,defaultCostPerKg:Me,forceColorMatch:me,onForceColorMatchChange:(e,t)=>he(n=>({...n,[e]:t})),archiveAmsMapping:Ke,nozzleRackChoice:St[e]??{},onNozzleRackChoiceChange:t=>Ct(n=>({...n,[e]:t}))},e):null}),(e===`create`||Ee>0||te===`model`&&re)&&(0,G.jsx)(jke,{options:F,onChange:I,defaultExpanded:!!a?.length,showDualNozzleOptions:Yt}),Ne&&Re.length>0&&(0,G.jsx)(Nke,{costCenters:Re,selectedCostCenterId:se,onChange:H}),Ne&&!Le&&Re.length===0&&(0,G.jsxs)(`div`,{role:`alert`,className:`p-3 bg-yellow-100 dark:bg-yellow-500/20 border border-yellow-500/50 rounded-lg text-sm text-yellow-800 dark:text-yellow-300 flex items-start gap-2`,children:[(0,G.jsx)(Fu,{className:`w-4 h-4 mt-0.5 shrink-0`}),d(`printModal.noPrintableCostCenters`)]}),e!==`edit-queue-item`&&!Bt&&(te===`model`||E.length<=1)&&(0,G.jsxs)(`div`,{className:`flex items-center gap-3`,children:[(0,G.jsx)(`label`,{htmlFor:`printQuantity`,className:`text-sm text-bambu-gray whitespace-nowrap`,children:d(`queue.quantity`,`Quantity`)}),(0,G.jsx)(`input`,{id:`printQuantity`,type:`number`,min:1,max:999,value:j,onChange:e=>M(Math.max(1,Math.min(999,parseInt(e.target.value)||1))),className:`w-20 px-2 py-1 text-sm bg-bambu-dark border border-bambu-dark-tertiary rounded text-white focus:outline-none focus:ring-1 focus:ring-bambu-green`}),j>1&&(0,G.jsx)(`span`,{className:`text-xs text-bambu-gray`,children:d(`queue.quantityHint`,`Creates {{count}} queue items`,{count:j})})]}),(0,G.jsx)(Mke,{options:L,onChange:R,dateFormat:Oe?.date_format||`system`,timeFormat:Oe?.time_format||`system`,canControlPrinter:m(`printers:control`),showStagger:!_&&te===`printer`&&E.length>1,printerCount:E.length,hasGcodeSnippets:!!Oe?.gcode_snippets}),Pt.isError&&(0,G.jsx)(`div`,{className:`mb-4 p-3 bg-red-100 dark:bg-red-500/20 border border-red-500/50 rounded-lg text-sm text-red-700 dark:text-red-400`,children:Pt.error?.message||`Failed to complete operation`}),te===`printer`&&E.length===1&&ct&&(0,G.jsxs)(`div`,{className:`mb-4 p-3 bg-blue-100 dark:bg-blue-500/20 border border-blue-500/50 rounded-lg text-sm text-blue-700 dark:text-blue-400 flex items-center gap-2`,children:[(0,G.jsx)(Y,{className:`w-4 h-4 animate-spin`}),d(`printModal.waitingForAmsStatus`,{printer:Pe?.find(e=>e.id===De)?.name??``})]}),(0,G.jsxs)(`div`,{className:`flex gap-3 pt-2`,children:[(0,G.jsx)(Q,{type:`button`,variant:`secondary`,onClick:o,className:`flex-1`,disabled:ve,children:`Cancel`}),(0,G.jsx)(Q,{type:`submit`,disabled:!Rt,className:`flex-1`,children:Lt?(0,G.jsxs)(G.Fragment,{children:[(0,G.jsx)(Y,{className:`w-4 h-4 animate-spin`}),Ht.loadingText]}):(0,G.jsxs)(G.Fragment,{children:[(0,G.jsx)(Wt,{className:`w-4 h-4`}),Ht.submitText]})})]})]})]})}),Se&&Se.length>0&&(0,G.jsx)(Qd,{title:d(`printModal.insufficientFilamentTitle`),message:Mt,confirmText:d(`printModal.printAnyway`),cancelText:d(`common.cancel`),variant:`warning`,onConfirm:()=>{Ce(null),It(void 0,{skipFilamentCheck:!0})},onCancel:()=>Ce(null)})]})}function UU({value:e,titleKey:t=`printers.copyToClipboard`,copiedTitleKey:n=`printers.copied`,className:r=`ml-2 p-1 rounded hover:bg-bambu-dark-tertiary text-bambu-gray hover:text-white transition-colors`,iconClassName:i=`w-3.5 h-3.5`}){let{t:a}=U(),[o,s]=(0,y.useState)(!1);return(0,G.jsx)(`button`,{onClick:async()=>{try{if(navigator.clipboard&&window.isSecureContext)await navigator.clipboard.writeText(e);else{let t=document.createElement(`textarea`);t.value=e,t.style.position=`fixed`,t.style.opacity=`0`,document.body.appendChild(t);try{if(t.select(),!document.execCommand(`copy`))return}finally{document.body.removeChild(t)}}s(!0),setTimeout(()=>s(!1),2e3)}catch{}},className:r,title:a(o?n:t),children:o?(0,G.jsx)(us,{className:`${i} text-bambu-green`}):(0,G.jsx)(zs,{className:i})})}function Pke({printer:e,status:t,totalPrintHours:n,onClose:r}){let{t:i}=U();(0,y.useEffect)(()=>{let e=e=>{e.key===`Escape`&&r()};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[r]);let a=[];if(a.push({label:i(`printers.model`),value:e.model??`—`}),a.push({label:i(`common.status`),value:(0,G.jsxs)(`span`,{className:`inline-flex items-center gap-1.5 px-2 py-0.5 rounded-full text-xs font-medium ${t?.connected?`bg-bambu-green/20 text-bambu-green`:`bg-red-100 dark:bg-red-500/20 text-red-700 dark:text-red-400`}`,children:[(0,G.jsx)(`span`,{className:`w-1.5 h-1.5 rounded-full ${t?.connected?`bg-bambu-green`:`bg-red-400`}`}),t?.connected?i(`printers.status.available`):i(`printers.status.offline`)]})}),t?.state&&a.push({label:i(`printers.state`),value:i({IDLE:`printers.status.idle`,RUNNING:`printers.status.printing`,PAUSE:`printers.status.paused`,FINISH:`printers.status.finished`,FAILED:`printers.status.error`}[t.state]??`printers.status.unknown`)}),a.push({label:i(`printers.ipAddress`),value:(0,G.jsxs)(`span`,{className:`flex items-center`,children:[(0,G.jsx)(`span`,{className:`font-mono`,children:e.ip_address}),(0,G.jsx)(UU,{value:e.ip_address})]})}),a.push({label:i(`printers.serialNumber`),value:(0,G.jsxs)(`span`,{className:`flex items-center`,children:[(0,G.jsx)(`span`,{className:`font-mono truncate`,children:e.serial_number}),(0,G.jsx)(UU,{value:e.serial_number})]})}),t?.wired_network)a.push({label:i(`printers.networkLabel`,`Network`),value:(0,G.jsxs)(`span`,{className:`flex items-center gap-2`,children:[(0,G.jsx)($o,{className:`w-4 h-4 text-bambu-green`}),(0,G.jsx)(`span`,{className:`text-bambu-green`,children:i(`printers.connection.ethernet`,`Ethernet`)})]})});else if(t?.wifi_signal!=null){let e=gm(t.wifi_signal);a.push({label:i(`printers.wifiSignalLabel`),value:(0,G.jsxs)(`span`,{className:`flex items-center gap-2`,children:[(0,G.jsx)(su,{className:`w-4 h-4 ${e.color}`}),(0,G.jsx)(`span`,{className:e.color,children:i(e.labelKey)}),(0,G.jsxs)(`span`,{className:`text-bambu-gray text-xs`,children:[`(`,t.wifi_signal,` dBm)`]})]})})}return a.push({label:i(`printers.firmware`),value:t?.firmware_version??`—`}),t?.developer_mode!=null&&a.push({label:i(`printers.developerMode`),value:(0,G.jsx)(`span`,{className:`inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium ${t.developer_mode?`bg-bambu-green/20 text-bambu-green`:`bg-bambu-dark-tertiary text-bambu-gray`}`,children:t.developer_mode?i(`printers.enabled`):i(`printers.disabled`)})}),a.push({label:i(`printers.nozzleCount`),value:e.nozzle_count}),a.push({label:i(`printers.autoArchive`),value:(0,G.jsx)(`span`,{className:`inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium ${e.auto_archive?`bg-bambu-green/20 text-bambu-green`:`bg-bambu-dark-tertiary text-bambu-gray`}`,children:e.auto_archive?i(`printers.enabled`):i(`printers.disabled`)})}),n!=null&&n>0&&a.push({label:i(`printers.totalPrintHours`),value:`${Math.round(n)}h`}),e.location&&a.push({label:i(`printers.sort.location`),value:e.location}),a.push({label:i(`printers.addedOn`),value:Qf(e.created_at)}),(0,G.jsx)(`div`,{className:`fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4`,role:`dialog`,"aria-modal":`true`,onClick:r,children:(0,G.jsx)(Md,{className:`w-full max-w-md`,onClick:e=>e.stopPropagation(),children:(0,G.jsxs)(Pd,{children:[(0,G.jsxs)(`div`,{className:`flex items-center justify-between mb-4`,children:[(0,G.jsx)(`h2`,{className:`text-lg font-semibold text-white`,children:e.name}),(0,G.jsx)(`button`,{onClick:r,className:`p-1 hover:bg-bambu-dark rounded flex-shrink-0`,children:(0,G.jsx)(ed,{className:`w-5 h-5 text-bambu-gray`})})]}),(0,G.jsx)(`div`,{className:`flex justify-center mb-4`,children:(0,G.jsx)(`img`,{src:mm(e.model),alt:e.model??e.name,className:`h-24 object-contain`})}),(0,G.jsx)(`div`,{className:`space-y-0`,children:a.map((e,t)=>(0,G.jsxs)(`div`,{className:`flex items-center justify-between gap-4 py-2.5 border-b border-bambu-dark-tertiary last:border-0`,children:[(0,G.jsx)(`span`,{className:`text-sm text-bambu-gray whitespace-nowrap`,children:e.label}),(0,G.jsx)(`span`,{className:`text-sm text-white text-right`,children:e.value})]},t))})]})})})}var WU=0,GU=1;function Fke({slotLabel:e,amsId:t,slotId:n,extruderSlots:r,isLoading:i=!1,onConfirm:a,onCancel:o}){let{t:s}=U(),[c,l]=(0,y.useState)(null);(0,y.useEffect)(()=>{let e=e=>{e.key===`Escape`&&!i&&o()};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[o,i]);let u=e=>{let i=r[String(e)];return i?.ams_id===t&&i?.slot_id===n},d=[{extruderId:GU,label:s(`printers.ams.feedLeft`),taken:u(GU)},{extruderId:WU,label:s(`printers.ams.feedRight`),taken:u(WU)}],f=d.some(e=>e.extruderId===c&&e.taken);return(0,y.useEffect)(()=>{f&&l(null)},[f]),(0,G.jsx)(`div`,{className:`fixed inset-0 bg-black/50 flex items-center justify-center p-4 z-50`,onClick:i?void 0:o,children:(0,G.jsx)(Md,{className:`w-full max-w-md`,onClick:e=>e.stopPropagation(),children:(0,G.jsxs)(Pd,{className:`p-6`,children:[(0,G.jsx)(`h3`,{className:`text-lg font-semibold text-white mb-2`,children:s(`printers.ams.feedTitle`,{slot:e})}),(0,G.jsx)(`p`,{className:`text-bambu-gray text-sm`,children:s(`printers.ams.feedPrompt`)}),(0,G.jsx)(`div`,{className:`grid grid-cols-2 gap-3 mt-4`,children:d.map(({extruderId:e,label:t,taken:n})=>{let r=c===e;return(0,G.jsxs)(`button`,{type:`button`,onClick:()=>l(e),disabled:n||i,title:n?s(`printers.ams.feedAlreadyLoaded`):void 0,className:`p-3 rounded-lg border text-sm transition-colors ${n?`border-transparent bg-bambu-dark text-bambu-gray/50 cursor-not-allowed`:r?`border-bambu-green/50 bg-bambu-green/10 text-white`:`border-transparent bg-bambu-dark text-white hover:bg-bambu-dark-tertiary`}`,children:[(0,G.jsx)(`div`,{className:`font-medium`,children:t}),n&&(0,G.jsx)(`div`,{className:`text-xs mt-1`,children:s(`printers.ams.feedAlreadyLoaded`)})]},e)})}),(0,G.jsxs)(`div`,{className:`flex gap-3 mt-6`,children:[(0,G.jsx)(Q,{variant:`secondary`,onClick:o,className:`flex-1`,disabled:i,children:s(`common.cancel`)}),(0,G.jsx)(Q,{onClick:()=>c!==null&&a(c),className:`flex-1`,disabled:c===null||i,children:i?(0,G.jsxs)(G.Fragment,{children:[(0,G.jsx)(Y,{className:`w-4 h-4 mr-2 animate-spin`}),s(`common.loading`)]}):s(`common.confirm`)})]})]})})})}function Ike(e){if(!e||e.length<6)return!1;let t=parseInt(e.slice(0,2),16),n=parseInt(e.slice(2,4),16),r=parseInt(e.slice(4,6),16);return(.299*t+.587*n+.114*r)/255>.6}function KU({trayColor:e,trayType:t,isEmpty:n,emptyKind:r,slotNumber:i}){let a=r===`reset`?`#3d3d3d`:`#666`;return(0,G.jsx)(`div`,{className:`w-3.5 h-3.5 rounded-full mx-auto mb-0.5 border-2 flex items-center justify-center`,style:{backgroundColor:e?`#${e}`:t?`#333`:`transparent`,borderColor:n?a:`rgba(255,255,255,0.1)`,borderStyle:n?`dashed`:`solid`},children:(0,G.jsx)(`span`,{className:`text-[6px] font-bold leading-none select-none`,style:{color:e&&Ike(e)?`#000`:`#fff`},children:i})})}var Lke=240,Rke=440,zke=[30,60,120,240,480,720,1440],qU=[`scheduled-dryings`],Bke={ams_power_required:`printers.drying.powerRequired`,ams_retract_filament:`printers.drying.retractFilament`,ams_blocked:`printers.drying.cannotDryNow`,ams_not_found:`printers.drying.waitingAmsNotFound`,printer_offline:`printers.drying.waitingOffline`,printer_busy:`printers.drying.waitingPrinterBusy`,already_drying:`printers.drying.waitingAlreadyDrying`,interrupted:`printers.drying.waitingInterrupted`};function Vke(e){return e?Bke[e]:void 0}function Hke(e){let t=(e??[]).map(e=>Number(e));return t.some(e=>e===1||e===8)?`printers.drying.powerRequired`:t.includes(3)?`printers.drying.retractFilament`:`printers.drying.cannotDryNow`}var JU=[{value:`all`,labelKey:`printers.filter.allStatuses`},{value:`printing`,labelKey:`printers.status.printing`},{value:`paused`,labelKey:`printers.status.paused`},{value:`idle`,labelKey:`printers.status.idle`},{value:`finished`,labelKey:`printers.status.finished`},{value:`error`,labelKey:`printers.status.error`},{value:`offline`,labelKey:`printers.status.offline`}];function Uke(e){return JU.some(t=>t.value===e)}function YU(e){return(e??.02).toFixed(3)}function XU({k:e,reserve:t}){let{t:n}=U(),r=`text-[length:var(--pc-t8,8px)] text-bambu-gray tabular-nums leading-none truncate`;return e?(0,G.jsxs)(`div`,{className:r,title:n(`ams.kFactor`),children:[n(`ams.kFactorShort`),` `,YU(e)]}):t?(0,G.jsx)(`div`,{className:r,"aria-hidden":`true`,children:`\xA0`}):null}function ZU({side:e}){let{mode:t}=kd(),{t:n}=U();return(0,G.jsx)(`span`,{className:`inline-flex items-center justify-center w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)] text-[length:var(--pc-t10,10px)] font-bold rounded`,style:{backgroundColor:t===`dark`?`#1a4d2e`:`#e7f5e9`,color:`#00ae42`},title:n(e===`L`?`common.left`:`common.right`),children:e})}function QU({inlet:e,title:t}){let{mode:n}=kd();return(0,G.jsx)(`span`,{className:`inline-flex items-center justify-center w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)] text-[length:var(--pc-t10,10px)] font-bold rounded`,style:{backgroundColor:n===`dark`?`#1e3a5f`:`#e3f0fb`,color:`#3b82f6`},title:t,children:lp[e]})}function $U(e,t,n,r){let i=n[String(e)];if(i)return{kind:`inlet`,inlet:i};let a=t[String(e)],o=a===void 0?r?void 0:e>=128?e-128:e:a;return o===1?{kind:`nozzle`,side:`L`}:o===0?{kind:`nozzle`,side:`R`}:null}function eW(e,t){if(!e)return``;if(e.includes(`hardened`))return t(`printers.nozzleHardenedSteel`);if(e.includes(`stainless`))return t(`printers.nozzleStainlessSteel`);if(e.includes(`tungsten`))return t(`printers.nozzleTungstenCarbide`);if(e.length>=4){let n=e.slice(2,4);if(n===`00`)return t(`printers.nozzleStainlessSteel`);if(n===`01`)return t(`printers.nozzleHardenedSteel`);if(n===`05`)return t(`printers.nozzleTungstenCarbide`)}return e===`00`?t(`printers.nozzleStainlessSteel`):e===`01`?t(`printers.nozzleHardenedSteel`):e===`05`?t(`printers.nozzleTungstenCarbide`):e.startsWith(`H`)?t(`printers.nozzleHardenedSteel`):e}function tW(e,t){return e?e.startsWith(`HH`)?t(`printers.nozzleHighFlow`):e.startsWith(`HS`)?t(`printers.nozzleStandardFlow`):``:``}function nW({slot:e,index:t,activeStatus:n,filamentName:r,children:i}){let{t:a}=U(),[o,s]=(0,y.useState)(!1),[c,l]=(0,y.useState)(`top`),u=(0,y.useRef)(null),d=(0,y.useRef)(null),f=(0,y.useRef)(null),p=!e.nozzle_diameter&&!e.nozzle_type,m=e.stat===1;(0,y.useEffect)(()=>{if(o&&u.current&&d.current){let e=u.current.getBoundingClientRect(),t=d.current.offsetHeight,n=e.top-56,r=window.innerHeight-e.bottom;nn?l(`bottom`):l(`top`)}},[o]);let h=()=>{f.current&&clearTimeout(f.current),f.current=setTimeout(()=>s(!0),80)},g=()=>{f.current&&clearTimeout(f.current),f.current=setTimeout(()=>s(!1),100)};(0,y.useEffect)(()=>()=>{f.current&&clearTimeout(f.current)},[]);let _=Ef(e.filament_color),v=eW(e.nozzle_type,a),b=tW(e.nozzle_type,a);return(0,G.jsxs)(`div`,{ref:u,className:`relative`,onMouseEnter:h,onMouseLeave:g,children:[i,o&&(0,G.jsxs)(`div`,{ref:d,className:` absolute left-1/2 -translate-x-1/2 z-50 ${c===`top`?`bottom-full mb-2`:`top-full mt-2`} diff --git a/static/index.html b/static/index.html index 3b1b01443..746042534 100644 --- a/static/index.html +++ b/static/index.html @@ -26,7 +26,7 @@ - +