From f6c6cfbad345c3a60962af34482feeca118b9426 Mon Sep 17 00:00:00 2001 From: maziggy Date: Thu, 9 Jul 2026 09:27:13 +0200 Subject: [PATCH] fix(ams): show "?" not "Empty" for non-RFID spools using tray_exist_bits (#2527) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A spool with no readable RFID was reported by the standard AMS with an empty tray_type and state=9 — structurally identical to a truly-empty slot at the tray level — so the AMS card rendered it "Empty" while Bambu Studio correctly showed "?". The authoritative "a spool is physically here" signal is firmware's AMS-level tray_exist_bits bitmask (what Studio uses), but Bambuddy inferred emptiness from the per-tray state/tray_type. Confirmed from the reporter's bundle: tray_exist_bits=f (all four slots present) with tray_is_bbl_bits=5 (only slots 0,2 Bambu) — the present-but-non-Bambu slots were the ones shown Empty. Supersedes closed #1838. apply_tray_exist_bits() already parses the bitmask to clear stale fields on absent slots; it now also annotates each slot with an authoritative `exists` bool, gated behind a new annotate_exists flag so only the printer-card path sets it. The VP bridge leaves it off, so the `exists` key never reaches the slicer wire format. `exists` flows through the AMSTray schema/serialization to the frontend, where getEmptySlotKind() uses it: exists===true + no tray_type -> "?" (present, unconfigured), exists===false -> "Empty", exists absent -> the previous state=9/10 heuristic (AMS-HT and missing-bitmask paths unchanged). H2D/X1C already reported present-unknown slots with a non-9 state and took the "?" path; with the fix they reach it via `exists` and are unaffected. --- CHANGELOG.md | 1 + backend/app/api/routes/printers.py | 1 + backend/app/schemas/printer.py | 4 +++ backend/app/services/bambu_mqtt.py | 12 +++++++ .../tests/unit/services/test_bambu_mqtt.py | 34 +++++++++++++++++++ .../spoolbuddy/AmsUnitCard.test.tsx | 19 +++++++++++ frontend/src/api/client.ts | 1 + .../src/components/spoolbuddy/AmsUnitCard.tsx | 12 ++++--- frontend/src/pages/PrintersPage.tsx | 9 ++++- .../{index-CJ6VzpV2.js => index-CWda6lvk.js} | 4 +-- static/index.html | 2 +- 11 files changed, 91 insertions(+), 8 deletions(-) rename static/assets/{index-CJ6VzpV2.js => index-CWda6lvk.js} (99%) diff --git a/CHANGELOG.md b/CHANGELOG.md index 140e40848..11ece4cc9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -37,6 +37,7 @@ All notable changes to Bambuddy will be documented in this file. - **Sort File Manager folder tree by recent activity (#1770, requested by @Kingbuzz0)** — Until now the folder tree was always sorted alphabetically by name, both backend (`order_by(LibraryFolder.name)`) and frontend. The reporter — a user with a lot of nested cad / slicer directories — wanted "find folders that just got a new 3MF" without scrolling the whole alphabet. **What changed.** The folder sidebar header gains a small dropdown (**By name** / **By recent activity**) plus an asc / desc arrow button, sitting alongside the existing Collapse + Wrap toggles. Choice persists per-browser via `localStorage` (`library-folder-sort-field`, `library-folder-sort-direction`) so the preference survives reloads. **Activity semantics.** `latest_activity_at` per folder = `MAX(folder.updated_at, MAX(immediate-child file.updated_at))`. The DB had the data — `LibraryFile.updated_at` is `onupdate=func.now()` and `LibraryFolder.updated_at` the same — but `LibraryFolder.updated_at` alone only bumps on rename / move, not on file-add inside the folder, which is exactly the wrong signal for "did I just drop a new model in here." The aggregate fixes that. Recursion across subfolders is intentionally **NOT** computed — a deeply nested new 3MF bubbles its immediate parent, not every ancestor up to the root. This keeps the route a single `GROUP BY` rather than a recursive CTE, matching the existing file_counts subquery shape sibling at `library.py:746`. A future Tier 3 follow-up could add the recursive-CTE variant if anyone reports deeply-nested updates not bubbling far enough. **Backend.** New `latest_activity_at: datetime | None` field on `FolderResponse` and `FolderTreeItem` schemas. The `/folders` tree route picks up a sibling `func.max(LibraryFile.updated_at)` group-by alongside the existing file-count subquery; resolves the field per row. The `/folders/by-project/{id}` and `/folders/by-archive/{id}` routes collapse their per-row file-count subquery to fetch `count + max` in one trip (one extra column, zero extra round-trips). All 5 single-folder constructors (POST `/folders`, GET `/folders/{id}`, PUT `/folders/{id}`, POST `/folders/external`, the create flows) populate the field with `max(folder.updated_at, latest_file)` or fall back to `folder.updated_at` when there are no files, so the API surface is consistent across every route that returns a folder. **External folders.** `LibraryFile` rows are created for scanned external files too (`library.py:526`), so the MAX aggregate works on them — but the timestamp reflects when Bambuddy last *scanned / re-indexed* the file, not the filesystem mtime. For a NAS that gets new files added outside Bambuddy, the activity-sort lags until the next scan. Documented in the file-manager wiki page rather than papered over with `os.stat()` on every list call, which would stall the route on slow mounts. **Frontend.** A new recursive `sortedFolders` `useMemo` applies the comparator uniformly to top-level + every nested `children` level so sort order is consistent at every depth. Comparator falls back to name when activity timestamps tie or are both null, so an empty folder never elbows a recently-used one to a random place — empties go to the end of the activity bucket regardless of direction. Both the desktop sidebar render and the mobile selector dropdown consume `sortedFolders` so the order is identical across breakpoints. The single-folder `findFolder()` traversal and `selectedFolder` memo still operate on the unsorted `folders` because they index by ID — sort-order-independent. **Recursion safety.** The sort creates fresh object refs at every level on every memo invocation; the `FolderTreeItem` keys stay ID-based (`${folder.id}-${collapseFoldersByDefault ? 'c' : 'e'}`) so React reconciliation by ID preserves folder expansion state across sort flips. **i18n.** 3 new keys in `fileManager.*` (`folderSort`, `folderSortByName`, `folderSortByActivity`) translated in all 11 locales (de / en / es / fr / it / ja / ko / pt-BR / tr / zh-CN / zh-TW), no English fallback. Parity 5238 leaves per locale. **Tests.** 2 new backend integration cases in `test_library_api.py` (file-in-folder bubbles `latest_activity_at` to the file's timestamp, empty folder falls back to `folder.updated_at`). All 152 library + folder + trash + slice integration tests still pass; 51/51 FileManagerPage frontend tests still pass; 26/26 QueuePage tests still pass; `npm run build` clean; `ruff` clean; i18n parity green. ### Fixed +- **AMS slot with a non-Bambu (no-RFID) spool showed "Empty" instead of "?" (#2527, reporter @NeighborGeek)** — When a spool without a readable RFID tag was loaded, the AMS card showed the slot as **Empty**, while Bambu Studio correctly showed a `?` for an unidentified filament. The reporter's decisive test — swapping the unknown spool between slots and watching "Empty" follow the spool, not the slot — pinned it to slot *content*, not position. Root cause: the authoritative "a spool is physically here" signal is firmware's AMS-level **`tray_exist_bits`** bitmask (what Studio uses to draw the `?`), but Bambuddy inferred emptiness from the *per-tray* `state`/`tray_type`. On the standard AMS (P1-series here, fw 01.09.00.00), a no-RFID spool is reported with an empty `tray_type` and `state=9` — structurally identical to a truly-empty slot at the tray level — so the frontend's `getEmptySlotKind()` classified it as firmware-confirmed-empty and rendered "Empty" rather than the existing `reset` kind that renders `?` ("Spool loaded — slot not configured", #1694). Confirmed from the support bundle: `tray_exist_bits='f'` (all four slots present) with `tray_is_bbl_bits='5'` (only slots 0,2 are Bambu) — slots 1,3 were present-but-non-Bambu, exactly the ones shown Empty. **Fix.** `apply_tray_exist_bits()` — which already parses the bitmask to clear stale fields on absent slots — now also annotates each slot with an authoritative `exists` bool (gated behind a new `annotate_exists` flag so only the printer-card path sets it; the VP bridge leaves it off and the `exists` key never reaches the slicer wire format). `exists` flows through the `AMSTray` schema/serialization to the frontend, where `getEmptySlotKind()` uses it: `exists === true` + no `tray_type` → `?` (present, unconfigured), `exists === false` → Empty, and `exists` absent → the previous `state=9/10` heuristic (so AMS-HT and missing-bitmask paths are unchanged). This is why the bug never reproduced on H2D or X1C — their firmware already reports present-unknown slots with a non-9 `state`, so they fell through to `reset`/`?`; with the fix they take the same path via `exists` and are unaffected. Supersedes the closed #1838. **Tests.** Backend: 3 helper cases (present/absent slots annotated, a present-no-`tray_type` slot marked `exists=true` and left uncleared, and `annotate_exists` off keeps the wire dict clean). Frontend: 1 `AmsUnitCard` case (a `state=9` slot with `exists=true` renders `?`, while `exists=false` still renders "Empty"). Full `test_bambu_mqtt` + VP-bridge suites 384/384 and the AMS/printer/VP backend selection green; `ruff` clean; `npm run build` + ESLint clean; `AmsUnitCard`/`PrintersPage` vitest green. **Scope.** No DB migration, no new permission, no i18n change; VP slicer-facing wire format unchanged. - **Postgres→SQLite backup dropped NOT NULL / DEFAULT / FK / UNIQUE, causing NULLs after restore (#2526, reporter @bmorrison9)** — On a PostgreSQL install, `create_backup_zip()` exports a portable SQLite copy of the database so backups can move between engines. It rebuilt each table with only column name + type + primary key — the code's own comment admitted "simplified — just column names and types" — dropping `NOT NULL`, `server_default`/`DEFAULT`, foreign keys, and unique constraints. When such a backup is restored onto a SQLite install, `restore_backup()` page-copies the file straight onto the live database (`sqlite3.Connection.backup()`), so the stripped-down schema becomes the *running* database; the post-restore `init_db()` can't repair it because `create_all()` is `CREATE TABLE IF NOT EXISTS` and never alters existing tables. The reporter root-caused it precisely: `SpoolBuddyDevice.created_at` is `server_default=func.now()`, so SQLAlchemy omits the column on INSERT and relies on the DB default — but with no `DEFAULT` clause the row got a bare `NULL`, which then failed Pydantic validation (`DeviceResponse.created_at`) on the next read and 500'd. Every `server_default` column across the schema was exposed the same way, and the FK/unique loss followed from the same simplified CREATE TABLE. **Fix.** The PostgreSQL branch now builds the portable SQLite schema with `Base.metadata.create_all()` against a SQLite engine — the exact DDL a native SQLite install gets — instead of the hand-rolled loop. That emits `NOT NULL`, `DEFAULT` (`server_default=func.now()` → `DEFAULT (CURRENT_TIMESTAMP)`), foreign keys, unique constraints, and indexes, so a Postgres→SQLite restore reproduces the same effective schema a fresh SQLite install would have. The data-export insert path is unchanged, and the `#1333` OIDC-icon guard is preserved automatically — `LargeBinary` renders as `BLOB` under the real DDL — which let the now-redundant `_sqlalchemy_type_to_sqlite_type()` type-mapping helper be removed. This fixes newly-created backups; a backup taken with an older build still carries the degraded schema, so re-take backups after upgrading. **Tests.** The `#1333` type-mapping unit tests were replaced with three that inspect the *real* backup schema (`metadata.create_all` on SQLite, read back via `sqlite_master`/`PRAGMA table_info`): the OIDC `icon_data` column is `BLOB` (#1333), `spoolbuddy_devices.created_at` keeps its `CURRENT_TIMESTAMP` DEFAULT (#2526), and a NOT NULL non-PK column stays NOT NULL. Full backup/restore suite (`test_settings_api`, `test_security`, Postgres-restore-cascade, SQLite-WAL-safety, OIDC-blob-roundtrip) 136/136 green; `ruff` clean. **Scope.** Backend-only, PostgreSQL-source backups. No DB migration, no new permission, no i18n change. - **"Store on external storage" diagnostic reported an unresolvable fail on P1S/P1P (#2524, reporter @gregspatrick)** — Install-step-4's `external_storage` check hard-**failed** for a P1S even though there is no reachable UI anywhere — Bambu Studio, OrcaSlicer, Handy, or the printer (P1S has no screen) — that can turn the option on. The reporter root-caused it precisely: `has_external_storage()` returns True for the P1S (it does have a MicroSD slot), so the check proceeds to read `state.store_to_sdcard` (MQTT `home_flag` bit 11), which is stuck `False`. The toggle only renders in Studio when the printer publishes `support_save_remote_print_file_to_storage`, and current P1-series firmware (through 01.10.00.00) never does — Bambu's own storage-cache wiki lists P1 Series as "Not Supported". So the user was shown a red fail they could never clear. **Fix.** New `NO_REMOTE_STORAGE_TOGGLE_MODELS` set (P1S, P1P) + `has_remote_storage_toggle()` helper, distinct from the no-slot `NO_EXTERNAL_STORAGE_MODELS` used for A1/A1 Mini (the P1S genuinely *has* a slot — conflating the two would be wrong). When a model has a slot but no reachable toggle and `store_to_sdcard` is False, the diagnostic now emits `skip` with `params={"reason": "unsupported_model"}` instead of `fail`, and the overall result no longer escalates to "problems" for it. A P1S that somehow reports the option *on* still passes. The gate is model-scoped and default-open, so X1/P2S/H2-class printers — where the toggle is reachable and the fail is actionable — are unaffected; if a future P1 firmware surfaces the capability, drop the model from the set and the check reactivates. The frontend `DiagnosticChecklist` picks a reason-specific message variant (`external_storage.skip_unsupported_model`) when a check carries a `reason`, falling back to the plain per-status text otherwise — so instead of the misleading generic "needs a live MQTT connection" skip line, P1 users see an accurate explanation that the option can't be enabled on current firmware and archived prints may lack thumbnails/metadata until Bambu adds support. **i18n.** 1 new key translated across all 11 locales; parity green at 5580 leaves each. **Tests.** Backend: 3 diagnostic cases (P1S/P1P → skip with the reason param, overall stays "ok"; P1S with the option on still passes) + 3 helper cases in `test_printer_models.py` (P1-series false, other models/unknown/empty true). Frontend: 2 `ConnectionDiagnosticModal` cases (reason variant renders and suppresses the generic text; no-reason falls back). Full diagnostic + model suites green; `ruff` clean; `npm run build` + ESLint clean. **Scope.** No DB migration, no new permission. - **Finish photo still caught the swapped/empty plate intermittently on A1 Mini + SwapMod (#1867 follow-on, reporter @qoatzelcoat)** — The last-layer edge trigger shipped in 0.2.4.9 fixed most cases but the reporter still saw the wrong (post-swap) plate now and then — "nothing changed, just kept adding files to the queue." Root cause, confirmed from the support bundle: this A1 Mini firmware (01.08.01.00) **never emits `stg_cur=22`** — across the whole 35k-line log (24 completions) the only stages it reports are 0/2/3/4/13/14/54/77/255, so every completion falls through to the `FINISH`-state fallback. Bambu only reports `gcode_state=FINISH` *after* the user End G-code runs (the print's last object layer was laid ~2 min before FINISH), so a live grab there is guaranteed to show the SwapMod-ejected plate. The last-layer edge (`layer_num >= total_layer_num` while RUNNING) is the right window but depends on catching **one transient MQTT packet** — if the firmware coalesces or drops the final `layer_num == total` push and jumps straight to FINISH, the edge is missed and it silently reverts to the post-swap grab. That's the intermittency; queued prints run unattended so the misses accumulate. **Fix — bank a frame instead of chasing an edge.** Bambuddy now keeps a rolling "last in-print camera frame" per printer, refreshed on layer change (throttled to ~25 s, always refreshed on the final object layer) via the same snapshot path the finish photo uses — so it honours the `capture_finish_photo` setting and works for external cameras, buffered RTSP, and fresh RTSP grabs alike. Because banking is **layer-driven it freezes automatically the instant printing ends**: the End G-code (plate swap) emits no further `layer_num` increases, so the last banked frame is always the finished print before the swap. On the `FINISH`-state fallback the finish-photo path now prefers the banked frame over a live grab; the `stage_22` and `last_layer` triggers still live-grab (they fire before the swap and give cleaner parked-toolhead framing), and if no banked frame exists it degrades to the old live grab rather than sending a text-only notification. Correctness no longer depends on *which* signal the firmware emits or on catching the edge — a missed edge just means the photo is one layer-frame stale (a finished print, not an empty plate). The bank is cleared on print start so a queued job can't reuse the prior job's frame. **Tests.** 8 new cases in `test_finish_photo_moment_sync.py`: `finish_state` prefers the banked frame and skips the live grab, falls back to live when no bank exists, and `last_layer` ignores the bank; plus 5 for the banking helper — stores while printing, throttles within the interval, always refreshes on the last layer, skips when not RUNNING (the freeze), and skips during calibration sub-stages. Full finish-photo + MQTT + layer-timelapse suites 355/355 green; `ruff check` clean. **Scope.** Backend-only. No DB migration, no new permission, no i18n change. diff --git a/backend/app/api/routes/printers.py b/backend/app/api/routes/printers.py index 368b752ef..eb7ed9981 100644 --- a/backend/app/api/routes/printers.py +++ b/backend/app/api/routes/printers.py @@ -535,6 +535,7 @@ async def get_printer_status( drying_temp=tray_data.get("drying_temp"), drying_time=tray_data.get("drying_time"), state=tray_data.get("state"), + exists=tray_data.get("exists"), ) ) # Prefer humidity_raw (percentage) over humidity (index 1-5) diff --git a/backend/app/schemas/printer.py b/backend/app/schemas/printer.py index 76afd17f2..ada69d489 100644 --- a/backend/app/schemas/printer.py +++ b/backend/app/schemas/printer.py @@ -181,6 +181,10 @@ class AMSTray(BaseModel): drying_temp: int | None = None # RFID-recommended drying temp drying_time: int | None = None # RFID-recommended drying time (hours) state: int | None = None # AMS tray state: 9=empty, 10=spool present not loaded, 11=loaded + # Firmware's authoritative "spool physically present" bit (from tray_exist_bits). + # True for a non-RFID spool the firmware can't identify — the UI shows "?" rather + # than "Empty" (#2527). None when the bitmask was unavailable (→ state-based fallback). + exists: bool | None = None class AMSUnit(BaseModel): diff --git a/backend/app/services/bambu_mqtt.py b/backend/app/services/bambu_mqtt.py index f8232be90..5571134f7 100644 --- a/backend/app/services/bambu_mqtt.py +++ b/backend/app/services/bambu_mqtt.py @@ -56,6 +56,7 @@ def apply_tray_exist_bits( *, power_on_flag: bool = True, log_label: str | None = None, + annotate_exists: bool = False, ) -> int: """Wipe stale per-tray filament fields on slots whose `tray_exist_bits` bit is 0. @@ -87,6 +88,14 @@ def apply_tray_exist_bits( way). Ints are tolerated for defensive symmetry but typically not seen on the wire. ``None`` / empty / unparseable → no-op. + ``annotate_exists`` writes a per-tray ``exists`` bool (from the bitmask) on + every processed slot. This is firmware's authoritative "spool physically + present" signal — the same one BambuStudio uses to draw a ``?`` for a + non-RFID spool in an otherwise-unidentified slot. Bambuddy's AMS card keys + empty-vs-unknown off it so a non-Bambu spool shows ``?`` instead of "Empty" + (#2527). Only the internal (printer-card) caller sets this; the VP bridge + leaves it False so the ``exists`` key never reaches the slicer wire format. + Mutates ``units`` in place. Returns the number of slots cleared. """ if not tray_exist_bits_str: @@ -131,6 +140,8 @@ def apply_tray_exist_bits( continue global_bit = ams_id * 4 + tray_id slot_exists = (tray_exist_bits >> global_bit) & 1 + if annotate_exists: + tray["exists"] = bool(slot_exists) if slot_exists: continue tray["state"] = 9 @@ -2009,6 +2020,7 @@ class BambuMQTTClient: ams_data.get("tray_exist_bits"), power_on_flag=ams_data.get("power_on_flag", True), log_label=self.serial_number, + annotate_exists=True, ) self.state.raw_data["ams"] = merged_ams diff --git a/backend/tests/unit/services/test_bambu_mqtt.py b/backend/tests/unit/services/test_bambu_mqtt.py index defe58a1d..efe1c224d 100644 --- a/backend/tests/unit/services/test_bambu_mqtt.py +++ b/backend/tests/unit/services/test_bambu_mqtt.py @@ -1330,6 +1330,40 @@ class TestApplyTrayExistBitsHelper: assert cleared == 0 assert units[0]["tray"][0]["state"] == 9 + def test_annotate_exists_marks_present_and_absent(self): + """#2527: annotate_exists writes the tray_exist_bits presence bit onto + every slot so a non-RFID spool (present, no tray_type) is distinguishable + from a truly-empty slot. 0x5 = slots 0,2 present; slots 1,3 absent.""" + from backend.app.services.bambu_mqtt import apply_tray_exist_bits + + units = [{"id": 0, "tray": [{"id": i} for i in range(4)]}] + apply_tray_exist_bits(units, "5", power_on_flag=True, annotate_exists=True) + exists = [t["exists"] for t in units[0]["tray"]] + assert exists == [True, False, True, False] + + def test_annotate_exists_present_unknown_slot_not_cleared(self): + """A present slot with no tray_type (fresh non-RFID spool) keeps its + state and is marked exists=True — the UI then shows "?" not "Empty".""" + from backend.app.services.bambu_mqtt import apply_tray_exist_bits + + # 0x1 = slot 0 present. Slot 0 has no tray_type (unidentified spool). + units = [{"id": 0, "tray": [{"id": 0, "state": 9}]}] + cleared = apply_tray_exist_bits(units, "1", power_on_flag=True, annotate_exists=True) + assert cleared == 0 + assert units[0]["tray"][0]["exists"] is True + # Present slot is left untouched (only absent slots get state=9 forced). + assert units[0]["tray"][0]["state"] == 9 + + def test_annotate_exists_off_by_default_keeps_wire_clean(self): + """The VP bridge calls this without annotate_exists, so the slicer-facing + tray dict must NOT gain a non-standard `exists` key.""" + from backend.app.services.bambu_mqtt import apply_tray_exist_bits + + units = [{"id": 0, "tray": [{"id": 0, "tray_type": "PLA"}, {"id": 1}]}] + apply_tray_exist_bits(units, "1", power_on_flag=True) + assert "exists" not in units[0]["tray"][0] + assert "exists" not in units[0]["tray"][1] + class TestNozzleRackData: """Tests for nozzle rack data parsing from H2 series device.nozzle.info.""" diff --git a/frontend/src/__tests__/components/spoolbuddy/AmsUnitCard.test.tsx b/frontend/src/__tests__/components/spoolbuddy/AmsUnitCard.test.tsx index 161fae297..4ad786f3d 100644 --- a/frontend/src/__tests__/components/spoolbuddy/AmsUnitCard.test.tsx +++ b/frontend/src/__tests__/components/spoolbuddy/AmsUnitCard.test.tsx @@ -114,6 +114,25 @@ describe('AmsUnitCard', () => { expect(screen.getByText('Empty')).toBeDefined(); }); + it('shows "?" for a non-RFID spool the firmware reports as state 9 (#2527)', () => { + // A non-Bambu spool with no RFID is physically present (tray_exist_bits → + // exists=true) but some firmware (standard AMS on P1-series) reports its + // tray as state=9 with no tray_type — identical to a truly-empty slot at + // the tray level. exists is authoritative, so it must read "?" not "Empty". + const unit = makeUnit({ + tray: [ + makeTray({ id: 0, tray_type: 'PLA', remain: 80 }), + makeTray({ id: 1, tray_color: null, tray_type: '', remain: 0, state: 9, exists: true }), + makeTray({ id: 2, tray_type: 'ABS', remain: 10 }), + // exists=false with the same state=9 is a genuinely empty slot. + makeTray({ id: 3, tray_color: null, tray_type: '', remain: 0, state: 9, exists: false }), + ], + }); + render(); + expect(screen.getByText('?')).toBeDefined(); + expect(screen.getByText('Empty')).toBeDefined(); + }); + it('renders fill level bars for slots with filament', () => { const { container } = render( diff --git a/frontend/src/api/client.ts b/frontend/src/api/client.ts index 6cf4c0782..a2ddf711e 100644 --- a/frontend/src/api/client.ts +++ b/frontend/src/api/client.ts @@ -365,6 +365,7 @@ export interface AMSTray { drying_temp: number | null; // RFID-recommended drying temp drying_time: number | null; // RFID-recommended drying time (hours) state: number | null; // AMS tray state: 9=empty, 10=spool present not loaded, 11=loaded + exists?: boolean | null; // Firmware tray_exist_bits: spool physically present (non-RFID → "?" not "Empty", #2527) } export interface AMSUnit { diff --git a/frontend/src/components/spoolbuddy/AmsUnitCard.tsx b/frontend/src/components/spoolbuddy/AmsUnitCard.tsx index fa0e1fba2..fc1431945 100644 --- a/frontend/src/components/spoolbuddy/AmsUnitCard.tsx +++ b/frontend/src/components/spoolbuddy/AmsUnitCard.tsx @@ -10,12 +10,16 @@ function isTrayEmpty(tray: AMSTray): boolean { return !tray.tray_type || tray.tray_type === ''; } -// Mirror of PrintersPage.getEmptySlotKind (#1694): 'physical' when firmware -// confirms no spool (state 9/10), 'reset' when tray_type is absent but the -// firmware hasn't confirmed empty (= spool loaded, slot just unconfigured). +// Mirror of PrintersPage.getEmptySlotKind (#1694, #2527): 'physical' when +// firmware confirms no spool, 'reset' when a spool is present but has no +// tray_type (= loaded, slot just unconfigured — e.g. a non-RFID spool). +// tray_exist_bits (exists) is authoritative when present; otherwise fall back +// to the state=9/10 heuristic. function getEmptySlotKind(tray: AMSTray): 'physical' | 'reset' | null { if (tray.tray_type) return null; - const state = (tray as { state?: number | null }).state ?? null; + if (tray.exists === true) return 'reset'; + if (tray.exists === false) return 'physical'; + const state = tray.state ?? null; return state === 9 || state === 10 ? 'physical' : 'reset'; } diff --git a/frontend/src/pages/PrintersPage.tsx b/frontend/src/pages/PrintersPage.tsx index 8f3cdd166..237f5942a 100644 --- a/frontend/src/pages/PrintersPage.tsx +++ b/frontend/src/pages/PrintersPage.tsx @@ -863,8 +863,15 @@ function TemperatureIndicator({ temp, goodThreshold = 28, fairThreshold = 35, on * * Returns null when the slot is loaded (tray_type is present). */ -function getEmptySlotKind(tray: { tray_type?: string | null; state?: number | null } | null | undefined): 'physical' | 'reset' | null { +function getEmptySlotKind(tray: { tray_type?: string | null; state?: number | null; exists?: boolean | null } | null | undefined): 'physical' | 'reset' | null { if (tray?.tray_type) return null; + // tray_exist_bits is firmware's authoritative presence signal: a non-RFID + // spool the firmware can't identify is physically present (exists === true) + // but carries no tray_type, so it must read as "?" (loaded, unconfigured), + // never "Empty" (#2527). BambuStudio draws it the same way. Only fall back to + // the state=9/10 heuristic when the bitmask was unavailable (exists == null). + if (tray?.exists === true) return 'reset'; + if (tray?.exists === false) return 'physical'; return (tray?.state === 9 || tray?.state === 10) ? 'physical' : 'reset'; } diff --git a/static/assets/index-CJ6VzpV2.js b/static/assets/index-CWda6lvk.js similarity index 99% rename from static/assets/index-CJ6VzpV2.js rename to static/assets/index-CWda6lvk.js index 0bb3ef4e8..57bae1532 100644 --- a/static/assets/index-CJ6VzpV2.js +++ b/static/assets/index-CWda6lvk.js @@ -8527,7 +8527,7 @@ void main() { border-l-[6px] border-l-transparent border-r-[6px] border-r-transparent ${c===`top`?`top-full border-t-[6px] border-t-bambu-dark-tertiary`:`bottom-full border-b-[6px] border-b-bambu-dark-tertiary`} - `})]})]})}function Pke({slots:e,filamentInfo:t}){let{t:n}=W(),r=e.filter(e=>e.id>=2),i=Array.from({length:6},(e,t)=>r.find(e=>e.id===16+t)??{id:-(t+1),nozzle_type:``,nozzle_diameter:``,wear:null,stat:null,max_temp:0,serial_number:``,filament_color:``,filament_id:``,filament_type:``});return(0,K.jsxs)(`div`,{className:`text-center px-2.5 py-1.5 bg-bambu-dark rounded-lg flex-[2_1_190px] flex flex-col justify-center`,children:[(0,K.jsx)(`p`,{className:`text-[9px] text-bambu-gray mb-1`,children:n(`printers.nozzleRack`)}),(0,K.jsx)(`div`,{className:`flex gap-[3px] justify-center`,children:i.map((e,n)=>{let r=!e.nozzle_diameter&&!e.nozzle_type,i=r?null:rf(e.filament_color),a=i?af(e.filament_color):!1;return(0,K.jsx)(gW,{slot:e,index:n,filamentName:e.filament_id?t?.[e.filament_id]?.name:void 0,children:(0,K.jsx)(`div`,{className:`w-7 h-7 rounded flex items-center justify-center cursor-default transition-colors border-b-2 ${r?`bg-bambu-dark-tertiary/20 border-bambu-dark-tertiary/20`:`bg-bambu-dark-tertiary/40 border-bambu-dark-tertiary/40`}`,style:i?{backgroundColor:i}:void 0,children:(0,K.jsx)(`span`,{className:`text-[10px] font-semibold ${r?`text-bambu-gray/30`:a?`text-black/80`:`text-white`}`,style:i&&!a?{textShadow:`0 1px 3px rgba(0,0,0,0.9)`}:void 0,children:r?`—`:e.nozzle_diameter||`?`})})},e.id>=0?e.id:`empty-${n}`)})})]})}function Fke({className:e}){return(0,K.jsx)(`svg`,{className:e,viewBox:`0 0 36 54`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,children:(0,K.jsx)(`path`,{d:`M17.8131 0.00538C18.4463 -0.15091 20.3648 3.14642 20.8264 3.84781C25.4187 10.816 35.3089 26.9368 35.9383 34.8694C37.4182 53.5822 11.882 61.3357 2.53721 45.3789C-1.73471 38.0791 0.016 32.2049 3.178 25.0232C6.99221 16.3662 12.6411 7.90372 17.8131 0.00538ZM18.3738 7.24807L17.5881 7.48441C14.4452 12.9431 10.917 18.2341 8.19369 23.9368C4.6808 31.29 1.18317 38.5479 7.69403 45.5657C17.3058 55.9228 34.9847 46.8808 31.4604 32.8681C29.2558 24.0969 22.4207 15.2913 18.3776 7.24807H18.3738Z`,fill:`#C3C2C1`})})}function Ike({className:e}){return(0,K.jsxs)(`svg`,{className:e,viewBox:`0 0 35 53`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,children:[(0,K.jsx)(`path`,{d:`M17.3165 0.0038C17.932 -0.14959 19.7971 3.08645 20.2458 3.77481C24.7103 10.6135 34.3251 26.4346 34.937 34.2198C36.3757 52.5848 11.5505 60.1942 2.46584 44.534C-1.68714 37.3735 0.0148 31.6085 3.08879 24.5603C6.79681 16.0605 12.2884 7.75907 17.3165 0.0038ZM17.8615 7.11561L17.0977 7.34755C14.0423 12.7048 10.6124 17.8974 7.96483 23.4941C4.54975 30.7107 1.14949 37.8337 7.47908 44.721C16.8233 54.8856 34.01 46.0117 30.5838 32.2595C28.4405 23.6512 21.7957 15.0093 17.8652 7.11561H17.8615Z`,fill:`#C3C2C1`}),(0,K.jsx)(`path`,{d:`M5.03547 30.112C9.64453 30.4936 11.632 35.7985 16.4154 35.791C19.6339 35.7873 20.2161 33.2283 22.3853 31.6197C31.6776 24.7286 33.5835 37.4894 27.9881 44.4254C18.1878 56.5653 -1.16063 44.6013 5.03917 30.1158L5.03547 30.112Z`,fill:`#1F8FEB`})]})}function Lke({className:e}){return(0,K.jsxs)(`svg`,{className:e,viewBox:`0 0 36 54`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,children:[(0,K.jsx)(`path`,{d:`M17.9625 4.48059L4.77216 26.3154L2.08228 40.2175L10.0224 50.8414H23.1594L33.3246 42.1693V30.2455L17.9625 4.48059Z`,fill:`#1F8FEB`}),(0,K.jsx)(`path`,{d:`M17.7948 0.00538C18.4273 -0.15091 20.3438 3.14642 20.8048 3.84781C25.3921 10.816 35.2715 26.9368 35.9001 34.8694C37.3784 53.5822 11.8702 61.3357 2.53562 45.3789C-1.73163 38.0829 0.0134 32.2087 3.1757 25.027C6.98574 16.3662 12.6284 7.90372 17.7948 0.00538ZM18.3549 7.24807L17.57 7.48441C14.4306 12.9431 10.9063 18.2341 8.1859 23.9368C4.67686 31.29 1.18305 38.5479 7.68679 45.5657C17.2881 55.9228 34.9476 46.8808 31.4271 32.8681C29.2249 24.0969 22.3974 15.2913 18.3587 7.24807H18.3549Z`,fill:`#C3C2C1`})]})}function Rke({className:e}){return(0,K.jsxs)(`svg`,{className:e,viewBox:`0 0 12 20`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,children:[(0,K.jsx)(`path`,{d:`M6 0.5C4.6 0.5 3.5 1.6 3.5 3V12.1C2.6 12.8 2 13.9 2 15C2 17.2 3.8 19 6 19C8.2 19 10 17.2 10 15C10 13.9 9.4 12.8 8.5 12.1V3C8.5 1.6 7.4 0.5 6 0.5Z`,stroke:`#C3C2C1`,strokeWidth:`1`,fill:`none`}),(0,K.jsx)(`circle`,{cx:`6`,cy:`15`,r:`2.5`,stroke:`#C3C2C1`,strokeWidth:`1`,fill:`none`})]})}function zke({className:e}){return(0,K.jsxs)(`svg`,{className:e,viewBox:`0 0 12 20`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,children:[(0,K.jsx)(`rect`,{x:`4.5`,y:`8`,width:`3`,height:`4.5`,fill:`#d4a017`,rx:`0.5`}),(0,K.jsx)(`circle`,{cx:`6`,cy:`15`,r:`2`,fill:`#d4a017`}),(0,K.jsx)(`path`,{d:`M6 0.5C4.6 0.5 3.5 1.6 3.5 3V12.1C2.6 12.8 2 13.9 2 15C2 17.2 3.8 19 6 19C8.2 19 10 17.2 10 15C10 13.9 9.4 12.8 8.5 12.1V3C8.5 1.6 7.4 0.5 6 0.5Z`,stroke:`#C3C2C1`,strokeWidth:`1`,fill:`none`})]})}function Bke({className:e}){return(0,K.jsxs)(`svg`,{className:e,viewBox:`0 0 12 20`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,children:[(0,K.jsx)(`rect`,{x:`4.5`,y:`3`,width:`3`,height:`9.5`,fill:`#c62828`,rx:`0.5`}),(0,K.jsx)(`circle`,{cx:`6`,cy:`15`,r:`2`,fill:`#c62828`}),(0,K.jsx)(`path`,{d:`M6 0.5C4.6 0.5 3.5 1.6 3.5 3V12.1C2.6 12.8 2 13.9 2 15C2 17.2 3.8 19 6 19C8.2 19 10 17.2 10 15C10 13.9 9.4 12.8 8.5 12.1V3C8.5 1.6 7.4 0.5 6 0.5Z`,stroke:`#C3C2C1`,strokeWidth:`1`,fill:`none`})]})}function Vke({className:e}){return(0,K.jsxs)(`svg`,{className:e,viewBox:`0 0 24 24`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,stroke:`currentColor`,strokeWidth:`1.5`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,K.jsx)(`rect`,{x:`9.2`,y:`3.4`,width:`5.6`,height:`8.1`}),(0,K.jsx)(`rect`,{x:`6`,y:`11.5`,width:`12.1`,height:`3.7`}),(0,K.jsx)(`path`,{d:`M 7.3 15.2 L 12.1 19.6 L 16.7 15.2`})]})}function _W({className:e,color:t,isHeating:n}){let r={"text-orange-400":`#fb923c`,"text-blue-400":`#60a5fa`,"text-green-400":`#4ade80`}[t]||`#888`,i=n?{filter:`drop-shadow(0 0 4px ${r}) drop-shadow(0 0 8px ${r})`}:{};return n?(0,K.jsxs)(`svg`,{className:e,style:i,viewBox:`0 0 12 20`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,children:[(0,K.jsx)(`rect`,{x:`4.5`,y:`3`,width:`3`,height:`9.5`,fill:r,rx:`0.5`}),(0,K.jsx)(`circle`,{cx:`6`,cy:`15`,r:`2`,fill:r}),(0,K.jsx)(`path`,{d:`M6 0.5C4.6 0.5 3.5 1.6 3.5 3V12.1C2.6 12.8 2 13.9 2 15C2 17.2 3.8 19 6 19C8.2 19 10 17.2 10 15C10 13.9 9.4 12.8 8.5 12.1V3C8.5 1.6 7.4 0.5 6 0.5Z`,stroke:r,strokeWidth:`1`,fill:`none`})]}):(0,K.jsxs)(`svg`,{className:e,viewBox:`0 0 12 20`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,children:[(0,K.jsx)(`path`,{d:`M6 0.5C4.6 0.5 3.5 1.6 3.5 3V12.1C2.6 12.8 2 13.9 2 15C2 17.2 3.8 19 6 19C8.2 19 10 17.2 10 15C10 13.9 9.4 12.8 8.5 12.1V3C8.5 1.6 7.4 0.5 6 0.5Z`,stroke:r,strokeWidth:`1`,fill:`none`}),(0,K.jsx)(`circle`,{cx:`6`,cy:`15`,r:`2.5`,stroke:r,strokeWidth:`1`,fill:`none`})]})}function Hke({state:e,onClick:t}){let{t:n}=W(),r=e!==null,i=`flex items-center justify-center w-[18px] h-[18px] rounded text-[10px] transition-colors `,a;return e===!0?(i+=r?`bg-blue-100 dark:bg-blue-500/20 text-blue-700 dark:text-blue-400 hover:bg-blue-500/30 cursor-pointer`:`bg-blue-100 dark:bg-blue-500/20 text-blue-700 dark:text-blue-400 cursor-default`,a=n(`printers.amsBackup.titleOn`)):e===!1?(i+=r?`bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark/80 cursor-pointer`:`bg-bambu-dark text-bambu-gray cursor-default`,a=n(`printers.amsBackup.titleOff`)):(i+=`bg-bambu-dark text-bambu-gray/50 cursor-default`,a=n(`printers.amsBackup.titleUnknown`)),(0,K.jsx)(`button`,{type:`button`,disabled:!r,onClick:()=>r&&t(),className:i,title:a,"aria-label":a,children:r?(0,K.jsx)(Al,{className:`w-3 h-3`}):(0,K.jsx)(`span`,{children:`?`})})}function vW({humidity:e,goodThreshold:t=40,fairThreshold:n=60,onClick:r,compact:i}){let a=typeof e==`string`?parseInt(e,10):e,o=typeof t==`number`?t:40,s=typeof n==`number`?n:60,c,l;isNaN(a)?(c=`#C3C2C1`,l=`Unknown`):a<=o?(c=`#22a352`,l=`Good`):a<=s?(c=`#d4a017`,l=`Fair`):(c=`#c62828`,l=`Bad`);let u;return u=isNaN(a)||a<=o?Fke:a<=s?Ike:Lke,(0,K.jsxs)(`button`,{type:`button`,onClick:r,className:`flex items-center gap-1 ${r?`cursor-pointer hover:opacity-80 transition-opacity`:``}`,title:`Humidity: ${a}% - ${l}${r?` (click for history)`:``}`,children:[(0,K.jsx)(u,{className:i?`w-2.5 h-3`:`w-3 h-4`}),(0,K.jsxs)(`span`,{className:`font-medium tabular-nums ${i?`text-[10px]`:`text-xs`}`,style:{color:c},children:[a,`%`]})]})}function yW({temp:e,goodThreshold:t=28,fairThreshold:n=35,onClick:r,compact:i}){let a=typeof t==`number`?t:28,o=typeof n==`number`?n:35,s,c,l;return e<=a?(s=`#22a352`,c=`Good`,l=Rke):e<=o?(s=`#d4a017`,c=`Fair`,l=zke):(s=`#c62828`,c=`Bad`,l=Bke),(0,K.jsxs)(`button`,{type:`button`,onClick:r,className:`flex items-center gap-1 ${r?`cursor-pointer hover:opacity-80 transition-opacity`:``}`,title:`Temperature: ${e}°C - ${c}${r?` (click for history)`:``}`,children:[(0,K.jsx)(l,{className:i?`w-2.5 h-3`:`w-3 h-4`}),(0,K.jsxs)(`span`,{className:`tabular-nums text-right ${i?`text-[10px] w-8`:`w-12`}`,style:{color:s},children:[e,`°C`]})]})}function bW(e){return e?.tray_type?null:e?.state===9||e?.state===10?`physical`:`reset`}function Uke({url:e,printName:t,className:n=`w-20 h-20`,radiusClass:r=`rounded-lg`}){let{t:i}=W(),[a,o]=(0,y.useState)(!1),[s,c]=(0,y.useState)(!1),[l,u]=(0,y.useState)(!1),d=(0,y.useMemo)(()=>e?ed(`${e}${e.includes(`?`)?`&`:`?`}v=${encodeURIComponent(t||Date.now().toString())}`):null,[e,t]);return(0,y.useEffect)(()=>{o(!1),c(!1)},[d]),(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`div`,{className:`${n} flex-shrink-0 ${r} overflow-hidden bg-bambu-dark-tertiary flex items-center justify-center ${d&&a?`cursor-pointer`:``}`,onClick:()=>d&&a&&u(!0),children:d&&!s?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`img`,{src:d,alt:i(`printers.printPreview`),className:`w-full h-full object-cover ${a?`block`:`hidden`}`,onLoad:()=>o(!0),onError:()=>c(!0)}),!a&&(0,K.jsx)(Uo,{className:`w-8 h-8 text-bambu-gray`})]}):(0,K.jsx)(Uo,{className:`w-8 h-8 text-bambu-gray`})}),l&&d&&(0,K.jsx)(`div`,{className:`fixed inset-0 bg-black/80 flex items-center justify-center z-50 p-8`,onClick:()=>u(!1),children:(0,K.jsxs)(`div`,{className:`relative max-w-2xl max-h-full`,children:[(0,K.jsx)(`img`,{src:d,alt:i(`printers.printPreview`),className:`max-w-full max-h-[80vh] rounded-lg shadow-2xl`}),t&&(0,K.jsx)(`p`,{className:`text-white text-center mt-4 text-lg`,children:t})]})})]})}function Wke({printers:e}){let{t}=W(),n=to(),[r,i]=(0,y.useState)(0);(0,y.useEffect)(()=>{let e=!1,t=n.getQueryCache().subscribe(()=>{e||(e=!0,requestAnimationFrame(()=>{i(e=>e+1),e=!1}))});return()=>t()},[n]);let{counts:a,nextFinish:o}=(0,y.useMemo)(()=>{let t=0,r=0,i=0,a=0,o=0,s=0,c=0,l=null,u=null,d=0;return e?.forEach(e=>{let f=n.getQueryData([`printerStatus`,e.id]);if(f===void 0)s++;else if(!f.connected)o++;else{let n=f.hms_errors?Yp(f.hms_errors).length:0;switch(n>0&&c++,f.state){case`RUNNING`:t++,f.remaining_time!=null&&f.remaining_time>0&&(u===null||f.remaining_time0||i++;break;default:a++;break}}}),{counts:{printing:t,paused:r,finished:i,idle:a,offline:o,loading:s,error:c,total:e?.length||0},nextFinish:l&&u?{name:l,remainingMin:u,progress:d}:null}},[e,n,r]);return e?.length?(0,K.jsxs)(`div`,{className:`mt-1 flex flex-wrap items-center gap-4 gap-y-2 text-bambu-gray`,children:[[{count:a.printing,dot:`bg-bambu-green animate-pulse`,label:t(`printers.status.printing`).toLowerCase()},{count:a.paused,dot:`bg-status-warning`,label:t(`printers.status.paused`,`paused`).toLowerCase()},{count:a.finished,dot:`bg-blue-400`,label:t(`printers.status.finished`,`finished`).toLowerCase()},{count:a.idle,dot:a.idle>0?`bg-bambu-green`:`bg-gray-500`,label:t(`printers.status.available`).toLowerCase()},{count:a.error,dot:`bg-status-error`,label:t(`printers.status.problem`).toLowerCase()},{count:a.offline,dot:`bg-gray-400`,label:t(`printers.status.offline`).toLowerCase()}].map(({count:e,dot:t,label:n})=>e>0&&(0,K.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,K.jsx)(`div`,{className:`w-2 h-2 rounded-full ${t}`}),(0,K.jsxs)(`span`,{className:`text-bambu-gray`,children:[(0,K.jsx)(`span`,{className:`text-white font-medium`,children:e}),` `,n]})]},n)),o&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`div`,{className:`w-px h-4 bg-bambu-dark-tertiary`}),(0,K.jsxs)(`div`,{className:`flex flex-col gap-1 sm:flex-row sm:items-center sm:gap-2`,children:[(0,K.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,K.jsxs)(`span`,{className:`text-bambu-green font-medium`,children:[t(`printers.nextAvailable`),`:`]}),(0,K.jsx)(`span`,{className:`text-white font-medium`,children:o.name})]}),(0,K.jsxs)(`div`,{className:`flex items-center gap-2 w-full sm:w-auto`,children:[(0,K.jsx)(`div`,{className:`w-full sm:w-16 bg-bambu-dark-tertiary rounded-full h-1.5`,children:(0,K.jsx)(`div`,{className:`bg-bambu-green h-1.5 rounded-full transition-all`,style:{width:`${o.progress}%`}})}),(0,K.jsxs)(`span`,{className:`text-white font-medium`,children:[Math.round(o.progress),`%`]}),(0,K.jsxs)(`span`,{className:`text-bambu-gray`,children:[`(`,jf(o.remainingMin*60),`)`]})]})]})]})]}):null}function xW({value:e,options:t,onChange:n,fullWidth:r=!1}){let[i,a]=(0,y.useState)(!1),o=t.find(t=>t.value===e)??t[0];return(0,K.jsxs)(`div`,{className:`relative ${r?`w-full min-w-0`:``}`,children:[(0,K.jsxs)(`button`,{type:`button`,onClick:()=>a(e=>!e),className:`h-8 px-2 rounded-lg border bg-bambu-dark border-bambu-dark-tertiary text-white text-sm font-medium transition-colors hover:bg-bambu-dark-tertiary focus:outline-none focus:border-bambu-green flex items-center justify-between gap-2 ${r?`w-full`:`min-w-28`}`,children:[(0,K.jsx)(`span`,{className:`truncate`,children:o?.label}),(0,K.jsx)(ns,{className:`w-4 h-4 text-bambu-gray transition-transform ${i?`rotate-180`:``}`})]}),i&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`div`,{className:`fixed inset-0 z-10`,onClick:()=>a(!1)}),(0,K.jsx)(`div`,{className:`absolute left-0 top-full z-20 mt-1 min-w-full rounded-lg border border-bambu-dark-tertiary bg-bambu-dark-secondary py-1 shadow-xl`,children:t.map(t=>(0,K.jsx)(`button`,{type:`button`,onClick:()=>{n(t.value),a(!1)},className:`w-full px-3 py-2 text-left text-sm transition-colors hover:bg-bambu-dark-tertiary ${t.value===e?`text-bambu-green`:`text-white`}`,children:t.label},t.value))})]})]})}function SW({label:e,icon:t,children:n}){let[r,i]=(0,y.useState)(!1);return(0,K.jsxs)(`div`,{className:`relative`,children:[(0,K.jsx)(`button`,{type:`button`,onClick:()=>i(e=>!e),className:`h-8 w-8 rounded-lg border bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary transition-colors flex items-center justify-center`,"aria-label":e,title:e,children:t}),r&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`div`,{className:`fixed inset-0 z-10`,onClick:()=>i(!1)}),(0,K.jsx)(`div`,{className:`absolute right-0 top-full z-20 mt-1 min-w-40 rounded-lg border border-bambu-dark-tertiary bg-bambu-dark-secondary p-2 shadow-xl`,children:n})]})]})}function CW({title:e,options:t=[],unit:n,customMin:r,customMax:i,customStep:a=1,widthClass:o=`w-[240px]`,popoverWidth:s=240,popoverHeight:c=280,isPending:l,onClose:u,onSubmit:d,children:f}){let p=(0,y.useRef)(null),[m,h]=(0,y.useState)(null),[g,_]=(0,y.useState)(``);(0,y.useLayoutEffect)(()=>{let e=p.current?.parentElement;if(!e)return;let t=()=>{h(Bp({triggerRect:e.getBoundingClientRect(),popoverWidth:s,estimatedHeight:c,horizontalAlign:`center`}))};return t(),window.addEventListener(`resize`,t),window.addEventListener(`scroll`,t,!0),()=>{window.removeEventListener(`resize`,t),window.removeEventListener(`scroll`,t,!0)}},[s,c]);let v=n!==void 0,b=()=>{let e=Number(g);Number.isFinite(e)&&d?.(Math.round(Math.min(i??e,Math.max(r??e,e))))};return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`span`,{ref:p,className:`hidden`,"aria-hidden":`true`}),(0,Rp.createPortal)((0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`div`,{className:`fixed inset-0 z-[1000]`,onClick:u}),(0,K.jsxs)(`div`,{className:`fixed z-[1001] flex ${o} flex-col overflow-hidden rounded-xl border border-bambu-dark-tertiary bg-bambu-dark-secondary shadow-2xl`,style:{top:m?.top??-9999,left:m?.left??-9999,visibility:m?`visible`:`hidden`},onClick:e=>e.stopPropagation(),children:[(0,K.jsx)(`div`,{className:`shrink-0 px-3 py-2.5 text-center text-sm font-medium text-white`,children:e}),(0,K.jsx)(`div`,{className:`shrink-0 h-px bg-bambu-dark-tertiary`}),t.length>0&&(0,K.jsx)(`div`,{className:`px-3 py-2.5`,children:(0,K.jsx)(`div`,{className:`grid grid-cols-2 gap-1.5`,children:t.map(e=>(0,K.jsx)(`button`,{type:`button`,disabled:l,onClick:()=>d?.(e.value),className:`h-8 rounded-lg border border-bambu-dark-tertiary bg-bambu-dark px-2 text-xs font-medium text-white transition-colors hover:bg-bambu-dark-tertiary disabled:cursor-not-allowed disabled:opacity-50`,children:e.label},`${e.label}-${e.value}`))})}),f,v&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`div`,{className:`shrink-0 h-px bg-bambu-dark-tertiary`}),(0,K.jsxs)(`form`,{className:`flex gap-1.5 px-3 pt-2.5 pb-3`,onSubmit:e=>{e.preventDefault(),b()},children:[(0,K.jsx)(`input`,{type:`number`,min:r,max:i,step:a,value:g,onChange:e=>_(e.target.value),placeholder:`Custom`,className:`h-8 min-w-0 flex-1 rounded-lg border border-bambu-dark-tertiary bg-bambu-dark px-2 text-xs text-white placeholder:text-bambu-gray/60 focus:border-bambu-green focus:outline-none`}),(0,K.jsx)(`button`,{type:`submit`,disabled:l||g.trim()===``,className:`h-8 rounded-lg border border-bambu-dark-tertiary bg-bambu-dark px-2 text-xs font-medium text-white transition-colors hover:bg-bambu-dark-tertiary disabled:cursor-not-allowed disabled:opacity-50`,children:`Set`})]})]})]})]}),document.body)]})}var Gke=Kp(Vp,`C`);function wW({label:e,current:t,target:n,isActive:r,isPending:i,onSubmit:a,options:o=Gke}){let[s,c]=(0,y.useState)(``),l=()=>{let e=Number(s);Number.isFinite(e)&&a(Math.min(320,Math.max(0,Math.round(e))))};return(0,K.jsxs)(`div`,{className:`rounded-lg border p-2 ${r?`border-amber-500/60 dark:border-amber-400/60 bg-amber-50 dark:bg-amber-400/10`:`border-bambu-dark-tertiary bg-bambu-dark`}`,children:[(0,K.jsxs)(`div`,{className:`mb-1.5 flex items-center justify-between gap-2`,children:[(0,K.jsx)(`span`,{className:`text-xs font-medium ${r?`text-amber-700 dark:text-amber-300`:`text-white`}`,children:e}),(0,K.jsxs)(`span`,{className:`text-[10px] text-bambu-gray`,children:[Math.round(t??0),`°C`,n===void 0?``:` / ${Math.round(n)}°`]})]}),(0,K.jsx)(`div`,{className:`grid grid-cols-2 gap-1`,children:o.map(t=>(0,K.jsx)(`button`,{type:`button`,disabled:i,onClick:()=>a(t.value),className:`h-7 rounded-md border border-bambu-dark-tertiary bg-bambu-dark-secondary px-1.5 text-[11px] font-medium text-white transition-colors hover:bg-bambu-dark-tertiary disabled:cursor-not-allowed disabled:opacity-50`,children:t.label},`${e}-${t.value}`))}),(0,K.jsxs)(`form`,{className:`mt-1.5 flex gap-1`,onSubmit:e=>{e.preventDefault(),l()},children:[(0,K.jsx)(`input`,{type:`number`,min:0,max:320,step:1,value:s,onChange:e=>c(e.target.value),placeholder:`Custom`,className:`h-7 min-w-0 flex-1 rounded-md border border-bambu-dark-tertiary bg-bambu-dark-secondary px-1.5 text-[11px] text-white placeholder:text-bambu-gray/60 focus:border-bambu-green focus:outline-none`}),(0,K.jsx)(`button`,{type:`submit`,disabled:i||s.trim()===``,className:`h-7 rounded-md border border-bambu-dark-tertiary bg-bambu-dark-secondary px-2 text-[11px] font-medium text-white transition-colors hover:bg-bambu-dark-tertiary disabled:cursor-not-allowed disabled:opacity-50`,children:`Set`})]})]})}var Kke=[`error`,`printing`,`paused`,`finished`,`idle`,`offline`],TW={error:{labelKey:`printers.status.problem`,dot:`bg-status-error`},printing:{labelKey:`printers.status.printing`,dot:`bg-bambu-green animate-pulse`},paused:{labelKey:`printers.status.paused`,dot:`bg-status-warning`},finished:{labelKey:`printers.status.finished`,dot:`bg-blue-400`},idle:{labelKey:`printers.status.idle`,dot:`bg-bambu-green`},offline:{labelKey:`printers.status.offline`,dot:`bg-gray-400`}};function EW(e){if(!e?.connected)return`offline`;if((e.hms_errors?Yp(e.hms_errors):[]).length>0)return`error`;switch(e.state){case`RUNNING`:return`printing`;case`PAUSE`:return`paused`;case`FINISH`:return`finished`;case`FAILED`:return`finished`;default:return`idle`}}function qke(e,t){if(t)return t;switch(e){case`RUNNING`:return`Printing`;case`PAUSE`:return`Paused`;case`FINISH`:return`Finished`;case`FAILED`:return`Failed`;case`IDLE`:return`Idle`;default:return e?e.charAt(0)+e.slice(1).toLowerCase():`Idle`}}var Jke=new Set([`X1C`,`X1`,`X1E`,`X2D`,`P1S`,`P2S`,`H2D`,`H2D Pro`,`H2C`,`H2S`]);function DW(e){return e?{O1D:`H2D`,O1E:`H2D Pro`,O2D:`H2D Pro`,O1C:`H2C`,O1C2:`H2C`,O1S:`H2S`,"BL-P001":`X1C`,"BL-P002":`X1`,"BL-P003":`X1E`,N6:`X2D`,N9:`A2L`,C11:`P1S`,C12:`P1P`,C13:`P2S`,N2S:`A1`,N1:`A1 Mini`,X1C:`X1C`,X1:`X1`,X1E:`X1E`,X2D:`X2D`,P1S:`P1S`,P1P:`P1P`,P2S:`P2S`,A1:`A1`,"A1 Mini":`A1 Mini`,A2L:`A2L`,H2D:`H2D`,"H2D Pro":`H2D Pro`,H2C:`H2C`,H2S:`H2S`}[e]||e:``}function OW({ams:e,printerId:t,label:n,amsLabels:r,canEdit:i,onSaved:a,children:o}){let{t:s}=W(),[c,l]=(0,y.useState)(!1),[u,d]=(0,y.useState)(`top`),[f,p]=(0,y.useState)(``),[m,h]=(0,y.useState)(!1),[g,_]=(0,y.useState)(null),[v,b]=(0,y.useState)(!1),x=(0,y.useRef)(null),S=(0,y.useRef)(null),C=(0,y.useRef)(null);(0,y.useEffect)(()=>{c&&(p(r?.[e.id]??``),_(null),requestAnimationFrame(()=>{if(x.current&&S.current){let e=x.current.getBoundingClientRect(),t=e.top-56,n=window.innerHeight-e.bottom;d(tt?`bottom`:`top`)}}))},[c,r,e.id]);let w=()=>{C.current&&clearTimeout(C.current),C.current=setTimeout(()=>l(!0),80)},T=()=>{C.current&&clearTimeout(C.current),v||(C.current=setTimeout(()=>l(!1),200))};(0,y.useEffect)(()=>()=>{C.current&&clearTimeout(C.current)},[]);let E=async()=>{if(i){h(!0),_(null);try{let n=f.trim();n?await Q.saveAmsLabel(t,e.id,n,e.serial_number):await Q.deleteAmsLabel(t,e.id,e.serial_number),a(),l(!1)}catch(e){_(e instanceof Error?e.message:String(e))}finally{h(!1)}}};return(0,K.jsxs)(`div`,{ref:x,className:`relative inline-block`,onMouseEnter:w,onMouseLeave:T,children:[o,c&&(0,K.jsx)(`div`,{ref:S,className:` + `})]})]})}function Pke({slots:e,filamentInfo:t}){let{t:n}=W(),r=e.filter(e=>e.id>=2),i=Array.from({length:6},(e,t)=>r.find(e=>e.id===16+t)??{id:-(t+1),nozzle_type:``,nozzle_diameter:``,wear:null,stat:null,max_temp:0,serial_number:``,filament_color:``,filament_id:``,filament_type:``});return(0,K.jsxs)(`div`,{className:`text-center px-2.5 py-1.5 bg-bambu-dark rounded-lg flex-[2_1_190px] flex flex-col justify-center`,children:[(0,K.jsx)(`p`,{className:`text-[9px] text-bambu-gray mb-1`,children:n(`printers.nozzleRack`)}),(0,K.jsx)(`div`,{className:`flex gap-[3px] justify-center`,children:i.map((e,n)=>{let r=!e.nozzle_diameter&&!e.nozzle_type,i=r?null:rf(e.filament_color),a=i?af(e.filament_color):!1;return(0,K.jsx)(gW,{slot:e,index:n,filamentName:e.filament_id?t?.[e.filament_id]?.name:void 0,children:(0,K.jsx)(`div`,{className:`w-7 h-7 rounded flex items-center justify-center cursor-default transition-colors border-b-2 ${r?`bg-bambu-dark-tertiary/20 border-bambu-dark-tertiary/20`:`bg-bambu-dark-tertiary/40 border-bambu-dark-tertiary/40`}`,style:i?{backgroundColor:i}:void 0,children:(0,K.jsx)(`span`,{className:`text-[10px] font-semibold ${r?`text-bambu-gray/30`:a?`text-black/80`:`text-white`}`,style:i&&!a?{textShadow:`0 1px 3px rgba(0,0,0,0.9)`}:void 0,children:r?`—`:e.nozzle_diameter||`?`})})},e.id>=0?e.id:`empty-${n}`)})})]})}function Fke({className:e}){return(0,K.jsx)(`svg`,{className:e,viewBox:`0 0 36 54`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,children:(0,K.jsx)(`path`,{d:`M17.8131 0.00538C18.4463 -0.15091 20.3648 3.14642 20.8264 3.84781C25.4187 10.816 35.3089 26.9368 35.9383 34.8694C37.4182 53.5822 11.882 61.3357 2.53721 45.3789C-1.73471 38.0791 0.016 32.2049 3.178 25.0232C6.99221 16.3662 12.6411 7.90372 17.8131 0.00538ZM18.3738 7.24807L17.5881 7.48441C14.4452 12.9431 10.917 18.2341 8.19369 23.9368C4.6808 31.29 1.18317 38.5479 7.69403 45.5657C17.3058 55.9228 34.9847 46.8808 31.4604 32.8681C29.2558 24.0969 22.4207 15.2913 18.3776 7.24807H18.3738Z`,fill:`#C3C2C1`})})}function Ike({className:e}){return(0,K.jsxs)(`svg`,{className:e,viewBox:`0 0 35 53`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,children:[(0,K.jsx)(`path`,{d:`M17.3165 0.0038C17.932 -0.14959 19.7971 3.08645 20.2458 3.77481C24.7103 10.6135 34.3251 26.4346 34.937 34.2198C36.3757 52.5848 11.5505 60.1942 2.46584 44.534C-1.68714 37.3735 0.0148 31.6085 3.08879 24.5603C6.79681 16.0605 12.2884 7.75907 17.3165 0.0038ZM17.8615 7.11561L17.0977 7.34755C14.0423 12.7048 10.6124 17.8974 7.96483 23.4941C4.54975 30.7107 1.14949 37.8337 7.47908 44.721C16.8233 54.8856 34.01 46.0117 30.5838 32.2595C28.4405 23.6512 21.7957 15.0093 17.8652 7.11561H17.8615Z`,fill:`#C3C2C1`}),(0,K.jsx)(`path`,{d:`M5.03547 30.112C9.64453 30.4936 11.632 35.7985 16.4154 35.791C19.6339 35.7873 20.2161 33.2283 22.3853 31.6197C31.6776 24.7286 33.5835 37.4894 27.9881 44.4254C18.1878 56.5653 -1.16063 44.6013 5.03917 30.1158L5.03547 30.112Z`,fill:`#1F8FEB`})]})}function Lke({className:e}){return(0,K.jsxs)(`svg`,{className:e,viewBox:`0 0 36 54`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,children:[(0,K.jsx)(`path`,{d:`M17.9625 4.48059L4.77216 26.3154L2.08228 40.2175L10.0224 50.8414H23.1594L33.3246 42.1693V30.2455L17.9625 4.48059Z`,fill:`#1F8FEB`}),(0,K.jsx)(`path`,{d:`M17.7948 0.00538C18.4273 -0.15091 20.3438 3.14642 20.8048 3.84781C25.3921 10.816 35.2715 26.9368 35.9001 34.8694C37.3784 53.5822 11.8702 61.3357 2.53562 45.3789C-1.73163 38.0829 0.0134 32.2087 3.1757 25.027C6.98574 16.3662 12.6284 7.90372 17.7948 0.00538ZM18.3549 7.24807L17.57 7.48441C14.4306 12.9431 10.9063 18.2341 8.1859 23.9368C4.67686 31.29 1.18305 38.5479 7.68679 45.5657C17.2881 55.9228 34.9476 46.8808 31.4271 32.8681C29.2249 24.0969 22.3974 15.2913 18.3587 7.24807H18.3549Z`,fill:`#C3C2C1`})]})}function Rke({className:e}){return(0,K.jsxs)(`svg`,{className:e,viewBox:`0 0 12 20`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,children:[(0,K.jsx)(`path`,{d:`M6 0.5C4.6 0.5 3.5 1.6 3.5 3V12.1C2.6 12.8 2 13.9 2 15C2 17.2 3.8 19 6 19C8.2 19 10 17.2 10 15C10 13.9 9.4 12.8 8.5 12.1V3C8.5 1.6 7.4 0.5 6 0.5Z`,stroke:`#C3C2C1`,strokeWidth:`1`,fill:`none`}),(0,K.jsx)(`circle`,{cx:`6`,cy:`15`,r:`2.5`,stroke:`#C3C2C1`,strokeWidth:`1`,fill:`none`})]})}function zke({className:e}){return(0,K.jsxs)(`svg`,{className:e,viewBox:`0 0 12 20`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,children:[(0,K.jsx)(`rect`,{x:`4.5`,y:`8`,width:`3`,height:`4.5`,fill:`#d4a017`,rx:`0.5`}),(0,K.jsx)(`circle`,{cx:`6`,cy:`15`,r:`2`,fill:`#d4a017`}),(0,K.jsx)(`path`,{d:`M6 0.5C4.6 0.5 3.5 1.6 3.5 3V12.1C2.6 12.8 2 13.9 2 15C2 17.2 3.8 19 6 19C8.2 19 10 17.2 10 15C10 13.9 9.4 12.8 8.5 12.1V3C8.5 1.6 7.4 0.5 6 0.5Z`,stroke:`#C3C2C1`,strokeWidth:`1`,fill:`none`})]})}function Bke({className:e}){return(0,K.jsxs)(`svg`,{className:e,viewBox:`0 0 12 20`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,children:[(0,K.jsx)(`rect`,{x:`4.5`,y:`3`,width:`3`,height:`9.5`,fill:`#c62828`,rx:`0.5`}),(0,K.jsx)(`circle`,{cx:`6`,cy:`15`,r:`2`,fill:`#c62828`}),(0,K.jsx)(`path`,{d:`M6 0.5C4.6 0.5 3.5 1.6 3.5 3V12.1C2.6 12.8 2 13.9 2 15C2 17.2 3.8 19 6 19C8.2 19 10 17.2 10 15C10 13.9 9.4 12.8 8.5 12.1V3C8.5 1.6 7.4 0.5 6 0.5Z`,stroke:`#C3C2C1`,strokeWidth:`1`,fill:`none`})]})}function Vke({className:e}){return(0,K.jsxs)(`svg`,{className:e,viewBox:`0 0 24 24`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,stroke:`currentColor`,strokeWidth:`1.5`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,K.jsx)(`rect`,{x:`9.2`,y:`3.4`,width:`5.6`,height:`8.1`}),(0,K.jsx)(`rect`,{x:`6`,y:`11.5`,width:`12.1`,height:`3.7`}),(0,K.jsx)(`path`,{d:`M 7.3 15.2 L 12.1 19.6 L 16.7 15.2`})]})}function _W({className:e,color:t,isHeating:n}){let r={"text-orange-400":`#fb923c`,"text-blue-400":`#60a5fa`,"text-green-400":`#4ade80`}[t]||`#888`,i=n?{filter:`drop-shadow(0 0 4px ${r}) drop-shadow(0 0 8px ${r})`}:{};return n?(0,K.jsxs)(`svg`,{className:e,style:i,viewBox:`0 0 12 20`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,children:[(0,K.jsx)(`rect`,{x:`4.5`,y:`3`,width:`3`,height:`9.5`,fill:r,rx:`0.5`}),(0,K.jsx)(`circle`,{cx:`6`,cy:`15`,r:`2`,fill:r}),(0,K.jsx)(`path`,{d:`M6 0.5C4.6 0.5 3.5 1.6 3.5 3V12.1C2.6 12.8 2 13.9 2 15C2 17.2 3.8 19 6 19C8.2 19 10 17.2 10 15C10 13.9 9.4 12.8 8.5 12.1V3C8.5 1.6 7.4 0.5 6 0.5Z`,stroke:r,strokeWidth:`1`,fill:`none`})]}):(0,K.jsxs)(`svg`,{className:e,viewBox:`0 0 12 20`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,children:[(0,K.jsx)(`path`,{d:`M6 0.5C4.6 0.5 3.5 1.6 3.5 3V12.1C2.6 12.8 2 13.9 2 15C2 17.2 3.8 19 6 19C8.2 19 10 17.2 10 15C10 13.9 9.4 12.8 8.5 12.1V3C8.5 1.6 7.4 0.5 6 0.5Z`,stroke:r,strokeWidth:`1`,fill:`none`}),(0,K.jsx)(`circle`,{cx:`6`,cy:`15`,r:`2.5`,stroke:r,strokeWidth:`1`,fill:`none`})]})}function Hke({state:e,onClick:t}){let{t:n}=W(),r=e!==null,i=`flex items-center justify-center w-[18px] h-[18px] rounded text-[10px] transition-colors `,a;return e===!0?(i+=r?`bg-blue-100 dark:bg-blue-500/20 text-blue-700 dark:text-blue-400 hover:bg-blue-500/30 cursor-pointer`:`bg-blue-100 dark:bg-blue-500/20 text-blue-700 dark:text-blue-400 cursor-default`,a=n(`printers.amsBackup.titleOn`)):e===!1?(i+=r?`bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark/80 cursor-pointer`:`bg-bambu-dark text-bambu-gray cursor-default`,a=n(`printers.amsBackup.titleOff`)):(i+=`bg-bambu-dark text-bambu-gray/50 cursor-default`,a=n(`printers.amsBackup.titleUnknown`)),(0,K.jsx)(`button`,{type:`button`,disabled:!r,onClick:()=>r&&t(),className:i,title:a,"aria-label":a,children:r?(0,K.jsx)(Al,{className:`w-3 h-3`}):(0,K.jsx)(`span`,{children:`?`})})}function vW({humidity:e,goodThreshold:t=40,fairThreshold:n=60,onClick:r,compact:i}){let a=typeof e==`string`?parseInt(e,10):e,o=typeof t==`number`?t:40,s=typeof n==`number`?n:60,c,l;isNaN(a)?(c=`#C3C2C1`,l=`Unknown`):a<=o?(c=`#22a352`,l=`Good`):a<=s?(c=`#d4a017`,l=`Fair`):(c=`#c62828`,l=`Bad`);let u;return u=isNaN(a)||a<=o?Fke:a<=s?Ike:Lke,(0,K.jsxs)(`button`,{type:`button`,onClick:r,className:`flex items-center gap-1 ${r?`cursor-pointer hover:opacity-80 transition-opacity`:``}`,title:`Humidity: ${a}% - ${l}${r?` (click for history)`:``}`,children:[(0,K.jsx)(u,{className:i?`w-2.5 h-3`:`w-3 h-4`}),(0,K.jsxs)(`span`,{className:`font-medium tabular-nums ${i?`text-[10px]`:`text-xs`}`,style:{color:c},children:[a,`%`]})]})}function yW({temp:e,goodThreshold:t=28,fairThreshold:n=35,onClick:r,compact:i}){let a=typeof t==`number`?t:28,o=typeof n==`number`?n:35,s,c,l;return e<=a?(s=`#22a352`,c=`Good`,l=Rke):e<=o?(s=`#d4a017`,c=`Fair`,l=zke):(s=`#c62828`,c=`Bad`,l=Bke),(0,K.jsxs)(`button`,{type:`button`,onClick:r,className:`flex items-center gap-1 ${r?`cursor-pointer hover:opacity-80 transition-opacity`:``}`,title:`Temperature: ${e}°C - ${c}${r?` (click for history)`:``}`,children:[(0,K.jsx)(l,{className:i?`w-2.5 h-3`:`w-3 h-4`}),(0,K.jsxs)(`span`,{className:`tabular-nums text-right ${i?`text-[10px] w-8`:`w-12`}`,style:{color:s},children:[e,`°C`]})]})}function bW(e){return e?.tray_type?null:e?.exists===!0?`reset`:e?.exists===!1||e?.state===9||e?.state===10?`physical`:`reset`}function Uke({url:e,printName:t,className:n=`w-20 h-20`,radiusClass:r=`rounded-lg`}){let{t:i}=W(),[a,o]=(0,y.useState)(!1),[s,c]=(0,y.useState)(!1),[l,u]=(0,y.useState)(!1),d=(0,y.useMemo)(()=>e?ed(`${e}${e.includes(`?`)?`&`:`?`}v=${encodeURIComponent(t||Date.now().toString())}`):null,[e,t]);return(0,y.useEffect)(()=>{o(!1),c(!1)},[d]),(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`div`,{className:`${n} flex-shrink-0 ${r} overflow-hidden bg-bambu-dark-tertiary flex items-center justify-center ${d&&a?`cursor-pointer`:``}`,onClick:()=>d&&a&&u(!0),children:d&&!s?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`img`,{src:d,alt:i(`printers.printPreview`),className:`w-full h-full object-cover ${a?`block`:`hidden`}`,onLoad:()=>o(!0),onError:()=>c(!0)}),!a&&(0,K.jsx)(Uo,{className:`w-8 h-8 text-bambu-gray`})]}):(0,K.jsx)(Uo,{className:`w-8 h-8 text-bambu-gray`})}),l&&d&&(0,K.jsx)(`div`,{className:`fixed inset-0 bg-black/80 flex items-center justify-center z-50 p-8`,onClick:()=>u(!1),children:(0,K.jsxs)(`div`,{className:`relative max-w-2xl max-h-full`,children:[(0,K.jsx)(`img`,{src:d,alt:i(`printers.printPreview`),className:`max-w-full max-h-[80vh] rounded-lg shadow-2xl`}),t&&(0,K.jsx)(`p`,{className:`text-white text-center mt-4 text-lg`,children:t})]})})]})}function Wke({printers:e}){let{t}=W(),n=to(),[r,i]=(0,y.useState)(0);(0,y.useEffect)(()=>{let e=!1,t=n.getQueryCache().subscribe(()=>{e||(e=!0,requestAnimationFrame(()=>{i(e=>e+1),e=!1}))});return()=>t()},[n]);let{counts:a,nextFinish:o}=(0,y.useMemo)(()=>{let t=0,r=0,i=0,a=0,o=0,s=0,c=0,l=null,u=null,d=0;return e?.forEach(e=>{let f=n.getQueryData([`printerStatus`,e.id]);if(f===void 0)s++;else if(!f.connected)o++;else{let n=f.hms_errors?Yp(f.hms_errors).length:0;switch(n>0&&c++,f.state){case`RUNNING`:t++,f.remaining_time!=null&&f.remaining_time>0&&(u===null||f.remaining_time0||i++;break;default:a++;break}}}),{counts:{printing:t,paused:r,finished:i,idle:a,offline:o,loading:s,error:c,total:e?.length||0},nextFinish:l&&u?{name:l,remainingMin:u,progress:d}:null}},[e,n,r]);return e?.length?(0,K.jsxs)(`div`,{className:`mt-1 flex flex-wrap items-center gap-4 gap-y-2 text-bambu-gray`,children:[[{count:a.printing,dot:`bg-bambu-green animate-pulse`,label:t(`printers.status.printing`).toLowerCase()},{count:a.paused,dot:`bg-status-warning`,label:t(`printers.status.paused`,`paused`).toLowerCase()},{count:a.finished,dot:`bg-blue-400`,label:t(`printers.status.finished`,`finished`).toLowerCase()},{count:a.idle,dot:a.idle>0?`bg-bambu-green`:`bg-gray-500`,label:t(`printers.status.available`).toLowerCase()},{count:a.error,dot:`bg-status-error`,label:t(`printers.status.problem`).toLowerCase()},{count:a.offline,dot:`bg-gray-400`,label:t(`printers.status.offline`).toLowerCase()}].map(({count:e,dot:t,label:n})=>e>0&&(0,K.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,K.jsx)(`div`,{className:`w-2 h-2 rounded-full ${t}`}),(0,K.jsxs)(`span`,{className:`text-bambu-gray`,children:[(0,K.jsx)(`span`,{className:`text-white font-medium`,children:e}),` `,n]})]},n)),o&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`div`,{className:`w-px h-4 bg-bambu-dark-tertiary`}),(0,K.jsxs)(`div`,{className:`flex flex-col gap-1 sm:flex-row sm:items-center sm:gap-2`,children:[(0,K.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,K.jsxs)(`span`,{className:`text-bambu-green font-medium`,children:[t(`printers.nextAvailable`),`:`]}),(0,K.jsx)(`span`,{className:`text-white font-medium`,children:o.name})]}),(0,K.jsxs)(`div`,{className:`flex items-center gap-2 w-full sm:w-auto`,children:[(0,K.jsx)(`div`,{className:`w-full sm:w-16 bg-bambu-dark-tertiary rounded-full h-1.5`,children:(0,K.jsx)(`div`,{className:`bg-bambu-green h-1.5 rounded-full transition-all`,style:{width:`${o.progress}%`}})}),(0,K.jsxs)(`span`,{className:`text-white font-medium`,children:[Math.round(o.progress),`%`]}),(0,K.jsxs)(`span`,{className:`text-bambu-gray`,children:[`(`,jf(o.remainingMin*60),`)`]})]})]})]})]}):null}function xW({value:e,options:t,onChange:n,fullWidth:r=!1}){let[i,a]=(0,y.useState)(!1),o=t.find(t=>t.value===e)??t[0];return(0,K.jsxs)(`div`,{className:`relative ${r?`w-full min-w-0`:``}`,children:[(0,K.jsxs)(`button`,{type:`button`,onClick:()=>a(e=>!e),className:`h-8 px-2 rounded-lg border bg-bambu-dark border-bambu-dark-tertiary text-white text-sm font-medium transition-colors hover:bg-bambu-dark-tertiary focus:outline-none focus:border-bambu-green flex items-center justify-between gap-2 ${r?`w-full`:`min-w-28`}`,children:[(0,K.jsx)(`span`,{className:`truncate`,children:o?.label}),(0,K.jsx)(ns,{className:`w-4 h-4 text-bambu-gray transition-transform ${i?`rotate-180`:``}`})]}),i&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`div`,{className:`fixed inset-0 z-10`,onClick:()=>a(!1)}),(0,K.jsx)(`div`,{className:`absolute left-0 top-full z-20 mt-1 min-w-full rounded-lg border border-bambu-dark-tertiary bg-bambu-dark-secondary py-1 shadow-xl`,children:t.map(t=>(0,K.jsx)(`button`,{type:`button`,onClick:()=>{n(t.value),a(!1)},className:`w-full px-3 py-2 text-left text-sm transition-colors hover:bg-bambu-dark-tertiary ${t.value===e?`text-bambu-green`:`text-white`}`,children:t.label},t.value))})]})]})}function SW({label:e,icon:t,children:n}){let[r,i]=(0,y.useState)(!1);return(0,K.jsxs)(`div`,{className:`relative`,children:[(0,K.jsx)(`button`,{type:`button`,onClick:()=>i(e=>!e),className:`h-8 w-8 rounded-lg border bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary transition-colors flex items-center justify-center`,"aria-label":e,title:e,children:t}),r&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`div`,{className:`fixed inset-0 z-10`,onClick:()=>i(!1)}),(0,K.jsx)(`div`,{className:`absolute right-0 top-full z-20 mt-1 min-w-40 rounded-lg border border-bambu-dark-tertiary bg-bambu-dark-secondary p-2 shadow-xl`,children:n})]})]})}function CW({title:e,options:t=[],unit:n,customMin:r,customMax:i,customStep:a=1,widthClass:o=`w-[240px]`,popoverWidth:s=240,popoverHeight:c=280,isPending:l,onClose:u,onSubmit:d,children:f}){let p=(0,y.useRef)(null),[m,h]=(0,y.useState)(null),[g,_]=(0,y.useState)(``);(0,y.useLayoutEffect)(()=>{let e=p.current?.parentElement;if(!e)return;let t=()=>{h(Bp({triggerRect:e.getBoundingClientRect(),popoverWidth:s,estimatedHeight:c,horizontalAlign:`center`}))};return t(),window.addEventListener(`resize`,t),window.addEventListener(`scroll`,t,!0),()=>{window.removeEventListener(`resize`,t),window.removeEventListener(`scroll`,t,!0)}},[s,c]);let v=n!==void 0,b=()=>{let e=Number(g);Number.isFinite(e)&&d?.(Math.round(Math.min(i??e,Math.max(r??e,e))))};return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`span`,{ref:p,className:`hidden`,"aria-hidden":`true`}),(0,Rp.createPortal)((0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`div`,{className:`fixed inset-0 z-[1000]`,onClick:u}),(0,K.jsxs)(`div`,{className:`fixed z-[1001] flex ${o} flex-col overflow-hidden rounded-xl border border-bambu-dark-tertiary bg-bambu-dark-secondary shadow-2xl`,style:{top:m?.top??-9999,left:m?.left??-9999,visibility:m?`visible`:`hidden`},onClick:e=>e.stopPropagation(),children:[(0,K.jsx)(`div`,{className:`shrink-0 px-3 py-2.5 text-center text-sm font-medium text-white`,children:e}),(0,K.jsx)(`div`,{className:`shrink-0 h-px bg-bambu-dark-tertiary`}),t.length>0&&(0,K.jsx)(`div`,{className:`px-3 py-2.5`,children:(0,K.jsx)(`div`,{className:`grid grid-cols-2 gap-1.5`,children:t.map(e=>(0,K.jsx)(`button`,{type:`button`,disabled:l,onClick:()=>d?.(e.value),className:`h-8 rounded-lg border border-bambu-dark-tertiary bg-bambu-dark px-2 text-xs font-medium text-white transition-colors hover:bg-bambu-dark-tertiary disabled:cursor-not-allowed disabled:opacity-50`,children:e.label},`${e.label}-${e.value}`))})}),f,v&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`div`,{className:`shrink-0 h-px bg-bambu-dark-tertiary`}),(0,K.jsxs)(`form`,{className:`flex gap-1.5 px-3 pt-2.5 pb-3`,onSubmit:e=>{e.preventDefault(),b()},children:[(0,K.jsx)(`input`,{type:`number`,min:r,max:i,step:a,value:g,onChange:e=>_(e.target.value),placeholder:`Custom`,className:`h-8 min-w-0 flex-1 rounded-lg border border-bambu-dark-tertiary bg-bambu-dark px-2 text-xs text-white placeholder:text-bambu-gray/60 focus:border-bambu-green focus:outline-none`}),(0,K.jsx)(`button`,{type:`submit`,disabled:l||g.trim()===``,className:`h-8 rounded-lg border border-bambu-dark-tertiary bg-bambu-dark px-2 text-xs font-medium text-white transition-colors hover:bg-bambu-dark-tertiary disabled:cursor-not-allowed disabled:opacity-50`,children:`Set`})]})]})]})]}),document.body)]})}var Gke=Kp(Vp,`C`);function wW({label:e,current:t,target:n,isActive:r,isPending:i,onSubmit:a,options:o=Gke}){let[s,c]=(0,y.useState)(``),l=()=>{let e=Number(s);Number.isFinite(e)&&a(Math.min(320,Math.max(0,Math.round(e))))};return(0,K.jsxs)(`div`,{className:`rounded-lg border p-2 ${r?`border-amber-500/60 dark:border-amber-400/60 bg-amber-50 dark:bg-amber-400/10`:`border-bambu-dark-tertiary bg-bambu-dark`}`,children:[(0,K.jsxs)(`div`,{className:`mb-1.5 flex items-center justify-between gap-2`,children:[(0,K.jsx)(`span`,{className:`text-xs font-medium ${r?`text-amber-700 dark:text-amber-300`:`text-white`}`,children:e}),(0,K.jsxs)(`span`,{className:`text-[10px] text-bambu-gray`,children:[Math.round(t??0),`°C`,n===void 0?``:` / ${Math.round(n)}°`]})]}),(0,K.jsx)(`div`,{className:`grid grid-cols-2 gap-1`,children:o.map(t=>(0,K.jsx)(`button`,{type:`button`,disabled:i,onClick:()=>a(t.value),className:`h-7 rounded-md border border-bambu-dark-tertiary bg-bambu-dark-secondary px-1.5 text-[11px] font-medium text-white transition-colors hover:bg-bambu-dark-tertiary disabled:cursor-not-allowed disabled:opacity-50`,children:t.label},`${e}-${t.value}`))}),(0,K.jsxs)(`form`,{className:`mt-1.5 flex gap-1`,onSubmit:e=>{e.preventDefault(),l()},children:[(0,K.jsx)(`input`,{type:`number`,min:0,max:320,step:1,value:s,onChange:e=>c(e.target.value),placeholder:`Custom`,className:`h-7 min-w-0 flex-1 rounded-md border border-bambu-dark-tertiary bg-bambu-dark-secondary px-1.5 text-[11px] text-white placeholder:text-bambu-gray/60 focus:border-bambu-green focus:outline-none`}),(0,K.jsx)(`button`,{type:`submit`,disabled:i||s.trim()===``,className:`h-7 rounded-md border border-bambu-dark-tertiary bg-bambu-dark-secondary px-2 text-[11px] font-medium text-white transition-colors hover:bg-bambu-dark-tertiary disabled:cursor-not-allowed disabled:opacity-50`,children:`Set`})]})]})}var Kke=[`error`,`printing`,`paused`,`finished`,`idle`,`offline`],TW={error:{labelKey:`printers.status.problem`,dot:`bg-status-error`},printing:{labelKey:`printers.status.printing`,dot:`bg-bambu-green animate-pulse`},paused:{labelKey:`printers.status.paused`,dot:`bg-status-warning`},finished:{labelKey:`printers.status.finished`,dot:`bg-blue-400`},idle:{labelKey:`printers.status.idle`,dot:`bg-bambu-green`},offline:{labelKey:`printers.status.offline`,dot:`bg-gray-400`}};function EW(e){if(!e?.connected)return`offline`;if((e.hms_errors?Yp(e.hms_errors):[]).length>0)return`error`;switch(e.state){case`RUNNING`:return`printing`;case`PAUSE`:return`paused`;case`FINISH`:return`finished`;case`FAILED`:return`finished`;default:return`idle`}}function qke(e,t){if(t)return t;switch(e){case`RUNNING`:return`Printing`;case`PAUSE`:return`Paused`;case`FINISH`:return`Finished`;case`FAILED`:return`Failed`;case`IDLE`:return`Idle`;default:return e?e.charAt(0)+e.slice(1).toLowerCase():`Idle`}}var Jke=new Set([`X1C`,`X1`,`X1E`,`X2D`,`P1S`,`P2S`,`H2D`,`H2D Pro`,`H2C`,`H2S`]);function DW(e){return e?{O1D:`H2D`,O1E:`H2D Pro`,O2D:`H2D Pro`,O1C:`H2C`,O1C2:`H2C`,O1S:`H2S`,"BL-P001":`X1C`,"BL-P002":`X1`,"BL-P003":`X1E`,N6:`X2D`,N9:`A2L`,C11:`P1S`,C12:`P1P`,C13:`P2S`,N2S:`A1`,N1:`A1 Mini`,X1C:`X1C`,X1:`X1`,X1E:`X1E`,X2D:`X2D`,P1S:`P1S`,P1P:`P1P`,P2S:`P2S`,A1:`A1`,"A1 Mini":`A1 Mini`,A2L:`A2L`,H2D:`H2D`,"H2D Pro":`H2D Pro`,H2C:`H2C`,H2S:`H2S`}[e]||e:``}function OW({ams:e,printerId:t,label:n,amsLabels:r,canEdit:i,onSaved:a,children:o}){let{t:s}=W(),[c,l]=(0,y.useState)(!1),[u,d]=(0,y.useState)(`top`),[f,p]=(0,y.useState)(``),[m,h]=(0,y.useState)(!1),[g,_]=(0,y.useState)(null),[v,b]=(0,y.useState)(!1),x=(0,y.useRef)(null),S=(0,y.useRef)(null),C=(0,y.useRef)(null);(0,y.useEffect)(()=>{c&&(p(r?.[e.id]??``),_(null),requestAnimationFrame(()=>{if(x.current&&S.current){let e=x.current.getBoundingClientRect(),t=e.top-56,n=window.innerHeight-e.bottom;d(tt?`bottom`:`top`)}}))},[c,r,e.id]);let w=()=>{C.current&&clearTimeout(C.current),C.current=setTimeout(()=>l(!0),80)},T=()=>{C.current&&clearTimeout(C.current),v||(C.current=setTimeout(()=>l(!1),200))};(0,y.useEffect)(()=>()=>{C.current&&clearTimeout(C.current)},[]);let E=async()=>{if(i){h(!0),_(null);try{let n=f.trim();n?await Q.saveAmsLabel(t,e.id,n,e.serial_number):await Q.deleteAmsLabel(t,e.id,e.serial_number),a(),l(!1)}catch(e){_(e instanceof Error?e.message:String(e))}finally{h(!1)}}};return(0,K.jsxs)(`div`,{ref:x,className:`relative inline-block`,onMouseEnter:w,onMouseLeave:T,children:[o,c&&(0,K.jsx)(`div`,{ref:S,className:` absolute left-0 z-50 ${u===`top`?`bottom-full mb-2`:`top-full mt-2`} animate-in fade-in-0 zoom-in-95 duration-150 @@ -8757,5 +8757,5 @@ ${t.slice(l+2)}`,d+=1;else break}t.push({indent:l,number:parseInt(s,10),content: In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}()}function a(e,t){if(e){if(typeof e==`string`)return o(e,t);var n={}.toString.call(e).slice(8,-1);return n===`Object`&&e.constructor&&(n=e.constructor.name),n===`Map`||n===`Set`?Array.from(e):n===`Arguments`||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?o(e,t):void 0}}function o(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n`u`||`remove`in Element.prototype||(Element.prototype.remove=function(){this.parentNode&&this.parentNode.removeChild(this)}),typeof self<`u`&&`document`in self&&((!(`classList`in document.createElement(`_`))||document.createElementNS&&!(`classList`in document.createElementNS(`http://www.w3.org/2000/svg`,`g`)))&&function(e){if(`Element`in e){var t=`classList`,n=`prototype`,r=e.Element[n],i=Object,a=String[n].trim||function(){return this.replace(/^\s+|\s+$/g,``)},o=Array[n].indexOf||function(e){for(var t=0,n=this.length;t2&&arguments[2]!==void 0&&arguments[2]?Object.assign({},this.getDefaultDiplay(),t):t||this.getDefaultDiplay())[e]||e}},{key:`getUpdatedInput`,value:function(e,t,n){var r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:n,i=arguments.length>4&&arguments[4]!==void 0&&arguments[4],a=this.getOptions(),o=[n,r,i],s=t;return(e===`{bksp}`||e===`{backspace}`)&&s.length>0?s=this.removeAt.apply(this,[s].concat(o)):(e===`{delete}`||e===`{forwarddelete}`)&&s.length>0?s=this.removeForwardsAt.apply(this,[s].concat(o)):e===`{space}`?s=this.addStringAt.apply(this,[s,` `].concat(o)):e!==`{tab}`||typeof a.tabCharOnTab==`boolean`&&!1===a.tabCharOnTab?e!==`{enter}`&&e!==`{numpadenter}`||!a.newLineOnEnter?e.includes(`numpad`)&&Number.isInteger(Number(e[e.length-2]))?s=this.addStringAt.apply(this,[s,e[e.length-2]].concat(o)):e===`{numpaddivide}`?s=this.addStringAt.apply(this,[s,`/`].concat(o)):e===`{numpadmultiply}`?s=this.addStringAt.apply(this,[s,`*`].concat(o)):e===`{numpadsubtract}`?s=this.addStringAt.apply(this,[s,`-`].concat(o)):e===`{numpadadd}`?s=this.addStringAt.apply(this,[s,`+`].concat(o)):e===`{numpaddecimal}`?s=this.addStringAt.apply(this,[s,`.`].concat(o)):e===`{`||e===`}`?s=this.addStringAt.apply(this,[s,e].concat(o)):e.includes(`{`)||e.includes(`}`)||(s=this.addStringAt.apply(this,[s,e].concat(o))):s=this.addStringAt.apply(this,[s,` `].concat(o)):s=this.addStringAt.apply(this,[s,` `].concat(o)),a.debug&&console.log(`Input will be: `+s),s}},{key:`updateCaretPos`,value:function(e){var t=arguments.length>1&&arguments[1]!==void 0&&arguments[1],n=this.updateCaretPosAction(e,t);this.dispatch((function(e){e.setCaretPosition(n)}))}},{key:`updateCaretPosAction`,value:function(e){var t=arguments.length>1&&arguments[1]!==void 0&&arguments[1],n=this.getOptions(),r=this.getCaretPosition();return r!=null&&(t?r>0&&(r-=e):r+=e),n.debug&&console.log(`Caret at:`,r),r}},{key:`addStringAt`,value:function(e,t){var n,r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:e.length,i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:e.length,a=arguments.length>4&&arguments[4]!==void 0&&arguments[4];return r||r===0?(n=[e.slice(0,r),t,e.slice(i)].join(``),this.isMaxLengthReached()||a&&this.updateCaretPos(t.length)):n=e+t,n}},{key:`removeAt`,value:function(e){var t,n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:e.length,r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:e.length,i=arguments.length>3&&arguments[3]!==void 0&&arguments[3];if(n===0&&r===0)return e;if(n===r){var a=/([\uD800-\uDBFF][\uDC00-\uDFFF])/g;n&&n>=0?e.substring(n-2,n).match(a)?(t=e.substr(0,n-2)+e.substr(n),i&&this.updateCaretPos(2,!0)):(t=e.substr(0,n-1)+e.substr(n),i&&this.updateCaretPos(1,!0)):e.slice(-2).match(a)?(t=e.slice(0,-2),i&&this.updateCaretPos(2,!0)):(t=e.slice(0,-1),i&&this.updateCaretPos(1,!0))}else t=e.slice(0,n)+e.slice(r),i&&this.dispatch((function(e){e.setCaretPosition(n)}));return t}},{key:`removeForwardsAt`,value:function(e){var t,n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:e.length,r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:e.length,i=arguments.length>3&&arguments[3]!==void 0&&arguments[3];return e!=null&&e.length&&n!==null?(n===r?t=e.substring(n,n+2).match(/([\uD800-\uDBFF][\uDC00-\uDFFF])/g)?e.substr(0,n)+e.substr(n+2):e.substr(0,n)+e.substr(n+1):(t=e.slice(0,n)+e.slice(r),i&&this.dispatch((function(e){e.setCaretPosition(n)}))),t):e}},{key:`handleMaxLength`,value:function(e,t){var n=this.getOptions(),r=n.maxLength,i=e[n.inputName||`default`],a=t.length-1>=r;if(t.length<=i.length)return!1;if(Number.isInteger(r))return n.debug&&console.log(`maxLength (num) reached:`,a),a?(this.maxLengthReached=!0,!0):(this.maxLengthReached=!1,!1);if(s(r)===`object`){var o=t.length-1>=r[n.inputName||`default`];return n.debug&&console.log(`maxLength (obj) reached:`,o),o?(this.maxLengthReached=!0,!0):(this.maxLengthReached=!1,!1)}}},{key:`isMaxLengthReached`,value:function(){return!!this.maxLengthReached}},{key:`isTouchDevice`,value:function(){return`ontouchstart`in window||navigator.maxTouchPoints}},{key:`pointerEventsSupported`,value:function(){return!!window.PointerEvent}},{key:`camelCase`,value:function(e){return e?e.toLowerCase().trim().split(/[.\-_\s]/g).reduce((function(e,t){return t.length?e+t[0].toUpperCase()+t.slice(1):e})):``}},{key:`chunkArray`,value:function(e,t){return i(Array(Math.ceil(e.length/t))).map((function(n,r){return e.slice(t*r,t+t*r)}))}},{key:`escapeRegex`,value:function(e){return e.replace(/[-\/\\^$*+?.()|[\]{}]/g,`\\$&`)}},{key:`getRtlOffset`,value:function(e,t){var n=e,r=t.indexOf(`‫`);return r=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:i}}throw TypeError(`Invalid attempt to iterate non-iterable instance. In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var o,s=!0,c=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return s=e.done,e},e:function(e){c=!0,o=e},f:function(){try{s||n.return==null||n.return()}finally{if(c)throw o}}}}(Object.getOwnPropertyNames(e.prototype));try{for(r.s();!(n=r.n()).done;){var i=n.value;i===`constructor`||i===`bindMethods`||(t[i]=t[i].bind(t))}}catch(e){r.e(e)}finally{r.f()}}}],t&&c(e.prototype,t),n&&c(e,n),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t,n}();l(d,`noop`,(function(){}));var f=d;function p(e){return p=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},p(e)}function m(e,t){for(var n=0;n1?t?.toLowerCase():t}},{key:`keyCodeToKey`,value:function(e){return{8:`Backspace`,9:`Tab`,13:`Enter`,16:`Shift`,17:`Ctrl`,18:`Alt`,19:`Pause`,20:`CapsLock`,27:`Esc`,32:`Space`,33:`PageUp`,34:`PageDown`,35:`End`,36:`Home`,37:`ArrowLeft`,38:`ArrowUp`,39:`ArrowRight`,40:`ArrowDown`,45:`Insert`,46:`Delete`,48:`0`,49:`1`,50:`2`,51:`3`,52:`4`,53:`5`,54:`6`,55:`7`,56:`8`,57:`9`,65:`A`,66:`B`,67:`C`,68:`D`,69:`E`,70:`F`,71:`G`,72:`H`,73:`I`,74:`J`,75:`K`,76:`L`,77:`M`,78:`N`,79:`O`,80:`P`,81:`Q`,82:`R`,83:`S`,84:`T`,85:`U`,86:`V`,87:`W`,88:`X`,89:`Y`,90:`Z`,91:`Meta`,96:`Numpad0`,97:`Numpad1`,98:`Numpad2`,99:`Numpad3`,100:`Numpad4`,101:`Numpad5`,102:`Numpad6`,103:`Numpad7`,104:`Numpad8`,105:`Numpad9`,106:`NumpadMultiply`,107:`NumpadAdd`,109:`NumpadSubtract`,110:`NumpadDecimal`,111:`NumpadDivide`,112:`F1`,113:`F2`,114:`F3`,115:`F4`,116:`F5`,117:`F6`,118:`F7`,119:`F8`,120:`F9`,121:`F10`,122:`F11`,123:`F12`,144:`NumLock`,145:`ScrollLock`,186:`;`,187:`=`,188:`,`,189:`-`,190:`.`,191:`/`,192:"`",219:`[`,220:`\\`,221:`]`,222:`'`}[e]||``}}],t&&m(e.prototype,t),n&&m(e,n),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t,n}();function v(e){return v=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},v(e)}function y(e,t){for(var n=0;n0&&arguments[0]!==void 0?arguments[0]:r())},c.appendChild(t)}));var l=a>0,u=document.createElement(`div`);u.classList.add(`hg-candidate-box-prev`),l&&u.classList.add(`hg-candidate-box-btn-active`);var d=function(){l&&n.renderPage({candidateListPages:r,targetElement:i,pageIndex:a-1,nbPages:o,onItemSelected:s})};this.options.useTouchEvents?u.ontouchstart=d:u.onclick=d,this.candidateBoxElement.appendChild(u),this.candidateBoxElement.appendChild(c);var f=ae.length)&&(t=e.length);for(var n=0,r=Array(t);n1&&arguments[1]!==void 0?arguments[1]:e;this.caretPosition=e,this.caretPositionEnd=t}},{key:`getInputCandidates`,value:function(e){var t=this,n=this.options,r=n.layoutCandidates,i=n.layoutCandidatesCaseSensitiveMatch;if(!r||T(r)!==`object`)return{};var a=Object.keys(r).filter((function(n){var r=e.substring(0,t.getCaretPositionEnd()||0)||e,a=RegExp(`${t.utilities.escapeRegex(n)}\$`,i?`g`:`gi`);return!!C(r.matchAll(a)).length}));if(a.length>1){var o=a.sort((function(e,t){return t.length-e.length}))[0];return{candidateKey:o,candidateValue:r[o]}}if(a.length){var s=a[0];return{candidateKey:s,candidateValue:r[s]}}return{}}},{key:`showCandidatesBox`,value:function(e,t,n){var r=this;this.candidateBox&&this.candidateBox.show({candidateValue:t,targetElement:n,onSelect:function(t,n){var i=r.options,a=i.layoutCandidatesCaseSensitiveMatch,o=i.disableCandidateNormalization,s=i.enableLayoutCandidatesKeyPress,c=t;o||(c=t.normalize(`NFD`)),typeof r.options.beforeInputUpdate==`function`&&r.options.beforeInputUpdate(r);var l=r.getInput(r.options.inputName,!0),u=r.getCaretPositionEnd()||0,d=l.substring(0,u||0)||l,f=RegExp(`${r.utilities.escapeRegex(e)}\$`,a?`g`:`gi`),p=d.replace(f,c),m=l.replace(d,p),h=p.length-d.length,g=(u||l.length)+h;g<0&&(g=0),r.setInput(m,r.options.inputName,!0),r.setCaretPosition(g),s&&typeof r.options.onKeyPress==`function`&&r.options.onKeyPress(t,n),typeof r.options.onChange==`function`&&r.options.onChange(r.getInput(r.options.inputName,!0),n),typeof r.options.onChangeAll==`function`&&r.options.onChangeAll(r.getAllInputs(),n)}})}},{key:`handleButtonClicked`,value:function(e,t){var n=this.options,r=n.inputName,i=r===void 0?this.defaultName:r,a=n.debug;if(e!==`{//}`){this.input[i]||(this.input[i]=``),typeof this.options.beforeInputUpdate==`function`&&this.options.beforeInputUpdate(this);var o=this.utilities.getUpdatedInput(e,this.input[i],this.caretPosition,this.caretPositionEnd);if(this.utilities.isStandardButton(e)&&this.activeInputElement&&this.input[i]&&this.input[i]===o&&this.caretPosition===0&&this.caretPositionEnd===o.length)return this.setInput(``,this.options.inputName,!0),this.setCaretPosition(0),this.activeInputElement.value=``,this.activeInputElement.setSelectionRange(0,0),void this.handleButtonClicked(e,t);if(typeof this.options.onKeyPress==`function`&&this.options.onKeyPress(e,t),this.input[i]!==o&&(!this.options.inputPattern||this.options.inputPattern&&this.inputPatternIsValid(o))){if(this.options.maxLength&&this.utilities.handleMaxLength(this.input,o))return;var s=this.utilities.getUpdatedInput(e,this.input[i],this.caretPosition,this.caretPositionEnd,!0);if(this.setInput(s,this.options.inputName,!0),a&&console.log(`Input changed:`,this.getAllInputs()),this.options.debug&&console.log(`Caret at: `,this.getCaretPosition(),this.getCaretPositionEnd(),`(${this.keyboardDOMClass})`,t?.type),this.options.syncInstanceInputs&&this.syncInstanceInputs(),typeof this.options.onChange==`function`&&this.options.onChange(this.getInput(this.options.inputName,!0),t),typeof this.options.onChangeAll==`function`&&this.options.onChangeAll(this.getAllInputs(),t),t!=null&&t.target&&this.options.enableLayoutCandidates){var c,l=this.getInputCandidates(o),u=l.candidateKey,d=l.candidateValue;u&&d?this.showCandidatesBox(u,d,this.keyboardDOM):(c=this.candidateBox)==null||c.destroy()}}this.caretPositionEnd&&this.caretPosition!==this.caretPositionEnd&&(this.setCaretPosition(this.caretPositionEnd,this.caretPositionEnd),this.activeInputElement&&this.activeInputElement.setSelectionRange(this.caretPositionEnd,this.caretPositionEnd),this.options.debug&&console.log(`Caret position aligned`,this.caretPosition)),a&&console.log(`Key pressed:`,e)}}},{key:`getMouseHold`,value:function(){return this.isMouseHold}},{key:`setMouseHold`,value:function(e){this.options.syncInstanceInputs?this.dispatch((function(t){t.isMouseHold=e})):this.isMouseHold=e}},{key:`handleButtonMouseDown`,value:function(e,t){var n=this;t&&(this.options.preventMouseDownDefault&&t.preventDefault(),this.options.stopMouseDownPropagation&&t.stopPropagation(),t.target.classList.add(this.activeButtonClass)),this.holdInteractionTimeout&&clearTimeout(this.holdInteractionTimeout),this.holdTimeout&&clearTimeout(this.holdTimeout),this.setMouseHold(!0),this.options.disableButtonHold||(this.holdTimeout=window.setTimeout((function(){(n.getMouseHold()&&(!e.includes(`{`)&&!e.includes(`}`)||e===`{delete}`||e===`{backspace}`||e===`{bksp}`||e===`{space}`||e===`{tab}`)||e===`{arrowright}`||e===`{arrowleft}`||e===`{arrowup}`||e===`{arrowdown}`)&&(n.options.debug&&console.log(`Button held:`,e),n.handleButtonHold(e)),clearTimeout(n.holdTimeout)}),500))}},{key:`handleButtonMouseUp`,value:function(e,t){var n=this;t&&(this.options.preventMouseUpDefault&&t.preventDefault&&t.preventDefault(),this.options.stopMouseUpPropagation&&t.stopPropagation&&t.stopPropagation(),!(t.target===this.keyboardDOM||t.target&&this.keyboardDOM.contains(t.target)||this.candidateBox&&this.candidateBox.candidateBoxElement&&(t.target===this.candidateBox.candidateBoxElement||t.target&&this.candidateBox.candidateBoxElement.contains(t.target)))&&this.candidateBox&&this.candidateBox.destroy()),this.recurseButtons((function(e){e.classList.remove(n.activeButtonClass)})),this.setMouseHold(!1),this.holdInteractionTimeout&&clearTimeout(this.holdInteractionTimeout),e&&typeof this.options.onKeyReleased==`function`&&this.options.onKeyReleased(e,t)}},{key:`handleKeyboardContainerMouseDown`,value:function(e){this.options.preventMouseDownDefault&&e.preventDefault()}},{key:`handleButtonHold`,value:function(e){var t=this;this.holdInteractionTimeout&&clearTimeout(this.holdInteractionTimeout),this.holdInteractionTimeout=window.setTimeout((function(){t.getMouseHold()?(t.handleButtonClicked(e),t.handleButtonHold(e)):clearTimeout(t.holdInteractionTimeout)}),100)}},{key:`syncInstanceInputs`,value:function(){var e=this;this.dispatch((function(t){t.replaceInput(e.input),t.setCaretPosition(e.caretPosition,e.caretPositionEnd)}))}},{key:`clearInput`,value:function(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:this.options.inputName||this.defaultName;this.input[e]=``,this.setCaretPosition(0),this.options.syncInstanceInputs&&this.syncInstanceInputs()}},{key:`getInput`,value:function(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:this.options.inputName||this.defaultName,t=arguments.length>1&&arguments[1]!==void 0&&arguments[1];return this.options.syncInstanceInputs&&!t&&this.syncInstanceInputs(),this.options.rtl?`‫`+this.input[e].replace(`‫`,``).replace(`‬`,``)+`‬`:this.input[e]}},{key:`getAllInputs`,value:function(){var e=this,t={};return Object.keys(this.input).forEach((function(n){t[n]=e.getInput(n,!0)})),t}},{key:`setInput`,value:function(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.options.inputName||this.defaultName,n=arguments.length>2?arguments[2]:void 0;this.input[t]=e,!n&&this.options.syncInstanceInputs&&this.syncInstanceInputs()}},{key:`replaceInput`,value:function(e){this.input=e}},{key:`setOptions`,value:function(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},t=this.changedOptions(e);this.options=Object.assign(this.options,e),t.length&&(this.options.debug&&console.log(`changedOptions`,t),this.onSetOptions(t),this.render())}},{key:`changedOptions`,value:function(e){var t=this;return Object.keys(e).filter((function(n){return JSON.stringify(e[n])!==JSON.stringify(t.options[n])}))}},{key:`onSetOptions`,value:function(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];e.includes(`layoutName`)&&this.candidateBox&&this.candidateBox.destroy(),(e.includes(`layoutCandidatesPageSize`)||e.includes(`layoutCandidates`))&&this.candidateBox&&(this.candidateBox.destroy(),this.candidateBox=new S({utilities:this.utilities,options:this.options}))}},{key:`resetRows`,value:function(){this.keyboardRowsDOM&&this.keyboardRowsDOM.remove(),this.keyboardDOM.className=this.keyboardDOMClass,this.keyboardDOM.setAttribute(`data-skInstance`,this.currentInstanceName),this.buttonElements={}}},{key:`dispatch`,value:function(e){if(!window.SimpleKeyboardInstances)throw console.warn(`SimpleKeyboardInstances is not defined. Dispatch cannot be called.`),Error(`INSTANCES_VAR_ERROR`);return Object.keys(window.SimpleKeyboardInstances).forEach((function(t){e(window.SimpleKeyboardInstances[t],t)}))}},{key:`addButtonTheme`,value:function(e,t){var n=this;t&&e&&(e.split(` `).forEach((function(r){t.split(` `).forEach((function(t){n.options.buttonTheme||(n.options.buttonTheme=[]);var i=!1;n.options.buttonTheme.map((function(e){if(e!=null&&e.class.split(` `).includes(t)){i=!0;var n=e.buttons.split(` `);n.includes(r)||(i=!0,n.push(r),e.buttons=n.join(` `))}return e})),i||n.options.buttonTheme.push({class:t,buttons:e})}))})),this.render())}},{key:`removeButtonTheme`,value:function(e,t){var n=this;if(!e&&!t)return this.options.buttonTheme=[],void this.render();e&&Array.isArray(this.options.buttonTheme)&&this.options.buttonTheme.length&&(e.split(` `).forEach((function(e){var r;(r=n.options)==null||(r=r.buttonTheme)==null||r.map((function(r,i){if(r&&t&&t.includes(r.class)||!t){var a,o=r?.buttons.split(` `).filter((function(t){return t!==e}));r&&o!=null&&o.length?r.buttons=o.join(` `):((a=n.options.buttonTheme)==null||a.splice(i,1),r=null)}return r}))})),this.render())}},{key:`getButtonElement`,value:function(e){var t,n=this.buttonElements[e];return n&&(t=n.length>1?n:n[0]),t}},{key:`inputPatternIsValid`,value:function(e){var t,n=this.options.inputPattern;if((t=n instanceof RegExp?n:n[this.options.inputName||this.defaultName])&&e){var r=t.test(e);return this.options.debug&&console.log(`inputPattern ("${t}"): ${r?`passed`:`did not pass!`}`),r}return!0}},{key:`setEventListeners`,value:function(){if(this.isFirstKeyboardInstance||!this.allKeyboardInstances){this.options.debug&&console.log(`Caret handling started (${this.keyboardDOMClass})`);var e=this.options.physicalKeyboardHighlightPreventDefault,t=e!==void 0&&e;document.addEventListener(`keyup`,this.handleKeyUp,t),document.addEventListener(`keydown`,this.handleKeyDown,t),document.addEventListener(`mouseup`,this.handleMouseUp),document.addEventListener(`touchend`,this.handleTouchEnd),this.options.updateCaretOnSelectionChange&&document.addEventListener(`selectionchange`,this.handleSelectionChange),document.addEventListener(`select`,this.handleSelect)}}},{key:`handleKeyUp`,value:function(e){this.caretEventHandler(e),this.options.physicalKeyboardHighlight&&this.physicalKeyboard.handleHighlightKeyUp(e)}},{key:`handleKeyDown`,value:function(e){this.options.physicalKeyboardHighlight&&this.physicalKeyboard.handleHighlightKeyDown(e)}},{key:`handleMouseUp`,value:function(e){this.caretEventHandler(e)}},{key:`handleTouchEnd`,value:function(e){this.caretEventHandler(e)}},{key:`handleSelect`,value:function(e){this.caretEventHandler(e)}},{key:`handleSelectionChange`,value:function(e){navigator.userAgent.includes(`Firefox`)||this.caretEventHandler(e)}},{key:`caretEventHandler`,value:function(e){var t,n=this;e.target.tagName&&(t=e.target.tagName.toLowerCase()),this.dispatch((function(r){var i=e.target===r.keyboardDOM||e.target&&r.keyboardDOM.contains(e.target);if(n.options.syncInstanceInputs&&Array.isArray(e.path)&&(i=e.path.some((function(e){var t;return e==null||(t=e.hasAttribute)==null?void 0:t.call(e,`data-skInstance`)}))),(t===`textarea`||t===`input`&&[`text`,`search`,`url`,`tel`,`password`].includes(e.target.type))&&!r.options.disableCaretPositioning){var a=e.target.selectionStart,o=e.target.selectionEnd;r.options.rtl&&(a=r.utilities.getRtlOffset(a,r.getInput()),o=r.utilities.getRtlOffset(o,r.getInput())),r.setCaretPosition(a,o),r.activeInputElement=e.target,r.options.debug&&console.log(`Caret at: `,r.getCaretPosition(),r.getCaretPositionEnd(),e&&e.target.tagName.toLowerCase(),`(${r.keyboardDOMClass})`,e?.type)}else !r.options.disableCaretPositioning&&i||e?.type===`selectionchange`||(r.setCaretPosition(null),r.activeInputElement=null,r.options.debug&&console.log(`Caret position reset due to "${e?.type}" event`,e))}))}},{key:`recurseButtons`,value:function(e){var t=this;e&&Object.keys(this.buttonElements).forEach((function(n){return t.buttonElements[n].forEach(e)}))}},{key:`destroy`,value:function(){this.options.debug&&console.log(`Destroying simple-keyboard instance: ${this.currentInstanceName}`);var e=this.options.physicalKeyboardHighlightPreventDefault,t=e!==void 0&&e;document.removeEventListener(`keyup`,this.handleKeyUp,t),document.removeEventListener(`keydown`,this.handleKeyDown,t),document.removeEventListener(`mouseup`,this.handleMouseUp),document.removeEventListener(`touchend`,this.handleTouchEnd),document.removeEventListener(`select`,this.handleSelect),this.options.updateCaretOnSelectionChange&&document.removeEventListener(`selectionchange`,this.handleSelectionChange),document.onpointerup=null,document.ontouchend=null,document.ontouchcancel=null,document.onmouseup=null,this.recurseButtons((function(e){e&&=(e.onpointerdown=null,e.onpointerup=null,e.onpointercancel=null,e.ontouchstart=null,e.ontouchend=null,e.ontouchcancel=null,e.onclick=null,e.onmousedown=null,e.onmouseup=null,e.remove(),null)})),this.keyboardDOM.onpointerdown=null,this.keyboardDOM.ontouchstart=null,this.keyboardDOM.onmousedown=null,this.resetRows(),this.candidateBox&&=(this.candidateBox.destroy(),null),this.activeInputElement=null,this.keyboardDOM.removeAttribute(`data-skInstance`),this.keyboardDOM.innerHTML=``,window.SimpleKeyboardInstances[this.currentInstanceName]=null,delete window.SimpleKeyboardInstances[this.currentInstanceName],this.initialized=!1}},{key:`getButtonThemeClasses`,value:function(e){var t=this.options.buttonTheme,n=[];return Array.isArray(t)&&t.forEach((function(t){if(t&&t.class&&typeof t.class==`string`&&t.buttons&&typeof t.buttons==`string`){var r=t.class.split(` `);t.buttons.split(` `).includes(e)&&(n=[].concat(C(n),C(r)))}else console.warn(`Incorrect "buttonTheme". Please check the documentation.`,t)})),n}},{key:`setDOMButtonAttributes`,value:function(e,t){var n=this.options.buttonAttributes;Array.isArray(n)&&n.forEach((function(n){n.attribute&&typeof n.attribute==`string`&&n.value&&typeof n.value==`string`?n.buttons&&typeof n.buttons==`string`?n.buttons.split(` `).includes(e)&&t(n.attribute,n.value):t(n.attribute,n.value):console.warn(`Incorrect "buttonAttributes". Please check the documentation.`,n)}))}},{key:`onTouchDeviceDetected`,value:function(){this.processAutoTouchEvents(),this.disableContextualWindow()}},{key:`disableContextualWindow`,value:function(){window.oncontextmenu=function(e){var t;if((t=e.target.classList)!=null&&t.contains(`hg-button`))return e.preventDefault(),e.stopPropagation(),!1}}},{key:`processAutoTouchEvents`,value:function(){this.options.autoUseTouchEvents&&(this.options.useTouchEvents=!0,this.options.debug&&console.log(`autoUseTouchEvents: Touch device detected, useTouchEvents enabled.`))}},{key:`onInit`,value:function(){this.options.debug&&console.log(`${this.keyboardDOMClass} Initialized`),this.setEventListeners(),typeof this.options.onInit==`function`&&this.options.onInit(this)}},{key:`beforeFirstRender`,value:function(){this.utilities.isTouchDevice()&&this.onTouchDeviceDetected(),typeof this.options.beforeFirstRender==`function`&&this.options.beforeFirstRender(this),this.isFirstKeyboardInstance&&this.utilities.pointerEventsSupported()&&!this.options.useTouchEvents&&!this.options.useMouseEvents&&this.options.debug&&console.log(`Using PointerEvents as it is supported by this browser`),this.options.useTouchEvents&&this.options.debug&&console.log(`useTouchEvents has been enabled. Only touch events will be used.`)}},{key:`beforeRender`,value:function(){typeof this.options.beforeRender==`function`&&this.options.beforeRender(this)}},{key:`onRender`,value:function(){typeof this.options.onRender==`function`&&this.options.onRender(this)}},{key:`onModulesLoaded`,value:function(){typeof this.options.onModulesLoaded==`function`&&this.options.onModulesLoaded(this)}},{key:`loadModules`,value:function(){var e=this;Array.isArray(this.options.modules)&&(this.options.modules.forEach((function(t){var n=e.utilities.isConstructor(t)?new t(e):t(e);n.init&&n.init(e)})),this.keyboardPluginClasses=`modules-loaded`,this.render(),this.onModulesLoaded())}},{key:`getModuleProp`,value:function(e,t){return!!this.modules[e]&&this.modules[e][t]}},{key:`getModulesList`,value:function(){return Object.keys(this.modules)}},{key:`parseRowDOMContainers`,value:function(e,t,n,r){var i=this,a=Array.from(e.children),o=0;return a.length&&n.forEach((function(n,s){var c=r[s];if(!(c&&c>n))return!1;var l=n-o,u=c-o,d=document.createElement(`div`);d.className+=`hg-button-container`;var f=`${i.options.layoutName}-r${t}c${s}`;d.setAttribute(`data-skUID`,f);var p=a.splice(l,u-l+1);o+=u-l,p.forEach((function(e){return d.appendChild(e)})),a.splice(l,0,d),e.innerHTML=``,a.forEach((function(t){return e.appendChild(t)})),i.options.debug&&console.log(`rowDOMContainer`,p,l,u,o+1)})),e}},{key:`render`,value:function(){var e=this;this.resetRows(),this.initialized||this.beforeFirstRender(),this.beforeRender();var t=`hg-layout-${this.options.layoutName}`,n=this.options.layout||{default:["` 1 2 3 4 5 6 7 8 9 0 - = {bksp}",`{tab} q w e r t y u i o p [ ] \\`,`{lock} a s d f g h j k l ; ' {enter}`,`{shift} z x c v b n m , . / {shift}`,`.com @ {space}`],shift:[`~ ! @ # $ % ^ & * ( ) _ + {bksp}`,`{tab} Q W E R T Y U I O P { } |`,`{lock} A S D F G H J K L : " {enter}`,`{shift} Z X C V B N M < > ? {shift}`,`.com @ {space}`]},r=this.options.useTouchEvents||!1,i=r?`hg-touch-events`:``,a=this.options.useMouseEvents||!1,o=this.options.disableRowButtonContainers;this.keyboardDOM.className=this.getKeyboardClassString(this.options.theme,t,this.keyboardPluginClasses,i),this.keyboardDOM.setAttribute(`data-skInstance`,this.currentInstanceName),this.keyboardRowsDOM=document.createElement(`div`),this.keyboardRowsDOM.className=`hg-rows`,n[this.options.layoutName||this.defaultName].forEach((function(t,n){var i=t.split(` `);e.options.excludeFromLayout&&e.options.excludeFromLayout[e.options.layoutName||e.defaultName]&&(i=i.filter((function(t){return e.options.excludeFromLayout&&!e.options.excludeFromLayout[e.options.layoutName||e.defaultName].includes(t)})));var s=document.createElement(`div`);s.className+=`hg-row`;var c=[],l=[];i.forEach((function(t,i){var u,d=!o&&typeof t==`string`&&t.length>1&&t.indexOf(`[`)===0,f=!o&&typeof t==`string`&&t.length>1&&t.indexOf(`]`)===t.length-1;d&&(c.push(i),t=t.replace(/\[/g,``)),f&&(l.push(i),t=t.replace(/\]/g,``));var p=e.utilities.getButtonClass(t),m=e.utilities.getButtonDisplayName(t,e.options.display,e.options.mergeDisplay),h=e.options.useButtonTag?`button`:`div`,g=document.createElement(h);g.className+=`hg-button ${p}`,(u=g.classList).add.apply(u,C(e.getButtonThemeClasses(t))),e.setDOMButtonAttributes(t,(function(e,t){g.setAttribute(e,t)})),e.activeButtonClass=`hg-activeButton`,!e.utilities.pointerEventsSupported()||r||a?r?(g.ontouchstart=function(n){e.handleButtonClicked(t,n),e.handleButtonMouseDown(t,n)},g.ontouchend=function(n){e.handleButtonMouseUp(t,n)},g.ontouchcancel=function(n){e.handleButtonMouseUp(t,n)}):(g.onclick=function(n){e.setMouseHold(!1),typeof e.options.onKeyReleased==`function`||e.options.useMouseEvents&&e.options.clickOnMouseDown||e.handleButtonClicked(t,n)},g.onmousedown=function(n){(typeof e.options.onKeyReleased==`function`||e.options.useMouseEvents&&e.options.clickOnMouseDown)&&!e.isMouseHold&&e.handleButtonClicked(t,n),e.handleButtonMouseDown(t,n)},g.onmouseup=function(n){e.handleButtonMouseUp(t,n)}):(g.onpointerdown=function(n){e.handleButtonClicked(t,n),e.handleButtonMouseDown(t,n)},g.onpointerup=function(n){e.handleButtonMouseUp(t,n)},g.onpointercancel=function(n){e.handleButtonMouseUp(t,n)}),g.setAttribute(`data-skBtn`,t);var _=`${e.options.layoutName}-r${n}b${i}`;g.setAttribute(`data-skBtnUID`,_);var v=document.createElement(`span`);v.innerHTML=m,g.appendChild(v),e.buttonElements[t]||(e.buttonElements[t]=[]),e.buttonElements[t].push(g),s.appendChild(g)})),s=e.parseRowDOMContainers(s,n,c,l),e.keyboardRowsDOM.appendChild(s)})),this.keyboardDOM.appendChild(this.keyboardRowsDOM),this.onRender(),this.initialized||(this.initialized=!0,!this.utilities.pointerEventsSupported()||r||a?r?(document.ontouchend=function(t){return e.handleButtonMouseUp(void 0,t)},document.ontouchcancel=function(t){return e.handleButtonMouseUp(void 0,t)},this.keyboardDOM.ontouchstart=function(t){return e.handleKeyboardContainerMouseDown(t)}):r||(document.onmouseup=function(t){return e.handleButtonMouseUp(void 0,t)},this.keyboardDOM.onmousedown=function(t){return e.handleKeyboardContainerMouseDown(t)}):(document.onpointerup=function(t){return e.handleButtonMouseUp(void 0,t)},this.keyboardDOM.onpointerdown=function(t){return e.handleKeyboardContainerMouseDown(t)}),this.onInit())}}],t&&D(e.prototype,t),n&&D(e,n),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t,n}(),j=A;return r}()},442:function(t){t.exports=e}},n={};function r(e){var i=n[e];if(i!==void 0)return i.exports;var a=n[e]={exports:{}};return t[e].call(a.exports,a,a.exports,r),a.exports}r.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return r.d(t,{a:t}),t},r.d=function(e,t){for(var n in t)r.o(t,n)&&!r.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},r.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},r.r=function(e){typeof Symbol<`u`&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:`Module`}),Object.defineProperty(e,"__esModule",{value:!0})};var i={};return function(){r.r(i),r.d(i,{KeyboardReact:function(){return u},default:function(){return d}}),r(981);var e=r(442),t=r(548),n=r.n(t);function a(e){return a=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},a(e)}function o(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function s(e){for(var t=1;t{e?.(t)},[t,e]);let d=(0,y.useCallback)(e=>{if(a.current)return;let t=e.target;if(!t.closest(`[data-vkb="false"]`)){if(t instanceof HTMLInputElement){if(!VQe.has(t.type))return}else if(!(t instanceof HTMLTextAreaElement))return;c.current=t,n(!0),s(`default`),l.current?.setInput?.(c.current.value),setTimeout(()=>{(t.closest(`.bg-zinc-800, .rounded-lg, [data-vkb-group]`)??t).scrollIntoView({behavior:`smooth`,block:`nearest`})},100)}},[]),f=(0,y.useCallback)(()=>{setTimeout(()=>{let e=document.activeElement;e&&(u.current?.contains(e)||e===c.current)||(n(!1),c.current=null)},150)},[]);(0,y.useEffect)(()=>(document.addEventListener(`focusin`,d),document.addEventListener(`focusout`,f),()=>{document.removeEventListener(`focusin`,d),document.removeEventListener(`focusout`,f)}),[d,f]);let p=(0,y.useCallback)(()=>{a.current=!0,i(!0),c.current?.blur(),c.current=null,setTimeout(()=>{n(!1),i(!1),a.current=!1},400)},[]),m=(0,y.useCallback)(e=>{let t=c.current;if(t){if(e===`{shift}`){s(e=>e==="default"?`shift`:`default`);return}if(e===`{lock}`){s(e=>e==="default"?`shift`:`default`);return}if(e===`{close}`){p();return}e===`{bksp}`?W9(t,t.value.slice(0,-1)):e===`{space}`?W9(t,t.value+` `):(W9(t,t.value+e),o===`shift`&&s(`default`)),t.focus(),l.current?.setInput?.(t.value)}},[o,p]);return t?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`div`,{className:`fixed inset-0 z-[9998] bg-transparent`,onMouseDown:e=>{e.preventDefault(),e.stopPropagation(),r||p()},onTouchStart:e=>{e.preventDefault(),e.stopPropagation(),r||p()},onClick:e=>{e.preventDefault(),e.stopPropagation()}}),!r&&(0,K.jsx)(`div`,{ref:u,className:`relative z-[9999] shrink-0`,onMouseDown:e=>e.preventDefault(),onTouchStart:e=>{e.target.closest(`.hg-button`)||e.preventDefault()},children:(0,K.jsx)(BQe.default,{keyboardRef:e=>{l.current=e},layoutName:o,onKeyPress:m,theme:`simple-keyboard vkb-theme`,layout:{default:[`1 2 3 4 5 6 7 8 9 0 {bksp}`,`q w e r t y u i o p`,`{lock} a s d f g h j k l`,`{shift} z x c v b n m . @`,`{space} {close}`],shift:[`! @ # $ % ^ & * ( ) {bksp}`,`Q W E R T Y U I O P`,`{lock} A S D F G H J K L`,`{shift} Z X C V B N M , _`,`{space} {close}`]},display:{"{bksp}":`⌫`,"{close}":`✕ Close`,"{shift}":`⇧`,"{lock}":`⇪`,"{space}":` `}})})]}):null}function UQe(){of();let[e,t]=(0,y.useState)(null),[n,r]=(0,y.useState)(null),[i,a]=(0,y.useState)(100),{i18n:o}=W(),s=$n(),c=Xn(),l=zQe(),{setViewportSuppressed:u}=kd();(0,y.useEffect)(()=>(u(!0),()=>u(!1)),[u]);let{data:d}=q({queryKey:[`settings`],queryFn:Q.getSettings});(0,y.useEffect)(()=>{d?.language&&d.language!==o.language&&o.changeLanguage(d.language)},[d?.language,o]);let{data:f=[]}=q({queryKey:[`spoolbuddy-devices`],queryFn:()=>ud.getDevices(),refetchInterval:3e4}),p=f[0],m=l.deviceOnline||!!p?.online,h=(0,y.useMemo)(()=>({...l,deviceOnline:m}),[l,m]),g=(0,y.useRef)(!1);(0,y.useEffect)(()=>{p&&!g.current&&(a(p.display_brightness),g.current=!0)},[p]),(0,y.useEffect)(()=>{let e=document.documentElement,t=e.classList.contains(`dark`);return e.classList.add(`dark`),()=>{t||e.classList.remove(`dark`)}},[]);let{data:_}=q({queryKey:[`spoolbuddy-update-check`,p?.device_id],queryFn:()=>p?ud.checkDaemonUpdate(p.device_id):Promise.resolve(null),enabled:!!p,refetchInterval:300*1e3,staleTime:0}),v=(0,y.useRef)(null);(0,y.useEffect)(()=>{if(!m){let e=`SpoolBuddy device disconnected`;r({type:`warning`,message:e}),v.current=e}else if(_?.update_available&&_.latest_version){let e=`Update available: v${_.latest_version}`;r({type:`info`,message:e}),v.current=e}else v.current&&=(r(null),null)},[m,_?.update_available,_?.latest_version]);let b=!!(l.matchedSpool||l.unknownTagUid||l.unknownTrayUuid),x=(0,y.useRef)(!1);(0,y.useEffect)(()=>{b&&!x.current&&c.pathname!==`/spoolbuddy`&&s(`/spoolbuddy`),x.current=b},[b,c.pathname,s]);let{data:S=[]}=q({queryKey:[`printers`],queryFn:()=>Q.getPrinters()}),C=go({queries:S.map(e=>({queryKey:[`printerStatus`,e.id],queryFn:()=>Q.getPrinterStatus(e.id),refetchInterval:1e4,select:e=>({connected:e?.connected})}))}),w=(0,y.useMemo)(()=>S.filter((e,t)=>C[t]?.data?.connected),[S,C]),T=(0,y.useRef)(null),E=(0,y.useRef)(!1),D=(0,y.useRef)(null),O=(0,y.useCallback)(e=>{T.current={x:e.touches[0].clientX,y:e.touches[0].clientY},E.current=!1},[]),k=(0,y.useCallback)(n=>{if(!T.current)return;let r=n.changedTouches[0].clientX-T.current.x,i=n.changedTouches[0].clientY-T.current.y,a=T.current.y;if(T.current=null,E.current=!1,i>=50&&Math.abs(i)>Math.abs(r)&&a<120){N(!0);return}if(w.length<2||Math.abs(r)<50||Math.abs(i)>Math.abs(r))return;let o=w.findIndex(t=>t.id===e);t(w[r<0?(o+1)%w.length:(o-1+w.length)%w.length].id)},[w,e,t]);(0,y.useEffect)(()=>{let e=D.current;if(!e)return;let t=e=>{if(!T.current)return;let t=Math.abs(e.touches[0].clientX-T.current.x),n=Math.abs(e.touches[0].clientY-T.current.y);if(E.current){e.preventDefault();return}t>10&&t>n&&(E.current=!0,e.preventDefault())};return e.addEventListener(`touchmove`,t,{passive:!1}),()=>e.removeEventListener(`touchmove`,t)},[]);let[A,j]=(0,y.useState)(!1),[M,N]=(0,y.useState)(!1);return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsxs)(`div`,{ref:D,"data-spoolbuddy-kiosk":!0,className:`w-screen h-screen bg-bambu-dark text-white flex flex-col overflow-hidden`,style:{...i<100?{filter:`brightness(${i/100})`}:void 0,overscrollBehaviorX:`none`},onTouchStart:O,onTouchEnd:k,children:[(0,K.jsx)(`button`,{onClick:()=>N(!0),className:`w-full h-1.5 bg-bambu-dark-secondary flex justify-center items-center shrink-0 touch-none`,"aria-label":`Open quick menu`,children:(0,K.jsx)(`div`,{className:`w-8 h-0.5 rounded-full bg-zinc-600`})}),(0,K.jsx)(MQe,{selectedPrinterId:e,onPrinterChange:t,deviceOnline:m}),(0,K.jsx)(`main`,{className:`flex-1 overflow-y-auto`,children:(0,K.jsx)(kr,{context:{selectedPrinterId:e,setSelectedPrinterId:t,sbState:h,setAlert:r,displayBrightness:i,setDisplayBrightness:a}})}),!A&&(0,K.jsx)(FQe,{alert:n}),!A&&(0,K.jsx)(PQe,{}),(0,K.jsx)(HQe,{onVisibilityChange:j})]}),(0,K.jsx)(IQe,{isOpen:M,onClose:()=>N(!1),deviceId:p?.device_id??null,deviceOnline:m})]})}function G9({color:e,isEmpty:t,size:n=32}){return t?(0,K.jsx)(`div`,{className:`rounded-full border-2 border-dashed border-zinc-500 flex items-center justify-center`,style:{width:n,height:n},children:(0,K.jsx)(`div`,{className:`w-2 h-2 rounded-full bg-zinc-600`})}):(0,K.jsxs)(`svg`,{width:n,height:n,viewBox:`0 0 32 32`,children:[(0,K.jsx)(`circle`,{cx:`16`,cy:`16`,r:`14`,fill:e,stroke:`white`,strokeWidth:`1.5`,strokeOpacity:`0.7`}),(0,K.jsx)(`circle`,{cx:`16`,cy:`16`,r:`11`,fill:e,style:{filter:`brightness(0.85)`}})]})}var WQe=`spoolbuddy-default-core-weight`;function GQe(){try{let e=localStorage.getItem(WQe);if(e){let t=parseInt(e,10);if(t>=0&&t<=500)return t}}catch{}return 250}function KQe({spool:e,scaleWeight:t,onClose:n,onSyncWeight:r,onAssignToAms:i,isAssigned:a,onUnassignFromAms:o}){let{t:s}=W(),[c,l]=(0,y.useState)(!1),[u,d]=(0,y.useState)(!1),f=tf(e.rgba),p=e.core_weight&&e.core_weight>0?e.core_weight:GQe(),m=t===null?null:Math.round(Math.max(0,t)),h=m===null?null:Math.round(Math.max(0,m-p)),g=Math.round(e.label_weight||1e3),_=h===null?null:Math.min(100,Math.round(h/g*100)),v=_===null?`#808080`:_>50?`#22c55e`:_>20?`#eab308`:`#ef4444`,b=Math.max(0,(e.label_weight||0)-(e.weight_used||0))+p,x=m===null?null:m-b,S=x===null?null:Math.abs(x)<=50,C=async()=>{if(t!==null){l(!0);try{await ud.updateSpoolWeight(e.id,Math.round(t)),d(!0),r?.(),setTimeout(()=>d(!1),3e3)}catch(e){console.error(`Failed to sync weight:`,e)}finally{l(!1)}}};return(0,K.jsxs)(`div`,{className:`flex flex-col items-center space-y-4 max-w-md`,children:[(0,K.jsxs)(`div`,{className:`flex items-start gap-5`,children:[(0,K.jsxs)(`div`,{className:`relative shrink-0`,children:[(0,K.jsx)(G9,{color:f,isEmpty:!1,size:100}),_!==null&&(0,K.jsxs)(`div`,{className:`absolute -bottom-2 -right-2 px-2 py-0.5 rounded-full text-xs font-bold text-white shadow-lg`,style:{backgroundColor:v},children:[_,`%`]})]}),(0,K.jsxs)(`div`,{className:`flex-1 min-w-0 pt-1`,children:[(0,K.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,K.jsx)(`h3`,{className:`text-lg font-semibold text-zinc-100`,children:e.color_name||`Unknown color`}),(0,K.jsxs)(`span`,{className:`text-xs font-mono text-zinc-500 shrink-0`,children:[`#`,e.id]})]}),(0,K.jsxs)(`p`,{className:`text-sm text-zinc-400`,children:[e.brand,` • `,e.material,e.subtype&&` ${e.subtype}`]}),h!==null&&(0,K.jsxs)(`div`,{className:`mt-3`,children:[(0,K.jsxs)(`div`,{className:`flex items-baseline gap-2`,children:[(0,K.jsxs)(`span`,{className:`text-3xl font-bold font-mono text-zinc-100`,children:[h,`g`]}),(0,K.jsxs)(`span`,{className:`text-sm text-zinc-500`,children:[`/ `,g,`g`]})]}),(0,K.jsx)(`p`,{className:`text-xs text-zinc-500 mt-0.5`,children:s(`spoolbuddy.spool.remaining`,`Remaining`)}),(0,K.jsx)(`div`,{className:`mt-2 max-w-xs`,children:(0,K.jsx)(`div`,{className:`h-2 bg-zinc-700 rounded-full overflow-hidden`,children:(0,K.jsx)(`div`,{className:`h-full rounded-full transition-all duration-500`,style:{width:`${_}%`,backgroundColor:v}})})})]})]})]}),(0,K.jsxs)(`div`,{className:`grid grid-cols-2 gap-x-6 gap-y-2 text-sm bg-zinc-800 rounded-lg p-4 w-full`,children:[(0,K.jsxs)(`div`,{className:`flex justify-between`,children:[(0,K.jsx)(`span`,{className:`text-zinc-500`,children:s(`spoolbuddy.dashboard.grossWeight`,`Gross weight`)}),(0,K.jsx)(`span`,{className:`font-mono text-zinc-300`,children:m===null?`—`:`${m}g`})]}),(0,K.jsxs)(`div`,{className:`flex justify-between`,children:[(0,K.jsx)(`span`,{className:`text-zinc-500`,children:s(`spoolbuddy.spool.coreWeight`,`Core`)}),(0,K.jsxs)(`span`,{className:`font-mono text-zinc-300`,children:[p,`g`]})]}),(0,K.jsxs)(`div`,{className:`flex justify-between`,children:[(0,K.jsx)(`span`,{className:`text-zinc-500`,children:s(`spoolbuddy.dashboard.spoolSize`,`Spool size`)}),(0,K.jsxs)(`span`,{className:`font-mono text-zinc-300`,children:[g,`g`]})]}),(0,K.jsxs)(`div`,{className:`flex justify-between items-center`,children:[(0,K.jsx)(`span`,{className:`text-zinc-500`,children:s(`spoolbuddy.spool.scaleWeight`,`Scale`)}),m===null?(0,K.jsx)(`span`,{className:`text-zinc-500`,children:`—`}):(0,K.jsxs)(`span`,{className:`flex items-center gap-1 font-mono ${S?`text-green-500`:`text-yellow-500`}`,children:[m,`g`,S?(0,K.jsx)(ts,{className:`w-3.5 h-3.5`}):(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(wu,{className:`w-3.5 h-3.5`}),(0,K.jsx)(`button`,{onClick:C,className:`p-1 hover:bg-green-500/20 rounded transition-colors text-green-500`,title:s(`spoolbuddy.dashboard.syncWeight`,`Sync Weight`),children:(0,K.jsx)(kl,{className:`w-4 h-4`})})]})]})]}),(0,K.jsxs)(`div`,{className:`flex justify-between items-center`,children:[(0,K.jsx)(`span`,{className:`text-zinc-500`,children:s(`spoolbuddy.dashboard.tagId`,`Tag`)}),(0,K.jsx)(`span`,{className:`font-mono text-xs text-zinc-400 truncate max-w-[120px]`,title:e.tag_uid||``,children:e.tag_uid?e.tag_uid.slice(-8):`—`})]})]}),(0,K.jsxs)(`div`,{className:`flex gap-2 justify-center`,children:[i&&(0,K.jsx)(`button`,{onClick:a?void 0:i,disabled:!!a,className:`px-5 py-2.5 rounded-lg text-sm font-medium bg-green-600 text-white hover:bg-green-700 transition-colors min-h-[44px] disabled:opacity-50 disabled:cursor-not-allowed`,children:s(`spoolbuddy.modal.assignToAms`,`Assign to AMS`)}),o&&(0,K.jsxs)(`button`,{onClick:o,className:`px-5 py-2.5 rounded-lg text-sm font-medium bg-red-600/20 text-red-400 hover:bg-red-600/30 transition-colors min-h-[44px]`,children:[(0,K.jsx)(Du,{className:`w-4 h-4 inline mr-1`}),s(`inventory.unassignSpool`)]}),(0,K.jsx)(`button`,{onClick:C,disabled:t===null||c,className:`px-5 py-2.5 rounded-lg text-sm font-medium transition-colors min-h-[44px] ${u?`bg-green-600/20 text-green-400`:i?`bg-zinc-700 text-zinc-300 hover:bg-zinc-600 disabled:opacity-40 disabled:cursor-not-allowed`:`bg-green-600 text-white hover:bg-green-700 disabled:opacity-40 disabled:cursor-not-allowed`}`,children:c?`...`:u?s(`spoolbuddy.dashboard.weightSynced`,`Synced!`):s(`spoolbuddy.dashboard.syncWeight`,`Sync Weight`)}),n&&(0,K.jsx)(`button`,{onClick:n,className:`px-5 py-2.5 rounded-lg text-sm font-medium bg-zinc-700 text-zinc-300 hover:bg-zinc-600 transition-colors min-h-[44px]`,children:s(`spoolbuddy.dashboard.close`,`Close`)})]})]})}function qQe({tagUid:e,scaleWeight:t,coreWeight:n,onLinkSpool:r,onAddToInventory:i,onClose:a}){let{t:o}=W(),s=n??GQe(),c=t===null?null:Math.round(Math.max(0,t)),l=c===null?null:Math.round(Math.max(0,c-s));return(0,K.jsxs)(`div`,{className:`flex flex-col items-center text-center space-y-5`,children:[(0,K.jsx)(`div`,{className:`w-20 h-20 rounded-2xl bg-green-500/15 flex items-center justify-center`,children:(0,K.jsx)(`svg`,{className:`w-10 h-10 text-green-500`,fill:`none`,viewBox:`0 0 24 24`,stroke:`currentColor`,children:(0,K.jsx)(`path`,{strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:`2`,d:`M7 7h.01M7 3h5c.512 0 1.024.195 1.414.586l7 7a2 2 0 010 2.828l-7 7a2 2 0 01-2.828 0l-7-7A2 2 0 013 12V7a4 4 0 014-4z`})})}),(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`h3`,{className:`text-lg font-semibold text-zinc-100`,children:o(`spoolbuddy.dashboard.newTag`,`New Tag Detected`)}),(0,K.jsx)(`p`,{className:`text-sm text-zinc-500 font-mono mt-1`,children:e})]}),c!==null&&(0,K.jsxs)(`div`,{className:`text-sm text-zinc-400`,children:[(0,K.jsxs)(`span`,{className:`font-mono font-semibold`,children:[c,`g`]}),` `,o(`spoolbuddy.dashboard.onScale`,`on scale`),l!==null&&l>0&&(0,K.jsxs)(`span`,{className:`text-zinc-500`,children:[` • ~`,l,`g filament`]})]}),(0,K.jsxs)(`div`,{className:`flex flex-wrap gap-2 justify-center`,children:[i&&(0,K.jsx)(`button`,{onClick:i,className:`px-5 py-2.5 rounded-lg text-sm font-medium bg-green-600 text-white hover:bg-green-700 transition-colors min-h-[44px]`,children:o(`spoolbuddy.modal.addToInventory`,`Add to Inventory`)}),r&&(0,K.jsxs)(`button`,{onClick:r,className:`px-5 py-2.5 rounded-lg text-sm font-medium bg-zinc-700 text-zinc-300 hover:bg-zinc-600 transition-colors min-h-[44px]`,children:[(0,K.jsx)(`svg`,{className:`w-4 h-4 inline-block mr-1.5 -mt-0.5`,fill:`none`,viewBox:`0 0 24 24`,stroke:`currentColor`,children:(0,K.jsx)(`path`,{strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:`2`,d:`M13.828 10.172a4 4 0 00-5.656 0l-4 4a4 4 0 105.656 5.656l1.102-1.101m-.758-4.899a4 4 0 005.656 0l4-4a4 4 0 00-5.656-5.656l-1.1 1.1`})}),o(`inventory.assignSpool`,`Assign Spool`)]}),a&&(0,K.jsx)(`button`,{onClick:a,className:`px-5 py-2.5 rounded-lg text-sm font-medium bg-zinc-700 text-zinc-300 hover:bg-zinc-600 transition-colors min-h-[44px]`,children:o(`spoolbuddy.dashboard.close`,`Close`)})]})]})}function JQe(e){return e?`#${e.slice(0,6)}`:`#808080`}function YQe(e){return!e.tray_type||e.tray_type===``}function XQe(e){if(e.tray_type)return null;let t=e.state??null;return t===9||t===10?`physical`:`reset`}function ZQe(e){return e<=3?`AMS ${String.fromCharCode(65+e)}`:e>=128&&e<=135?`AMS HT ${String.fromCharCode(65+e-128)}`:`AMS ${e}`}function QQe({className:e}){return(0,K.jsx)(`svg`,{className:e,viewBox:`0 0 36 54`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,children:(0,K.jsx)(`path`,{d:`M17.8131 0.00538C18.4463 -0.15091 20.3648 3.14642 20.8264 3.84781C25.4187 10.816 35.3089 26.9368 35.9383 34.8694C37.4182 53.5822 11.882 61.3357 2.53721 45.3789C-1.73471 38.0791 0.016 32.2049 3.178 25.0232C6.99221 16.3662 12.6411 7.90372 17.8131 0.00538ZM18.3738 7.24807L17.5881 7.48441C14.4452 12.9431 10.917 18.2341 8.19369 23.9368C4.6808 31.29 1.18317 38.5479 7.69403 45.5657C17.3058 55.9228 34.9847 46.8808 31.4604 32.8681C29.2558 24.0969 22.4207 15.2913 18.3776 7.24807H18.3738Z`,fill:`#C3C2C1`})})}function $Qe({className:e}){return(0,K.jsxs)(`svg`,{className:e,viewBox:`0 0 35 53`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,children:[(0,K.jsx)(`path`,{d:`M17.3165 0.0038C17.932 -0.14959 19.7971 3.08645 20.2458 3.77481C24.7103 10.6135 34.3251 26.4346 34.937 34.2198C36.3757 52.5848 11.5505 60.1942 2.46584 44.534C-1.68714 37.3735 0.0148 31.6085 3.08879 24.5603C6.79681 16.0605 12.2884 7.75907 17.3165 0.0038ZM17.8615 7.11561L17.0977 7.34755C14.0423 12.7048 10.6124 17.8974 7.96483 23.4941C4.54975 30.7107 1.14949 37.8337 7.47908 44.721C16.8233 54.8856 34.01 46.0117 30.5838 32.2595C28.4405 23.6512 21.7957 15.0093 17.8652 7.11561H17.8615Z`,fill:`#C3C2C1`}),(0,K.jsx)(`path`,{d:`M5.03547 30.112C9.64453 30.4936 11.632 35.7985 16.4154 35.791C19.6339 35.7873 20.2161 33.2283 22.3853 31.6197C31.6776 24.7286 33.5835 37.4894 27.9881 44.4254C18.1878 56.5653 -1.16063 44.6013 5.03917 30.1158L5.03547 30.112Z`,fill:`#1F8FEB`})]})}function e$e({className:e}){return(0,K.jsxs)(`svg`,{className:e,viewBox:`0 0 36 54`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,children:[(0,K.jsx)(`path`,{d:`M17.9625 4.48059L4.77216 26.3154L2.08228 40.2175L10.0224 50.8414H23.1594L33.3246 42.1693V30.2455L17.9625 4.48059Z`,fill:`#1F8FEB`}),(0,K.jsx)(`path`,{d:`M17.7948 0.00538C18.4273 -0.15091 20.3438 3.14642 20.8048 3.84781C25.3921 10.816 35.2715 26.9368 35.9001 34.8694C37.3784 53.5822 11.8702 61.3357 2.53562 45.3789C-1.73163 38.0829 0.0134 32.2087 3.1757 25.027C6.98574 16.3662 12.6284 7.90372 17.7948 0.00538ZM18.3549 7.24807L17.57 7.48441C14.4306 12.9431 10.9063 18.2341 8.1859 23.9368C4.67686 31.29 1.18305 38.5479 7.68679 45.5657C17.2881 55.9228 34.9476 46.8808 31.4271 32.8681C29.2249 24.0969 22.3974 15.2913 18.3587 7.24807H18.3549Z`,fill:`#C3C2C1`})]})}function t$e({className:e}){return(0,K.jsxs)(`svg`,{className:e,viewBox:`0 0 12 20`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,children:[(0,K.jsx)(`path`,{d:`M6 0.5C4.6 0.5 3.5 1.6 3.5 3V12.1C2.6 12.8 2 13.9 2 15C2 17.2 3.8 19 6 19C8.2 19 10 17.2 10 15C10 13.9 9.4 12.8 8.5 12.1V3C8.5 1.6 7.4 0.5 6 0.5Z`,stroke:`#C3C2C1`,strokeWidth:`1`,fill:`none`}),(0,K.jsx)(`circle`,{cx:`6`,cy:`15`,r:`2.5`,stroke:`#C3C2C1`,strokeWidth:`1`,fill:`none`})]})}function n$e({className:e}){return(0,K.jsxs)(`svg`,{className:e,viewBox:`0 0 12 20`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,children:[(0,K.jsx)(`rect`,{x:`4.5`,y:`8`,width:`3`,height:`4.5`,fill:`#d4a017`,rx:`0.5`}),(0,K.jsx)(`circle`,{cx:`6`,cy:`15`,r:`2`,fill:`#d4a017`}),(0,K.jsx)(`path`,{d:`M6 0.5C4.6 0.5 3.5 1.6 3.5 3V12.1C2.6 12.8 2 13.9 2 15C2 17.2 3.8 19 6 19C8.2 19 10 17.2 10 15C10 13.9 9.4 12.8 8.5 12.1V3C8.5 1.6 7.4 0.5 6 0.5Z`,stroke:`#C3C2C1`,strokeWidth:`1`,fill:`none`})]})}function r$e({className:e}){return(0,K.jsxs)(`svg`,{className:e,viewBox:`0 0 12 20`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,children:[(0,K.jsx)(`rect`,{x:`4.5`,y:`3`,width:`3`,height:`9.5`,fill:`#c62828`,rx:`0.5`}),(0,K.jsx)(`circle`,{cx:`6`,cy:`15`,r:`2`,fill:`#c62828`}),(0,K.jsx)(`path`,{d:`M6 0.5C4.6 0.5 3.5 1.6 3.5 3V12.1C2.6 12.8 2 13.9 2 15C2 17.2 3.8 19 6 19C8.2 19 10 17.2 10 15C10 13.9 9.4 12.8 8.5 12.1V3C8.5 1.6 7.4 0.5 6 0.5Z`,stroke:`#C3C2C1`,strokeWidth:`1`,fill:`none`})]})}function i$e({humidity:e,goodThreshold:t=40,fairThreshold:n=60}){let r,i;return e<=t?(r=`#22a352`,i=QQe):e<=n?(r=`#d4a017`,i=$Qe):(r=`#c62828`,i=e$e),(0,K.jsxs)(`div`,{className:`flex items-center gap-0.5`,children:[(0,K.jsx)(i,{className:`w-3 h-3.5`}),(0,K.jsxs)(`span`,{className:`font-medium tabular-nums text-xs`,style:{color:r},children:[e,`%`]})]})}function a$e({temp:e,goodThreshold:t=28,fairThreshold:n=35}){let r,i;return e<=t?(r=`#22a352`,i=t$e):e<=n?(r=`#d4a017`,i=n$e):(r=`#c62828`,i=r$e),(0,K.jsxs)(`div`,{className:`flex items-center gap-0.5`,children:[(0,K.jsx)(i,{className:`w-3 h-3.5`}),(0,K.jsxs)(`span`,{className:`font-medium tabular-nums text-xs`,style:{color:r},children:[e,`°C`]})]})}function K9({side:e}){return(0,K.jsx)(`span`,{className:`inline-flex items-center justify-center w-4 h-4 text-[9px] font-bold rounded`,style:{backgroundColor:`#1a4d2e`,color:`#00ae42`},children:e})}function o$e({tray:e,slotIndex:t,isActive:n,fillOverride:r,spoolmanFill:i,onClick:a}){let o=YQe(e),s=XQe(e),c=JQe(e.tray_color),l=e.remain!==null&&e.remain!==void 0&&e.remain>=0?e.remain:null,u=i??(r===0&&l!==null&&l>0?null:r)??l;return(0,K.jsxs)(`div`,{className:`relative flex flex-col items-center p-2.5 rounded-lg transition-all ${n?`ring-2 ring-bambu-green`:``} ${a?`cursor-pointer hover:bg-white/5`:``}`,onClick:a,title:a?`AMS Slot ${t+1}`:void 0,children:[(0,K.jsxs)(`div`,{className:`relative w-16 h-16 mb-1`,children:[o?(0,K.jsx)(`div`,{className:`w-full h-full rounded-full border-2 border-dashed border-gray-500 flex items-center justify-center`,children:(0,K.jsx)(`div`,{className:`w-3 h-3 rounded-full bg-gray-600`})}):(0,K.jsxs)(`svg`,{viewBox:`0 0 56 56`,className:`w-full h-full`,children:[(0,K.jsx)(`circle`,{cx:`28`,cy:`28`,r:`26`,fill:c}),(0,K.jsx)(`circle`,{cx:`28`,cy:`28`,r:`20`,fill:c,style:{filter:`brightness(0.85)`}}),(0,K.jsx)(`ellipse`,{cx:`20`,cy:`20`,rx:`6`,ry:`4`,fill:`white`,opacity:`0.3`}),(0,K.jsx)(`circle`,{cx:`28`,cy:`28`,r:`8`,fill:`#2d2d2d`}),(0,K.jsx)(`circle`,{cx:`28`,cy:`28`,r:`5`,fill:`#1a1a1a`})]}),n&&(0,K.jsx)(`div`,{className:`absolute -bottom-1 left-1/2 -translate-x-1/2 w-2.5 h-2.5 bg-bambu-green rounded-full`})]}),(0,K.jsx)(`span`,{className:`text-sm text-white/70 truncate max-w-full`,title:s===`reset`?`Spool loaded — slot not configured`:void 0,children:o?s===`reset`?`?`:`Empty`:e.tray_type||`Unknown`}),!o&&u!==null&&u>=0&&(0,K.jsx)(`div`,{className:`w-full h-1 bg-bambu-dark-tertiary rounded-full overflow-hidden mt-1`,children:(0,K.jsx)(`div`,{className:`h-full rounded-full transition-all`,style:{width:`${u}%`,backgroundColor:Kf(u)}})}),(0,K.jsx)(`span`,{className:`absolute top-1 right-1 text-xs text-white/30`,children:t+1})]})}function s$e({unit:e,activeSlot:t,onConfigureSlot:n,isDualNozzle:r,nozzleSide:i,thresholds:a,fillOverrides:o,spoolmanFillOverrides:s}){let c=e.tray||[],l=e.is_ams_ht,u=l?1:4;return(0,K.jsxs)(`div`,{className:`bg-bambu-dark-secondary rounded-lg p-3`,children:[(0,K.jsxs)(`div`,{className:`flex items-center justify-between mb-2`,children:[(0,K.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,K.jsx)(`span`,{className:`text-white font-medium text-base`,children:ZQe(e.id)}),r&&i&&(0,K.jsx)(K9,{side:i})]}),(0,K.jsxs)(`div`,{className:`flex items-center gap-2`,children:[e.temp!=null&&(0,K.jsx)(a$e,{temp:e.temp,goodThreshold:a?.tempGood,fairThreshold:a?.tempFair}),e.humidity!=null&&(0,K.jsx)(i$e,{humidity:e.humidity,goodThreshold:a?.humidityGood,fairThreshold:a?.humidityFair})]})]}),(0,K.jsx)(`div`,{className:`grid ${l?`grid-cols-1 max-w-[100px] mx-auto`:`grid-cols-4`} gap-2`,children:Array.from({length:u}).map((r,i)=>{let a=c[i]||{id:i,tray_color:null,tray_type:``,tray_sub_brands:null,tray_id_name:null,tray_info_idx:null,remain:-1,k:null,cali_idx:null,tag_uid:null,tray_uuid:null,nozzle_temp_min:null,nozzle_temp_max:null};return(0,K.jsx)(o$e,{tray:a,slotIndex:i,isActive:t===i,fillOverride:o?.[`${e.id}-${i}`]??null,spoolmanFill:s?.[`${e.id}-${i}`]??null,onClick:n?()=>n(e.id,i,YQe(a)?null:a):void 0},i)})})]})}function q9(e){return e<=3?`AMS ${String.fromCharCode(65+e)}`:e>=128&&e<=135?`AMS HT ${String.fromCharCode(65+e-128)}`:`AMS ${e}`}function J9(e){return!e.tray_type||e.tray_type===``}function c$e(e){return e?`#${e.slice(0,6)}`:`#808080`}var Y9=e=>(e??``).trim().toUpperCase();function l$e(e,t){let n=Y9(e),r=Y9(t);return!n||!r?`none`:n===r?`exact`:r.includes(n)||n.includes(r)?`partial`:`none`}function u$e(e,t){let n=Y9(e),r=Y9(t);return!n||!r?!1:n===r}function d$e({isOpen:e,onClose:t,spool:n,printerId:r,spoolmanMode:i=!1}){let{t:a}=W(),o=to(),[s,c]=(0,y.useState)(null),[l,u]=(0,y.useState)(null),[d,f]=(0,y.useState)(!1),[p,m]=(0,y.useState)(null),[h,g]=(0,y.useState)(null);(0,y.useEffect)(()=>{e&&(c(null),u(null),f(!1),m(null),g(null))},[e]);let _=(0,y.useCallback)(e=>{e.key===`Escape`&&t()},[t]);(0,y.useEffect)(()=>(e&&document.addEventListener(`keydown`,_),()=>document.removeEventListener(`keydown`,_)),[e,_]);let{data:v}=q({queryKey:[`printerStatus`,r],queryFn:()=>Q.getPrinterStatus(r),enabled:e&&r!==null,refetchInterval:5e3}),{data:b}=q({queryKey:[`printer`,r],queryFn:()=>Q.getPrinter(r),enabled:e&&r!==null}),{data:x}=q({queryKey:[`settings`],queryFn:()=>Q.getSettings(),enabled:e,staleTime:300*1e3}),{data:S}=q({queryKey:[`spool-assignments`,r],queryFn:()=>Q.getAssignments(r),enabled:e&&r!==null,staleTime:30*1e3}),{data:C=[]}=q({queryKey:[`spoolman-slot-assignments`,r],queryFn:()=>Q.getSpoolmanSlotAssignments(r??void 0),enabled:e&&!!i&&r!==null,staleTime:30*1e3}),w=i?C.find(e=>e.spoolman_spool_id===n.id):void 0,T=(0,y.useMemo)(()=>{let e={};if(!S)return e;for(let t of S){let n=t.spool;if(n&&n.label_weight>0&&n.weight_used!=null){let r=Math.round(Math.max(0,n.label_weight-n.weight_used)/n.label_weight*100);e[`${t.ams_id}-${t.tray_id}`]=r}}return e},[S]),E=x?{humidityGood:Number(x.ams_humidity_good)||40,humidityFair:Number(x.ams_humidity_fair)||60,tempGood:Number(x.ams_temp_good)||28,tempFair:Number(x.ams_temp_fair)||35}:void 0,D=v?.connected??!1,O=(0,y.useMemo)(()=>v?.ams??[],[v?.ams]),k=(0,y.useMemo)(()=>O.filter(e=>!e.is_ams_ht),[O]),A=(0,y.useMemo)(()=>O.filter(e=>e.is_ams_ht),[O]),j=(0,y.useMemo)(()=>[...v?.vt_tray??[]].sort((e,t)=>(e.id??254)-(t.id??254)),[v?.vt_tray]),M=b?.nozzle_count===2||v?.temperatures?.nozzle_2!==void 0,N=(0,y.useRef)({});(0,y.useEffect)(()=>{v?.ams_extruder_map&&Object.keys(v.ams_extruder_map).length>0&&(N.current=v.ams_extruder_map)},[v?.ams_extruder_map]);let P=v?.ams_extruder_map&&Object.keys(v.ams_extruder_map).length>0?v.ams_extruder_map:N.current,F=(0,y.useCallback)(e=>{if(!M)return null;let t=P[String(e)],n=e>=128?e-128:e;return(t===void 0?n:t)===1?`L`:`R`},[M,P]),I=J({mutationFn:async({amsId:e,trayId:t})=>{if(!r)throw Error(`No printer selected`);return i?await Q.assignSpoolmanSlot({spoolman_spool_id:n.id,printer_id:r,ams_id:e,tray_id:t}):await Q.assignSpool({spool_id:n.id,printer_id:r,ams_id:e,tray_id:t})},onSuccess:e=>{u(`success`);let n=e&&`pending_config`in e&&e.pending_config;c(n?a(`spoolbuddy.modal.assignPendingInsert`,`Assigned. Slot will configure when you insert the spool.`):a(`spoolbuddy.modal.assignSuccess`,`Assigned!`)),o.invalidateQueries({queryKey:[`slotPresets`]}),o.invalidateQueries({queryKey:[`spoolman-slot-assignments`]}),o.invalidateQueries({queryKey:[`spoolman-slot-assignments-all`]}),setTimeout(()=>t(),n?2500:1500)},onError:e=>{u(`error`),c(e instanceof Error?e.message:a(`spoolbuddy.modal.assignError`,`Failed to assign spool.`))}}),L=I.isPending,R=(0,y.useCallback)((e,t)=>{if(e===254||e===255){let n=e===254?254:254+t;return j.find(e=>(e.id??254)===n)||null}return O.find(t=>t.id===e)?.tray?.find(e=>e.id===t)||null},[O,j]),z=(0,y.useCallback)((e,t)=>e<=3?`${q9(e)} ${a(`ams.slot`,`Slot`)} ${t+1}`:e>=128&&e<=135?q9(e):e===254?a(`printers.extL`,`Ext-L`):M?a(`printers.extR`,`Ext-R`):a(`printers.ext`,`Ext`),[a,M]),B=(0,y.useCallback)((e,t)=>{u(`info`),c(a(`spoolbuddy.modal.assigning`,`Configuring slot...`)),I.mutate({amsId:e,trayId:t})},[I,a]),V=(0,y.useCallback)((e,t)=>{if(!L){if(!x?.disable_filament_warnings){let r=R(e,t);if(r&&!J9(r)){let i=r.tray_sub_brands||r.tray_type||``,a=l$e(n.material,i),o=n.slicer_filament_name||n.slicer_filament,s=r.tray_type||``,c=u$e(o,s);if(a!==`exact`){let r;r=a===`none`&&!c?`material_profile`:a===`partial`&&!c?`partial_profile`:a===`none`?`material`:`partial`;let l=z(e,t);g({amsId:e,trayId:t}),m({type:r,spoolMaterial:n.material||``,trayMaterial:i||``,spoolProfile:o||void 0,trayProfile:s||void 0,location:l}),f(!0);return}}}B(e,t)}},[L,x?.disable_filament_warnings,n,R,z,B]),ee=(0,y.useCallback)(()=>{h&&(f(!1),m(null),B(h.amsId,h.trayId),g(null))},[h,B]),te=(0,y.useMemo)(()=>{let e=[];for(let t of A){let n=t.tray?.[0]||{id:0,tray_color:null,tray_type:``,tray_sub_brands:null,tray_id_name:null,tray_info_idx:null,remain:-1,k:null,cali_idx:null,tag_uid:null,tray_uuid:null,nozzle_temp_min:null,nozzle_temp_max:null},r=T[`${t.id}-0`]??null,i=n.remain!=null&&n.remain>=0?n.remain:null,a=r===0&&i!==null&&i>0?null:r;e.push({key:`ht-${t.id}`,label:q9(t.id),amsId:t.id,trayId:0,tray:n,isEmpty:J9(n),nozzleSide:F(t.id),effectiveFill:a??i})}for(let t of j){let n=t.id??254,r=n-254,i=T[`255-${r}`]??null,o=t.remain!=null&&t.remain>=0?t.remain:null,s=i===0&&o!==null&&o>0?null:i;e.push({key:`ext-${n}`,label:M?n===254?a(`printers.extL`,`Ext-L`):a(`printers.extR`,`Ext-R`):a(`printers.ext`,`Ext`),amsId:255,trayId:r,tray:t,isEmpty:J9(t),nozzleSide:M?n===254?`L`:`R`:null,effectiveFill:s??o})}return e},[A,j,M,a,F,T]);return e?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsxs)(`div`,{className:`fixed inset-0 z-[60] bg-bambu-dark flex flex-col`,children:[(0,K.jsxs)(`div`,{className:`flex items-center justify-between px-5 py-3 border-b border-zinc-800 shrink-0`,children:[(0,K.jsxs)(`div`,{className:`flex items-center gap-3 min-w-0`,children:[(0,K.jsx)(`div`,{className:`w-7 h-7 rounded-full shrink-0`,style:nf(n.rgba)}),(0,K.jsx)(`div`,{className:`min-w-0`,children:(0,K.jsxs)(`h2`,{className:`text-sm font-semibold text-zinc-100 truncate`,children:[a(`spoolbuddy.modal.assignToAmsTitle`,`Assign to AMS`),(0,K.jsxs)(`span`,{className:`font-normal text-zinc-500 ml-2`,children:[n.color_name||`Unknown`,` • `,n.brand,` `,n.material,n.subtype&&` ${n.subtype}`]}),(0,K.jsxs)(`span`,{className:`text-[10px] font-mono text-zinc-500 ml-2 shrink-0`,children:[`#`,n.id]})]})})]}),(0,K.jsx)(`button`,{onClick:t,disabled:L,className:`p-2 rounded-lg text-zinc-500 hover:text-zinc-300 hover:bg-zinc-800 transition-colors shrink-0 disabled:opacity-50`,children:(0,K.jsx)(Hu,{className:`w-5 h-5`})})]}),s&&(0,K.jsxs)(`div`,{className:`mx-5 mt-3 p-3 rounded-lg flex items-center gap-3 border shrink-0 ${l===`info`?`bg-blue-500/10 border-blue-500/40`:l===`success`?`bg-green-500/10 border-green-500/40`:`bg-red-500/10 border-red-500/40`}`,children:[l===`info`&&(0,K.jsx)(X,{className:`w-4 h-4 text-blue-400 animate-spin shrink-0`}),l===`success`&&(0,K.jsx)(ds,{className:`w-4 h-4 text-green-400 shrink-0`}),l===`error`&&(0,K.jsx)(_s,{className:`w-4 h-4 text-red-400 shrink-0`}),(0,K.jsx)(`span`,{className:`text-sm ${l===`info`?`text-blue-300`:l===`success`?`text-green-300`:`text-red-300`}`,children:s})]}),(0,K.jsx)(`div`,{className:`flex-1 flex flex-col gap-3 p-4 min-h-0 overflow-y-auto`,children:!D&&r?(0,K.jsx)(`div`,{className:`flex-1 flex items-center justify-center`,children:(0,K.jsx)(`div`,{className:`text-center text-white/50`,children:(0,K.jsx)(`p`,{className:`text-lg mb-2`,children:a(`spoolbuddy.ams.printerDisconnected`,`Printer disconnected`)})})}):O.length===0&&j.length===0?(0,K.jsx)(`div`,{className:`flex-1 flex items-center justify-center`,children:(0,K.jsxs)(`div`,{className:`text-center text-white/50`,children:[(0,K.jsx)(Ic,{className:`w-12 h-12 mx-auto mb-3 opacity-50`}),(0,K.jsx)(`p`,{className:`text-lg mb-2`,children:a(`spoolbuddy.ams.noData`,`No AMS detected`)}),(0,K.jsx)(`p`,{className:`text-sm`,children:a(`spoolbuddy.ams.connectAms`,`Connect an AMS to see filament slots`)})]})}):(0,K.jsxs)(K.Fragment,{children:[k.length>0&&(0,K.jsx)(`div`,{className:`grid grid-cols-1 md:grid-cols-2 gap-3 flex-1 min-h-0`,children:k.map(e=>(0,K.jsx)(s$e,{unit:e,activeSlot:w?.ams_id===e.id?w.tray_id??null:null,onConfigureSlot:(t,n)=>V(e.id,n),isDualNozzle:M,nozzleSide:F(e.id),thresholds:E,fillOverrides:T},e.id))}),te.length>0&&(0,K.jsx)(`div`,{className:`flex gap-2 shrink-0`,children:te.map(({key:e,label:t,amsId:n,trayId:r,tray:i,isEmpty:a,nozzleSide:o,effectiveFill:s})=>{let c=c$e(i.tray_color);return(0,K.jsxs)(`div`,{onClick:()=>V(n,r),className:`bg-bambu-dark-secondary rounded-lg px-3 py-2 cursor-pointer hover:bg-bambu-dark-secondary/80 transition-all flex items-center gap-2 ${w&&w.ams_id===n&&w.tray_id===r?`ring-2 ring-bambu-green`:``} ${L?`opacity-50 pointer-events-none`:``}`,children:[(0,K.jsx)(`div`,{className:`relative w-10 h-10 shrink-0`,children:a?(0,K.jsx)(`div`,{className:`w-full h-full rounded-full border-2 border-dashed border-gray-500 flex items-center justify-center`,children:(0,K.jsx)(`div`,{className:`w-1.5 h-1.5 rounded-full bg-gray-600`})}):(0,K.jsxs)(`svg`,{viewBox:`0 0 56 56`,className:`w-full h-full`,children:[(0,K.jsx)(`circle`,{cx:`28`,cy:`28`,r:`26`,fill:c}),(0,K.jsx)(`circle`,{cx:`28`,cy:`28`,r:`20`,fill:c,style:{filter:`brightness(0.85)`}}),(0,K.jsx)(`ellipse`,{cx:`20`,cy:`20`,rx:`6`,ry:`4`,fill:`white`,opacity:`0.3`}),(0,K.jsx)(`circle`,{cx:`28`,cy:`28`,r:`8`,fill:`#2d2d2d`}),(0,K.jsx)(`circle`,{cx:`28`,cy:`28`,r:`5`,fill:`#1a1a1a`})]})}),(0,K.jsxs)(`div`,{className:`min-w-0`,children:[(0,K.jsxs)(`div`,{className:`flex items-center gap-1`,children:[(0,K.jsx)(`span`,{className:`text-xs text-white/50 font-medium`,children:t}),o&&(0,K.jsx)(K9,{side:o})]}),(0,K.jsx)(`div`,{className:`text-sm text-white/80 truncate`,children:a?`Empty`:i.tray_type||`?`})]}),!a&&s!=null&&s>=0&&(0,K.jsx)(`div`,{className:`w-1.5 h-8 bg-bambu-dark-tertiary rounded-full overflow-hidden shrink-0 flex flex-col-reverse`,children:(0,K.jsx)(`div`,{className:`w-full rounded-full`,style:{height:`${s}%`,backgroundColor:Kf(s)}})})]},e)})})]})}),(0,K.jsx)(`div`,{className:`flex justify-end gap-3 px-5 py-3 border-t border-zinc-800 shrink-0`,children:(0,K.jsx)(`button`,{onClick:t,disabled:L,className:`px-5 py-2.5 rounded-lg text-sm font-medium bg-zinc-800 text-zinc-300 hover:bg-zinc-700 transition-colors min-h-[44px] disabled:opacity-50`,children:l===`success`?a(`spoolbuddy.dashboard.close`,`Close`):a(`spoolbuddy.modal.cancel`,`Cancel`)})})]}),d&&p&&(()=>{let e=``;return p.type===`material`?e=a(`inventory.assignMismatchMessage`,{spoolMaterial:p.spoolMaterial,trayMaterial:p.trayMaterial,location:p.location}):p.type===`partial`?e=a(`inventory.assignPartialMismatchMessage`,{spoolMaterial:p.spoolMaterial,trayMaterial:p.trayMaterial,location:p.location}):p.type===`material_profile`?e=`${a(`inventory.assignMismatchMessage`,{spoolMaterial:p.spoolMaterial,trayMaterial:p.trayMaterial,location:p.location})}\n\n${a(`inventory.assignProfileMismatchMessage`,{spoolProfile:p.spoolProfile||a(`common.unknown`),trayProfile:p.trayProfile||a(`common.unknown`),location:p.location})}`:p.type===`partial_profile`&&(e=`${a(`inventory.assignPartialMismatchMessage`,{spoolMaterial:p.spoolMaterial,trayMaterial:p.trayMaterial,location:p.location})}\n\n${a(`inventory.assignProfileMismatchMessage`,{spoolProfile:p.spoolProfile||a(`common.unknown`),trayProfile:p.trayProfile||a(`common.unknown`),location:p.location})}`),e=`${e}\n\n${a(`inventory.assignReconfigureNote`)}`,(0,K.jsx)(Rd,{title:a(`inventory.assignMismatchTitle`),message:e,confirmText:a(`inventory.assignMismatchConfirm`),variant:`warning`,isLoading:I.isPending,onConfirm:ee,onCancel:()=>{I.isPending||(f(!1),g(null),m(null))}})})()]}):null}function f$e({isOpen:e,onClose:t,tagId:n,untaggedSpools:r,onLink:i}){let{t:a}=W(),[o,s]=(0,y.useState)(null),c=(0,y.useCallback)(()=>{s(null),t()},[t]),l=(0,y.useCallback)(e=>{e.key===`Escape`&&c()},[c]);return(0,y.useEffect)(()=>(e&&(document.addEventListener(`keydown`,l),document.body.style.overflow=`hidden`),()=>{document.removeEventListener(`keydown`,l),document.body.style.overflow=``}),[e,l]),e?(0,K.jsx)(`div`,{className:`fixed inset-0 z-50 flex items-center justify-center bg-black/70 animate-fade-in`,onClick:c,children:(0,K.jsxs)(`div`,{className:`bg-zinc-800 rounded-xl shadow-2xl w-full max-w-lg mx-4 animate-slide-up`,onClick:e=>e.stopPropagation(),children:[(0,K.jsxs)(`div`,{className:`flex items-center justify-between px-5 py-4 border-b border-zinc-700`,children:[(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`h2`,{className:`text-base font-semibold text-zinc-100`,children:a(`spoolbuddy.dashboard.linkTagTitle`,`Link Tag to Spool`)}),(0,K.jsx)(`p`,{className:`text-sm text-zinc-500 font-mono`,children:n})]}),(0,K.jsx)(`button`,{onClick:c,className:`p-2 rounded-lg text-zinc-500 hover:text-zinc-300 hover:bg-zinc-700 transition-colors`,children:(0,K.jsx)(Hu,{className:`w-5 h-5`})})]}),(0,K.jsxs)(`div`,{className:`px-5 py-4 space-y-3 max-h-[400px] overflow-y-auto`,children:[(0,K.jsx)(`p`,{className:`text-sm text-zinc-400`,children:a(`spoolbuddy.dashboard.selectSpool`,`Select a spool to link this tag to:`)}),r.length===0?(0,K.jsx)(`div`,{className:`text-center py-8 text-zinc-500`,children:a(`spoolbuddy.dashboard.noUntagged`,`No spools without tags found`)}):(0,K.jsx)(`div`,{className:`space-y-2`,children:r.map(e=>(0,K.jsxs)(`button`,{type:`button`,onClick:()=>s(e),className:`w-full flex items-center gap-3 p-3 rounded-lg border-2 transition-all text-left ${o?.id===e.id?`border-green-500 bg-green-500/10`:`border-zinc-700 hover:border-green-500/50 hover:bg-zinc-700/50`}`,children:[(0,K.jsx)(G9,{color:tf(e.rgba),isEmpty:!1,size:40}),(0,K.jsxs)(`div`,{className:`flex-1 min-w-0`,children:[(0,K.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,K.jsx)(`div`,{className:`font-medium text-zinc-100 truncate`,children:e.color_name||`Unknown color`}),(0,K.jsxs)(`span`,{className:`text-[10px] font-mono text-zinc-500 shrink-0`,children:[`#`,e.id]})]}),(0,K.jsxs)(`div`,{className:`text-sm text-zinc-400 truncate`,children:[e.brand,` • `,e.material,e.subtype&&` ${e.subtype}`]})]}),(0,K.jsxs)(`div`,{className:`text-sm font-mono text-zinc-500`,children:[Math.max(0,e.label_weight-e.weight_used),`g`]})]},e.id))})]}),(0,K.jsxs)(`div`,{className:`flex justify-end gap-2 px-5 py-4 border-t border-zinc-700`,children:[(0,K.jsx)(`button`,{onClick:c,className:`px-4 py-2.5 rounded-lg text-sm font-medium bg-zinc-700 text-zinc-300 hover:bg-zinc-600 transition-colors min-h-[44px]`,children:a(`common.cancel`,`Cancel`)}),(0,K.jsx)(`button`,{onClick:()=>{o&&(i(o),s(null))},disabled:!o,className:`px-4 py-2.5 rounded-lg text-sm font-medium bg-green-600 text-white hover:bg-green-700 disabled:opacity-40 disabled:cursor-not-allowed transition-colors min-h-[44px]`,children:a(`spoolbuddy.dashboard.linkTag`,`Link Tag`)})]})]})}):null}function p$e(e){return e?e.replace(/[^0-9a-f]/gi,``).toUpperCase():``}function m$e(e,t){let n=p$e(e),r=p$e(t);return!n||!r?!1:n===r?!0:n.endsWith(r)||r.endsWith(n)}var h$e=[`#00AE42`,`#FF6B35`,`#3B82F6`,`#EF4444`,`#A855F7`,`#FBBF24`,`#14B8A6`,`#EC4899`,`#F97316`,`#22C55E`];function g$e(){let{t:e}=W(),[t,n]=(0,y.useState)(0);(0,y.useEffect)(()=>{let e=setInterval(()=>{n(e=>(e+1)%h$e.length)},5e3);return()=>clearInterval(e)},[]);let r=h$e[t];return(0,K.jsxs)(`div`,{className:`flex flex-col items-center text-center`,children:[(0,K.jsxs)(`div`,{className:`relative mb-6 flex items-center justify-center`,style:{width:160,height:160},children:[(0,K.jsx)(`div`,{className:`absolute inset-0 flex items-center justify-center pointer-events-none`,children:[0,1].map(e=>(0,K.jsx)(`div`,{className:`absolute rounded-full border spoolbuddy-optimized-ping`,style:{width:80,height:80,borderColor:`${r}4D`,transition:`border-color 140ms linear`,animationDelay:`${e*.8}s`}},e))}),(0,K.jsxs)(`div`,{className:`relative overflow-hidden rounded-full`,children:[(0,K.jsx)(`div`,{className:`absolute inset-0 rounded-full opacity-30 spoolbuddy-spool-glow`,style:{background:`radial-gradient(circle, ${r} 0%, transparent 70%)`}}),(0,K.jsx)(`div`,{className:`relative`,style:{transition:`opacity 140ms linear`},children:(0,K.jsx)(G9,{color:r,isEmpty:!1,size:100})})]})]}),(0,K.jsxs)(`div`,{className:`space-y-2`,children:[(0,K.jsx)(`p`,{className:`text-xl font-medium text-zinc-300`,children:e(`spoolbuddy.dashboard.readyToScan`,`Ready to scan`)}),(0,K.jsx)(`p`,{className:`text-sm text-zinc-500`,children:e(`spoolbuddy.dashboard.idleMessage`,`Place a spool on the scale to identify it`)})]}),(0,K.jsxs)(`div`,{className:`mt-6 flex items-center gap-2 text-sm text-zinc-600`,children:[(0,K.jsx)(`svg`,{className:`w-4 h-4`,fill:`none`,viewBox:`0 0 24 24`,stroke:`currentColor`,children:(0,K.jsx)(`path`,{strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:`2`,d:`M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z`})}),(0,K.jsx)(`span`,{children:e(`spoolbuddy.dashboard.nfcHint`,`NFC tag will be read automatically`)})]})]})}function _$e(){let{t:e}=W();return(0,K.jsxs)(`div`,{className:`flex flex-col items-center text-center`,children:[(0,K.jsx)(`div`,{className:`relative mb-6 flex items-center justify-center`,style:{width:160,height:160},children:(0,K.jsx)(`div`,{className:`w-24 h-24 rounded-full bg-zinc-800 flex items-center justify-center`,children:(0,K.jsx)(`svg`,{className:`w-12 h-12 text-zinc-600`,fill:`none`,viewBox:`0 0 24 24`,stroke:`currentColor`,children:(0,K.jsx)(`path`,{strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:`1.5`,d:`M18.364 5.636a9 9 0 010 12.728m0 0l-12.728-12.728m12.728 12.728L5.636 5.636m12.728 0a9 9 0 00-12.728 0m0 12.728a9 9 0 010-12.728`})})})}),(0,K.jsxs)(`div`,{className:`space-y-2`,children:[(0,K.jsx)(`p`,{className:`text-lg font-medium text-zinc-500`,children:e(`spoolbuddy.status.deviceOffline`,`Device Offline`)}),(0,K.jsx)(`p`,{className:`text-sm text-zinc-600`,children:e(`spoolbuddy.status.connectDisplay`,`Connect the SpoolBuddy display to scan spools`)})]}),(0,K.jsxs)(`div`,{className:`mt-6 flex items-center gap-2 text-xs text-zinc-600`,children:[(0,K.jsx)(`svg`,{className:`w-4 h-4`,fill:`none`,viewBox:`0 0 24 24`,stroke:`currentColor`,children:(0,K.jsx)(`path`,{strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:`2`,d:`M8.111 16.404a5.5 5.5 0 017.778 0M12 20h.01m-7.08-7.071c3.904-3.905 10.236-3.905 14.14 0M1.394 9.393c5.857-5.857 15.355-5.857 21.213 0`})}),(0,K.jsx)(`span`,{children:e(`spoolbuddy.status.waitingConnection`,`Waiting for device connection...`)})]})]})}function v$e(){let{sbState:e,selectedPrinterId:t}=nr(),{t:n}=W(),{showToast:r}=kd(),{data:i}=q({queryKey:[`spoolman-settings`],queryFn:Q.getSpoolmanSettings,staleTime:300*1e3}),a=i?.spoolman_enabled===`true`&&!!i?.spoolman_url,{data:o=[],refetch:s}=q({queryKey:a?[`spoolman-inventory-spools`]:[`inventory-spools`],queryFn:()=>a?Q.getSpoolmanInventorySpools(!1):Q.getSpools(!1),enabled:i!==void 0}),{data:c=[]}=q({queryKey:[`spoolman-slot-assignments`],queryFn:()=>Q.getSpoolmanSlotAssignments(),enabled:a,staleTime:3*1e3,refetchInterval:3*1e3,refetchIntervalInBackground:!1}),{data:l=[]}=q({queryKey:[`printers`],queryFn:()=>Q.getPrinters()}),u=go({queries:l.map(e=>({queryKey:[`printerStatus`,e.id],queryFn:()=>Q.getPrinterStatus(e.id),refetchInterval:1e4,select:e=>({connected:e?.connected,awaiting_plate_clear:e?.awaiting_plate_clear===!0})}))}),d=l.map((e,t)=>({printer:e,pending:u[t]?.data?.awaiting_plate_clear===!0})).filter(e=>e.pending),f=to(),p=J({mutationFn:e=>Q.clearPlate(e),onSuccess:(e,t)=>{f.setQueryData([`printerStatus`,t],e=>e&&{...e,awaiting_plate_clear:!1}),r(n(`spoolbuddy.dashboard.plateClearedToast`,`Plate marked as cleared`),`success`)},onError:()=>{r(n(`spoolbuddy.dashboard.plateClearFailed`,`Could not mark plate as cleared`),`error`)}}),m=J({mutationFn:e=>Q.unassignSpoolmanSlot(e),onSuccess:()=>{f.invalidateQueries({queryKey:[`spoolman-slot-assignments`]}),f.invalidateQueries({queryKey:[`spoolman-inventory-spools`]})},onError:()=>r(n(`inventory.unassignFailed`,`Failed to unassign spool`),`error`)}),[h,g]=(0,y.useState)(null),[_,v]=(0,y.useState)(null),[b,x]=(0,y.useState)(null),[S,C]=(0,y.useState)(!1),[w,T]=(0,y.useState)(!1),[E,D]=(0,y.useState)(!1),[O,k]=(0,y.useState)(!1),[A,j]=(0,y.useState)(null),M=e.matchedSpool?.tag_uid??e.unknownTagUid??null,N=e.weight,P=e.weightStable,F=(0,y.useRef)(null);N===null?F.current=null:(F.current===null||Math.abs(N-F.current)>=3||P)&&(F.current=N);let I=F.current,L=(0,y.useMemo)(()=>{if(e.matchedSpool?.id){let t=o.find(t=>t.id===e.matchedSpool?.id);if(t)return t}return h&&(o.find(e=>m$e(e.tag_uid,h))||A)||null},[h,e.matchedSpool,o,A]),R=(0,y.useMemo)(()=>{if(L&&!A)return L;let t=e.matchedSpool;return t?{id:t.id,tag_uid:t.tag_uid,material:t.material,subtype:t.subtype,color_name:t.color_name,rgba:t.rgba,brand:t.brand,label_weight:t.label_weight,core_weight:t.core_weight,weight_used:t.weight_used}:null},[L,A,e.matchedSpool]),z=a&&R!=null?c.some(e=>e.spoolman_spool_id===R.id):!1,B=(0,y.useMemo)(()=>a?o.filter(e=>!e.tag_uid&&!e.tray_uuid&&!e.archived_at):o.filter(e=>!e.tag_uid&&!e.archived_at),[o,a]);(0,y.useEffect)(()=>{if(M){let e=b===M;(h!==null&&h!==M||!e&&h!==M)&&(g(M),v(null),x(null),j(null)),!e&&N!==null&&P&&v(Math.round(Math.max(0,N)))}else b&&(g(null),x(null),v(null),j(null))},[M,N,P,h,b]);let V=()=>{x(h)},ee=async t=>{if(h)try{if(a){let i=e.unknownTagUid||void 0,a=!e.unknownTagUid&&e.unknownTrayUuid?e.unknownTrayUuid:void 0;if(!i&&!a){r(n(`spoolman.linkFailed`),`error`);return}let o=await Q.linkTagToSpoolmanSpool(t.id,{tray_uuid:a,tag_uid:i});if(!o){r(n(`spoolman.linkFailed`),`error`);return}let{id:s,material:c,subtype:l,color_name:u,rgba:d,brand:f,label_weight:p,core_weight:m,weight_used:h}=o;j({id:s,material:c,subtype:l,color_name:u,rgba:d,brand:f,label_weight:p,core_weight:m,weight_used:h}),r(n(`spoolman.linkSuccess`),`success`)}else await Q.linkTagToSpool(t.id,{tag_uid:h,tag_type:`generic`,data_origin:`nfc_link`});s()}catch(e){console.error(`Failed to link tag:`,e),r(n(`spoolman.linkFailed`),`error`)}finally{C(!1)}},te=async()=>{if(h){k(!0);try{let t=ne??_;if(a){let n=await Q.createSpoolmanInventorySpool({material:`PLA`,subtype:null,color_name:null,rgba:null,extra_colors:null,effect_type:null,brand:null,label_weight:1e3,core_weight:250,core_weight_catalog_id:null,weight_used:0,slicer_filament:null,slicer_filament_name:null,nozzle_temp_min:null,nozzle_temp_max:null,note:null,added_full:null,last_used:null,encode_time:null,tag_uid:null,tray_uuid:null,data_origin:null,tag_type:null,cost_per_kg:null,last_scale_weight:t===null?null:Math.round(t),last_weighed_at:t===null?null:new Date().toISOString(),category:null,low_stock_threshold_pct:null});await Q.linkTagToSpoolmanSpool(n.id,{tag_uid:e.unknownTagUid||void 0,tray_uuid:!e.unknownTagUid&&e.unknownTrayUuid?e.unknownTrayUuid:void 0})}else await Q.createSpool({material:`PLA`,subtype:null,color_name:null,rgba:null,extra_colors:null,effect_type:null,brand:null,label_weight:1e3,core_weight:250,core_weight_catalog_id:null,weight_used:0,slicer_filament:null,slicer_filament_name:null,nozzle_temp_min:null,nozzle_temp_max:null,note:null,added_full:null,last_used:null,encode_time:null,tag_uid:h,tray_uuid:null,data_origin:`spoolbuddy`,tag_type:`generic`,cost_per_kg:null,last_scale_weight:t===null?null:Math.round(t),last_weighed_at:t===null?null:new Date().toISOString(),category:null,low_stock_threshold_pct:null})}catch(e){let t=e instanceof Error?e.message:String(e);console.error(`Failed to quick-add spool:`,t),r(t||n(`spoolbuddy.errors.quickAddFailed`,`Failed to add spool`),`error`)}finally{D(!1),k(!1),s()}}},ne=N!==null&&(M===h||M===null&&h!==null)?N:null,re=o.length,ie=new Set(o.map(e=>e.material)).size,H=new Set(o.filter(e=>e.brand).map(e=>e.brand)).size;return(0,K.jsxs)(`div`,{className:`h-full flex flex-col p-4`,children:[(0,K.jsxs)(`div`,{className:`flex items-center gap-6 px-4 py-1.5 bg-zinc-800/50 rounded-xl border border-zinc-700/50 mb-3 shrink-0`,children:[(0,K.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,K.jsx)(`span`,{className:`text-xl font-bold text-zinc-100`,children:re}),(0,K.jsx)(`span`,{className:`text-sm text-zinc-500`,children:n(`spoolbuddy.inventory.spools`,`Spools`)})]}),(0,K.jsx)(`div`,{className:`w-px h-5 bg-zinc-700`}),(0,K.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,K.jsx)(`span`,{className:`text-xl font-bold text-zinc-100`,children:ie}),(0,K.jsx)(`span`,{className:`text-sm text-zinc-500`,children:n(`spoolbuddy.spool.material`,`Materials`)})]}),(0,K.jsx)(`div`,{className:`w-px h-5 bg-zinc-700`}),(0,K.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,K.jsx)(`span`,{className:`text-xl font-bold text-zinc-100`,children:H}),(0,K.jsx)(`span`,{className:`text-sm text-zinc-500`,children:n(`spoolbuddy.spool.brand`,`Brands`)})]})]}),(0,K.jsxs)(`div`,{className:`flex-1 flex gap-4 min-h-0`,children:[(0,K.jsxs)(`div`,{className:`w-5/12 flex flex-col min-h-0`,children:[(0,K.jsxs)(`div`,{className:`border border-dashed border-zinc-700/50 rounded-xl p-4`,children:[(0,K.jsx)(`h2`,{className:`text-sm font-semibold text-zinc-400 uppercase tracking-wide mb-3`,children:n(`spoolbuddy.dashboard.device`,`Device`)}),(0,K.jsxs)(`div`,{className:`space-y-2.5`,children:[(0,K.jsxs)(`div`,{className:`flex items-center gap-3`,children:[(0,K.jsx)(`div`,{className:`w-2.5 h-2.5 rounded-full ${e.deviceOnline?`bg-green-500`:`bg-red-500`}`}),(0,K.jsx)(`span`,{className:`text-base text-zinc-400`,children:e.deviceOnline?n(`spoolbuddy.status.online`,`Online`):n(`spoolbuddy.status.offline`,`Disconnected`)})]}),(0,K.jsxs)(`div`,{className:`flex items-center justify-between p-3 bg-zinc-800/50 rounded-lg`,children:[(0,K.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,K.jsx)(`svg`,{className:`w-4 h-4 ${e.deviceOnline?`text-green-500`:`text-zinc-500`}`,fill:`none`,viewBox:`0 0 24 24`,stroke:`currentColor`,children:(0,K.jsx)(`path`,{strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:`2`,d:`M3 6l3 1m0 0l-3 9a5.002 5.002 0 006.001 0M6 7l3 9M6 7l6-2m6 2l3-1m-3 1l-3 9a5.002 5.002 0 006.001 0M18 7l3 9m-3-9l-6-2m0-2v2m0 16V5m0 16H9m3 0h3`})}),(0,K.jsx)(`span`,{className:`text-sm text-zinc-500`,children:n(`spoolbuddy.spool.scaleWeight`,`Scale`)})]}),(0,K.jsx)(`span`,{className:`text-lg font-mono font-semibold text-zinc-100`,children:I===null?`—`:`${Math.abs(I)<=20?0:Math.round(Math.max(0,I))}g`})]}),(0,K.jsxs)(`div`,{className:`flex items-center justify-between p-3 bg-zinc-800/50 rounded-lg`,children:[(0,K.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,K.jsx)(`svg`,{className:`w-4 h-4 ${e.deviceOnline?`text-green-500`:`text-zinc-500`}`,fill:`none`,viewBox:`0 0 24 24`,stroke:`currentColor`,children:(0,K.jsx)(`path`,{strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:`2`,d:`M7 7h.01M7 3h5c.512 0 1.024.195 1.414.586l7 7a2 2 0 010 2.828l-7 7a2 2 0 01-2.828 0l-7-7A2 2 0 013 12V7a4 4 0 014-4z`})}),(0,K.jsx)(`span`,{className:`text-sm text-zinc-500`,children:`NFC`})]}),(0,K.jsx)(`span`,{className:`text-sm font-medium ${M?`text-green-500`:`text-zinc-500`}`,children:M?n(`spoolbuddy.dashboard.tagDetected`,`Tag detected`):n(`spoolbuddy.dashboard.noTag`,`No tag`)})]})]})]}),l.length>0&&(0,K.jsxs)(`div`,{className:`mt-3 border border-dashed border-zinc-700/50 rounded-xl p-4`,children:[(0,K.jsx)(`h2`,{className:`text-sm font-semibold text-zinc-400 uppercase tracking-wide mb-2.5`,children:n(`spoolbuddy.dashboard.printers`,`Printers`)}),(0,K.jsx)(`div`,{className:`flex flex-wrap gap-2 overflow-hidden`,children:l.map((e,t)=>{let n=u[t]?.data?.connected??!1;return(0,K.jsxs)(`div`,{className:`flex items-center gap-1.5 px-2.5 py-1 bg-zinc-800/50 rounded-lg`,title:`${e.name} — ${n?`Online`:`Offline`}`,children:[(0,K.jsx)(`div`,{className:`w-2 h-2 rounded-full shrink-0 ${n?`bg-green-500`:`bg-zinc-600`}`}),(0,K.jsx)(`span`,{className:`text-xs text-zinc-400 truncate max-w-[100px]`,children:e.name})]},e.id)})}),d.length>0&&(0,K.jsx)(`div`,{className:`mt-2 flex flex-wrap gap-2`,"data-testid":`plate-clear-section`,"aria-label":n(`spoolbuddy.dashboard.plateReadyLabel`,`Plates ready to clear`),children:d.map(({printer:e})=>(0,K.jsxs)(`button`,{type:`button`,onClick:()=>p.mutate(e.id),disabled:p.isPending,"data-testid":`plate-clear-button-${e.id}`,title:n(`spoolbuddy.dashboard.plateReady`,`Plate ready: {{name}}`,{name:e.name}),className:`flex items-center gap-1.5 px-2.5 py-1 rounded-lg bg-amber-500/10 hover:bg-amber-500/20 active:bg-amber-500/30 border border-amber-500/30 text-amber-200 transition-colors disabled:opacity-60 disabled:cursor-wait`,children:[(0,K.jsxs)(`svg`,{className:`w-3 h-3 shrink-0`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2.5`,strokeLinecap:`round`,strokeLinejoin:`round`,"aria-hidden":`true`,children:[(0,K.jsx)(`path`,{d:`M12 9v4`}),(0,K.jsx)(`path`,{d:`M12 17h.01`}),(0,K.jsx)(`path`,{d:`M10.29 3.86 1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z`})]}),(0,K.jsx)(`span`,{className:`text-xs truncate max-w-[100px]`,children:e.name}),(0,K.jsx)(`span`,{className:`text-xs opacity-70`,"aria-hidden":`true`,children:`·`}),(0,K.jsx)(`span`,{className:`text-xs font-medium`,children:n(`spoolbuddy.dashboard.plateClearAction`,`Clear`)})]},e.id))})]})]}),(0,K.jsx)(`div`,{className:`w-7/12 min-h-0`,children:(0,K.jsxs)(`div`,{className:`border border-dashed border-zinc-700/50 rounded-xl p-6 h-full flex flex-col`,children:[(0,K.jsx)(`h2`,{className:`text-sm font-semibold text-zinc-400 uppercase tracking-wide mb-4 shrink-0`,children:n(`spoolbuddy.dashboard.currentSpool`,`Current Spool`)}),(0,K.jsx)(`div`,{className:`flex-1 flex items-center justify-center min-h-0`,children:e.deviceOnline?(L||e.matchedSpool)&&h&&b!==h?(0,K.jsx)(KQe,{spool:(()=>{let t=L??e.matchedSpool;return{id:t.id,tag_uid:h,material:t.material,subtype:t.subtype,color_name:t.color_name,rgba:t.rgba,brand:t.brand,label_weight:t.label_weight,core_weight:t.core_weight,weight_used:t.weight_used}})(),scaleWeight:ne??_,onSyncWeight:()=>s(),onAssignToAms:()=>T(!0),isAssigned:z,onUnassignFromAms:z&&L?.id!=null?()=>m.mutate(L.id):void 0,onClose:V}):M&&h&&!L&&!e.matchedSpool&&b!==h?(0,K.jsx)(qQe,{tagUid:h,scaleWeight:ne??_,onLinkSpool:B.length>0?()=>C(!0):void 0,onAddToInventory:()=>D(!0),onClose:V}):(0,K.jsx)(g$e,{}):(0,K.jsx)(_$e,{})})]})})]}),R&&!A&&h&&(0,K.jsx)(d$e,{isOpen:w,onClose:()=>T(!1),spool:R,printerId:t,spoolmanMode:a}),h&&(0,K.jsx)(f$e,{isOpen:S,onClose:()=>C(!1),tagId:h,untaggedSpools:B,onLink:ee}),E&&h&&(0,K.jsx)(`div`,{className:`fixed inset-0 z-50 flex items-center justify-center bg-black/60`,children:(0,K.jsxs)(`div`,{className:`bg-zinc-800 rounded-2xl p-6 mx-4 max-w-sm w-full border border-zinc-700`,children:[(0,K.jsx)(`h3`,{className:`text-lg font-semibold text-zinc-100 mb-3`,children:n(`spoolbuddy.modal.addToInventory`,`Add to Inventory`)}),(0,K.jsxs)(`div`,{className:`flex gap-2.5 p-3 bg-amber-500/10 border border-amber-500/20 rounded-lg mb-4`,children:[(0,K.jsx)(`svg`,{className:`w-5 h-5 text-amber-500 shrink-0 mt-0.5`,fill:`none`,viewBox:`0 0 24 24`,stroke:`currentColor`,children:(0,K.jsx)(`path`,{strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:`2`,d:`M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z`})}),(0,K.jsx)(`p`,{className:`text-sm text-amber-200/80`,children:n(`spoolbuddy.modal.quickAddHint`,`For best results, add the spool in the Bambuddy web interface first (with material, color, brand), then use "Assign Spool" here to assign the NFC tag.`)})]}),(0,K.jsx)(`p`,{className:`text-sm text-zinc-400 mb-1`,children:n(`spoolbuddy.modal.quickAddDesc`,`This will create a basic PLA spool entry with this NFC tag. You can edit the details later in Bambuddy.`)}),(0,K.jsx)(`p`,{className:`text-xs text-zinc-500 font-mono mb-5`,children:h}),(0,K.jsxs)(`div`,{className:`flex gap-3`,children:[(0,K.jsx)(`button`,{onClick:()=>D(!1),className:`flex-1 px-4 py-2.5 rounded-lg text-sm font-medium bg-zinc-700 text-zinc-300 hover:bg-zinc-600 transition-colors min-h-[44px]`,children:n(`common.cancel`,`Cancel`)}),(0,K.jsx)(`button`,{onClick:te,disabled:O,className:`flex-1 px-4 py-2.5 rounded-lg text-sm font-medium bg-green-600 text-white hover:bg-green-700 disabled:opacity-50 transition-colors min-h-[44px]`,children:O?n(`common.saving`,`Saving...`):n(`spoolbuddy.modal.addAnyway`,`Add Anyway`)})]})]})})]})}function y$e(e){return e<=3?`AMS ${String.fromCharCode(65+e)}`:e>=128&&e<=135?`AMS HT ${String.fromCharCode(65+e-128)}`:`AMS ${e}`}function b$e(e){return e?{O1D:`H2D`,O1E:`H2D Pro`,O2D:`H2D Pro`,O1C:`H2C`,O1C2:`H2C`,O1S:`H2S`,"BL-P001":`X1C`,"BL-P002":`X1`,"BL-P003":`X1E`,N6:`X2D`,N9:`A2L`,C11:`P1S`,C12:`P1P`,C13:`P2S`,N2S:`A1`,N1:`A1 Mini`,X1C:`X1C`,X1:`X1`,X1E:`X1E`,X2D:`X2D`,P1S:`P1S`,P1P:`P1P`,P2S:`P2S`,A1:`A1`,"A1 Mini":`A1 Mini`,A2L:`A2L`,H2D:`H2D`,"H2D Pro":`H2D Pro`,H2C:`H2C`,H2S:`H2S`}[e]||e:``}function X9(e){return!e.tray_type||e.tray_type===``}function x$e(e){return e?`#${e.slice(0,6)}`:`#808080`}function S$e(){let{selectedPrinterId:e,setAlert:t}=nr(),{t:n}=W(),r=to(),{showToast:i}=kd(),{data:a}=q({queryKey:[`printerStatus`,e],queryFn:()=>Q.getPrinterStatus(e),enabled:e!==null,staleTime:30*1e3}),{data:o}=q({queryKey:[`printer`,e],queryFn:()=>Q.getPrinter(e),enabled:e!==null,staleTime:60*1e3}),{data:s}=q({queryKey:[`slotPresets`,e],queryFn:()=>Q.getSlotPresets(e),enabled:e!==null,staleTime:120*1e3}),{data:c}=q({queryKey:[`settings`],queryFn:()=>Q.getSettings(),staleTime:300*1e3}),{data:l}=q({queryKey:[`spoolman-status`],queryFn:Q.getSpoolmanStatus,staleTime:60*1e3}),u=l?.enabled&&l?.connected,{data:d}=q({queryKey:[`linked-spools`],queryFn:Q.getLinkedSpools,enabled:!!u,staleTime:30*1e3}),f=d?.linked,{data:p=[]}=q({queryKey:[`spoolman-slot-assignments-all`],queryFn:()=>Q.getSpoolmanSlotAssignments(),enabled:!!u,staleTime:30*1e3}),{data:m=[]}=q({queryKey:[`spoolman-inventory-spools`],queryFn:()=>Q.getSpoolmanInventorySpools(!1),enabled:!!u,staleTime:30*1e3}),{data:h}=q({queryKey:[`spool-assignments`,e],queryFn:()=>Q.getAssignments(e),enabled:e!==null,staleTime:30*1e3}),g=(0,y.useMemo)(()=>{let e={};if(!h)return e;for(let t of h){let n=t.spool;if(n&&n.label_weight>0&&n.weight_used!=null){let r=Math.round(Math.max(0,n.label_weight-n.weight_used)/n.label_weight*100);e[`${t.ams_id}-${t.tray_id}`]=r}}return e},[h]),_=o?.serial_number??``,v=(0,y.useCallback)((t,n,r)=>{if(e!==null&&p.length&&m.length){let r=p.find(r=>r.printer_id===e&&r.ams_id===t&&r.tray_id===n);if(r){let e=m.find(e=>e.id===r.spoolman_spool_id);if(e&&(e.label_weight??0)>0)return Math.round(Math.max(0,e.label_weight-e.weight_used)/e.label_weight*100)}}if(f&&_){let e=(r?.tray_uuid||r?.tag_uid||Xf(_,t,n))?.toUpperCase(),i=qf(e?f[e]:void 0);if(i!==null)return i}return null},[f,_,e,p,m]),b=a?.connected??!1,x=(0,y.useRef)({});(0,y.useEffect)(()=>{e&&a?.ams&&a.ams.length>0&&(x.current[e]=a.ams)},[a?.ams,e]);let S=(0,y.useMemo)(()=>{let t=a?.ams;return t&&t.length>0?t:(e?x.current[e]:null)??[]},[a?.ams,e]),C=(0,y.useMemo)(()=>S.filter(e=>!e.is_ams_ht),[S]),w=(0,y.useMemo)(()=>S.filter(e=>e.is_ams_ht),[S]),T=(0,y.useMemo)(()=>{let e={};if(!f||!_)return e;for(let t of C)for(let n=0;n<(t.tray?.length??0);n++){let r=t.tray[n],i=v(t.id,n,X9(r)?null:r);i!==null&&(e[`${t.id}-${n}`]=i)}return e},[f,_,C,v]),E=(0,y.useRef)(void 0),D=a?.tray_now;D!==void 0&&D!==255?E.current=D:D===255&&(E.current=void 0);let O=D!==void 0&&D!==255?D:E.current,k=o?.nozzle_count===2||a?.temperatures?.nozzle_2!==void 0,A=(0,y.useMemo)(()=>[...a?.vt_tray??[]].sort((e,t)=>(e.id??254)-(t.id??254)),[a?.vt_tray]),j=c?{humidityGood:Number(c.ams_humidity_good)||40,humidityFair:Number(c.ams_humidity_fair)||60,tempGood:Number(c.ams_temp_good)||28,tempFair:Number(c.ams_temp_fair)||35}:void 0,M=(0,y.useRef)({});(0,y.useEffect)(()=>{a?.ams_extruder_map&&Object.keys(a.ams_extruder_map).length>0&&(M.current=a.ams_extruder_map)},[a?.ams_extruder_map]);let N=a?.ams_extruder_map&&Object.keys(a.ams_extruder_map).length>0?a.ams_extruder_map:M.current,P=(0,y.useCallback)(e=>{if(!k)return null;let t=N[String(e)],n=e>=128?e-128:e;return(t===void 0?n:t)===1?`L`:`R`},[k,N]),[F,I]=(0,y.useState)(null),[L,R]=(0,y.useState)(null),[z,B]=(0,y.useState)(null),[V,ee]=(0,y.useState)(null),te=(0,y.useCallback)((e,t)=>h?.find(n=>n.ams_id===Number(e)&&n.tray_id===Number(t)),[h]),ne=(0,y.useCallback)((e,t,n)=>{if(!f||!_)return;let r=(n?.tray_uuid||n?.tag_uid||Xf(_,e,t))?.toUpperCase();return r?f[r]:void 0},[f,_]),re=J({mutationFn:({printerId:e,amsId:t,trayId:n})=>Q.unassignSpool(e,t,n),onSuccess:()=>{r.invalidateQueries({queryKey:[`spool-assignments`,e]}),r.invalidateQueries({queryKey:[`spool-assignments`]}),i(n(`inventory.unassignSuccess`,`Spool unassigned`),`success`),R(null)}}),ie=J({mutationFn:e=>Q.unlinkSpool(e),onSuccess:e=>{i(n(`spoolman.unlinkSuccess`)||e?.message,`success`),r.invalidateQueries({queryKey:[`linked-spools`]}),r.invalidateQueries({queryKey:[`unlinked-spools`]}),r.invalidateQueries({queryKey:[`spoolman-slot-assignments`]}),r.invalidateQueries({queryKey:[`spoolman-slot-assignments-all`]}),r.invalidateQueries({queryKey:[`spoolman-inventory-spools`]}),R(null)},onError:e=>{i(e.message||n(`spoolman.unlinkFailed`),`error`)}}),H=J({mutationFn:e=>Q.unassignSpoolmanSlot(e),onSuccess:()=>{i(n(`inventory.unassignSuccess`,`Spool unassigned`),`success`),r.invalidateQueries({queryKey:[`spoolman-slot-assignments`]}),r.invalidateQueries({queryKey:[`spoolman-slot-assignments-all`]}),r.invalidateQueries({queryKey:[`spoolman-inventory-spools`]}),r.invalidateQueries({queryKey:[`unlinked-spools`]}),r.invalidateQueries({queryKey:[`linked-spools`]}),R(null)},onError:e=>{i(e.message||n(`inventory.assignFailed`,`Failed to unassign spool`),`error`)}}),ae=(0,y.useCallback)(e=>O===void 0?null:e<=3&&Math.floor(O/4)===e?O%4:e>=128&&e<=135&&O===Gf(e,0,!1)?0:null,[O]),oe=(0,y.useCallback)((e,t,n)=>{let r=Gf(e,t,!1),i=s?.[r],a=N[String(e)],o=e>=128?e-128:e,c=a===void 0?o:a;R({amsId:e,trayId:t,trayCount:n&&e>=128?1:4,tray:n,trayType:n?.tray_type||void 0,trayColor:n?.tray_color||void 0,traySubBrands:n?.tray_sub_brands||void 0,trayInfoIdx:n?.tray_info_idx||void 0,extruderId:k?c:void 0,caliIdx:n?.cali_idx,savedPresetId:i?.preset_id,location:`${y$e(e)} Slot ${t+1}`})},[s,N,k]),U=(0,y.useCallback)(e=>{let t=e.id??254,n=t-254,r=s?.[1020+n];R({amsId:255,trayId:n,trayCount:1,tray:X9(e)?null:e,trayType:e.tray_type||void 0,trayColor:e.tray_color||void 0,traySubBrands:e.tray_sub_brands||void 0,trayInfoIdx:e.tray_info_idx||void 0,extruderId:k?+(t===254):void 0,caliIdx:e.cali_idx,savedPresetId:r?.preset_id,location:k?t===254?`Ext-L`:`Ext-R`:`External`})},[s,k]),se=(0,y.useCallback)(()=>{if(!L)return;let{tray:e,location:t,...n}=L;R(null),I(n)},[L]),ce=(0,y.useCallback)(()=>{if(!L||!e)return;let{amsId:t,trayId:n,trayType:r,trayColor:i,location:a}=L;R(null),B({printerId:e,amsId:t,trayId:n,trayInfo:{type:r||``,material:r,color:i?.slice(0,6)||``,location:a}})},[L,e]),le=(0,y.useCallback)(()=>{if(!L||!e)return;let{amsId:t,trayId:n,tray:r}=L,i=(r?.tray_uuid||r?.tag_uid||Xf(_,t,n))?.toUpperCase()||``;R(null),ee({tagUid:r?.tag_uid||i,trayUuid:r?.tray_uuid||``,printerId:e,amsId:t,trayId:n})},[L,e,_]),ue=(0,y.useCallback)(()=>{if(!L||!e)return;let{amsId:t,trayId:n}=L;re.mutate({printerId:e,amsId:t,trayId:n})},[L,e,re]);(0,y.useEffect)(()=>{if(!b&&e){t({type:`warning`,message:n(`spoolbuddy.ams.printerDisconnected`,`Printer disconnected`)});return}for(let e of S){let n=e.tray||[];for(let r=0;r=0&&i.remain<15&&i.tray_type){let n=e.id===254||e.id===255,a=!n&&e.id>=128,o=Wf(e.id,r,a,n);t({type:`warning`,message:`Low Filament: ${i.tray_type} (${o}) - ${i.remain}% remaining`});return}}}t(null)},[S,b,e,t,n]);let de=(0,y.useMemo)(()=>{let e=[];for(let t of w){let n=t.tray?.[0]||{id:0,tray_color:null,tray_type:``,tray_sub_brands:null,tray_id_name:null,tray_info_idx:null,remain:-1,k:null,cali_idx:null,tag_uid:null,tray_uuid:null,nozzle_temp_min:null,nozzle_temp_max:null},r=v(t.id,0,X9(n)?null:n),i=g[`${t.id}-0`]??null,a=n.remain!=null&&n.remain>=0?n.remain:null,o=i===0&&a!==null&&a>0?null:i;e.push({key:`ht-${t.id}`,label:y$e(t.id),tray:n,isEmpty:X9(n),isActive:ae(t.id)===0,temp:t.temp,humidity:t.humidity,nozzleSide:P(t.id),effectiveFill:r??o??a,onClick:()=>oe(t.id,0,X9(n)?null:n)})}for(let t of A){let r=t.id??254,i=k&&O===254?r===254&&a?.active_extruder===1||r===255&&a?.active_extruder===0:O===r,o=r-254,s=v(255,o,X9(t)?null:t),c=g[`255-${o}`]??null,l=t.remain!=null&&t.remain>=0?t.remain:null,u=c===0&&l!==null&&l>0?null:c;e.push({key:`ext-${r}`,label:k?r===254?n(`printers.extL`,`Ext-L`):n(`printers.extR`,`Ext-R`):n(`printers.ext`,`Ext`),tray:t,isEmpty:X9(t),isActive:i,nozzleSide:null,effectiveFill:s??u??l,onClick:()=>U(t)})}return e},[w,A,k,O,a?.active_extruder,n,ae,P,oe,U,g,v]);return(0,K.jsxs)(`div`,{className:`h-full flex flex-col p-4`,children:[(0,K.jsx)(`div`,{className:`flex-1 min-h-0`,children:e?b?S.length===0&&A.length===0?(0,K.jsx)(`div`,{className:`flex-1 flex items-center justify-center h-full`,children:(0,K.jsxs)(`div`,{className:`text-center text-white/50`,children:[(0,K.jsx)(Ic,{className:`w-12 h-12 mx-auto mb-3 opacity-50`}),(0,K.jsx)(`p`,{className:`text-lg mb-2`,children:n(`spoolbuddy.ams.noData`,`No AMS detected`)}),(0,K.jsx)(`p`,{className:`text-sm`,children:n(`spoolbuddy.ams.connectAms`,`Connect an AMS to see filament slots`)})]})}):(0,K.jsxs)(`div`,{className:`flex flex-col gap-3 h-full`,children:[(0,K.jsx)(`div`,{className:`grid grid-cols-1 md:grid-cols-2 gap-3`,children:C.map(e=>(0,K.jsx)(s$e,{unit:e,activeSlot:ae(e.id),onConfigureSlot:oe,isDualNozzle:k,nozzleSide:P(e.id),thresholds:j,fillOverrides:g,spoolmanFillOverrides:T},e.id))}),de.length>0&&(0,K.jsx)(`div`,{className:`grid grid-cols-2 md:grid-cols-4 gap-3`,children:de.map(({key:e,label:t,tray:n,isEmpty:r,isActive:i,temp:a,humidity:o,nozzleSide:s,effectiveFill:c,onClick:l})=>{let u=x$e(n.tray_color);return(0,K.jsxs)(`div`,{className:`bg-bambu-dark-secondary rounded-lg px-3 py-2 cursor-pointer hover:bg-bambu-dark-secondary/80 transition-all flex items-center gap-3 ${i?`ring-2 ring-bambu-green`:``}`,onClick:l,children:[(0,K.jsxs)(`div`,{className:`relative w-10 h-10 flex-shrink-0`,children:[r?(0,K.jsx)(`div`,{className:`w-full h-full rounded-full border-2 border-dashed border-gray-500 flex items-center justify-center`,children:(0,K.jsx)(`div`,{className:`w-1.5 h-1.5 rounded-full bg-gray-600`})}):(0,K.jsxs)(`svg`,{viewBox:`0 0 56 56`,className:`w-full h-full`,children:[(0,K.jsx)(`circle`,{cx:`28`,cy:`28`,r:`26`,fill:u}),(0,K.jsx)(`circle`,{cx:`28`,cy:`28`,r:`20`,fill:u,style:{filter:`brightness(0.85)`}}),(0,K.jsx)(`ellipse`,{cx:`20`,cy:`20`,rx:`6`,ry:`4`,fill:`white`,opacity:`0.3`}),(0,K.jsx)(`circle`,{cx:`28`,cy:`28`,r:`8`,fill:`#2d2d2d`}),(0,K.jsx)(`circle`,{cx:`28`,cy:`28`,r:`5`,fill:`#1a1a1a`})]}),i&&(0,K.jsx)(`div`,{className:`absolute -bottom-0.5 left-1/2 -translate-x-1/2 w-1.5 h-1.5 bg-bambu-green rounded-full`})]}),(0,K.jsxs)(`div`,{className:`min-w-0`,children:[(0,K.jsxs)(`div`,{className:`flex items-center gap-1`,children:[(0,K.jsx)(`span`,{className:`text-xs text-white/50 font-medium truncate`,children:t}),s&&(0,K.jsx)(K9,{side:s})]}),(0,K.jsx)(`div`,{className:`text-sm text-white/80 truncate`,children:r?`Empty`:n.tray_type||`?`}),(a!=null||o!=null)&&(0,K.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[a!=null&&(0,K.jsx)(a$e,{temp:a,goodThreshold:j?.tempGood,fairThreshold:j?.tempFair}),o!=null&&(0,K.jsx)(i$e,{humidity:o,goodThreshold:j?.humidityGood,fairThreshold:j?.humidityFair})]})]}),!r&&c!=null&&c>=0&&(0,K.jsx)(`div`,{className:`w-1.5 h-8 bg-bambu-dark-tertiary rounded-full overflow-hidden flex-shrink-0 flex flex-col-reverse`,children:(0,K.jsx)(`div`,{className:`w-full rounded-full`,style:{height:`${c}%`,backgroundColor:Kf(c)}})})]},e)})})]}):(0,K.jsx)(`div`,{className:`flex-1 flex items-center justify-center h-full`,children:(0,K.jsx)(`div`,{className:`text-center text-white/50`,children:(0,K.jsx)(`p`,{className:`text-lg mb-2`,children:n(`spoolbuddy.ams.printerDisconnected`,`Printer disconnected`)})})}):(0,K.jsx)(`div`,{className:`flex-1 flex items-center justify-center h-full`,children:(0,K.jsxs)(`div`,{className:`text-center text-white/50`,children:[(0,K.jsx)(`p`,{className:`text-lg mb-2`,children:n(`spoolbuddy.ams.noPrinter`,`No printer selected`)}),(0,K.jsx)(`p`,{className:`text-sm`,children:n(`spoolbuddy.ams.selectPrinter`,`Select a printer from the top bar`)})]})})}),F&&e&&(0,K.jsx)(YU,{isOpen:!!F,onClose:()=>I(null),printerId:e,slotInfo:F,printerModel:b$e(o?.model??null)||void 0,nozzleDiameter:ip(a,F.amsId),fullScreen:!0,onSuccess:()=>{r.invalidateQueries({queryKey:[`slotPresets`,e]}),r.invalidateQueries({queryKey:[`printerStatus`,e]})}}),L&&e&&(()=>{let t=te(L.amsId,L.trayId),r=ne(L.amsId,L.trayId,L.tray),i=u?p.find(t=>t.printer_id===e&&t.ams_id===L.amsId&&t.tray_id===L.trayId):void 0,a=i?m.find(e=>e.id===i.spoolman_spool_id)??null:null;return(0,K.jsxs)(`div`,{className:`fixed inset-0 z-50 flex items-center justify-center`,children:[(0,K.jsx)(`div`,{className:`absolute inset-0 bg-black/60 backdrop-blur-sm`,onClick:()=>R(null)}),(0,K.jsxs)(`div`,{className:`relative w-full max-w-sm mx-4 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl`,children:[(0,K.jsxs)(`div`,{className:`flex items-center justify-between p-4 border-b border-bambu-dark-tertiary`,children:[(0,K.jsxs)(`div`,{className:`flex items-center gap-2`,children:[L.trayColor&&(0,K.jsx)(`span`,{className:`w-4 h-4 rounded-full border border-black/20`,style:{backgroundColor:`#${L.trayColor.slice(0,6)}`}}),(0,K.jsx)(`h2`,{className:`text-lg font-semibold text-white`,children:L.location}),L.traySubBrands&&(0,K.jsxs)(`span`,{className:`text-sm text-bambu-gray`,children:[`(`,L.traySubBrands,`)`]})]}),(0,K.jsx)(`button`,{onClick:()=>R(null),className:`p-1 text-bambu-gray hover:text-white rounded transition-colors`,children:(0,K.jsx)(Hu,{className:`w-5 h-5`})})]}),(0,K.jsxs)(`div`,{className:`p-4 space-y-2`,children:[!u&&t?.spool&&(0,K.jsxs)(`div`,{className:`p-2.5 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary mb-3`,children:[(0,K.jsx)(`p`,{className:`text-xs text-bambu-gray mb-1`,children:n(`inventory.assignedSpool`,`Assigned spool`)}),(0,K.jsxs)(`div`,{className:`flex items-center gap-2`,children:[t.spool.rgba&&(0,K.jsx)(`span`,{className:`w-3 h-3 rounded-full border border-black/20 flex-shrink-0`,style:nf(t.spool.rgba)}),(0,K.jsxs)(`span`,{className:`text-sm text-white`,children:[t.spool.brand?`${t.spool.brand} `:``,t.spool.material,t.spool.color_name?` - ${t.spool.color_name}`:``]}),(0,K.jsxs)(`span`,{className:`text-[10px] font-mono text-zinc-500 shrink-0 ml-auto`,children:[`#`,t.spool.id]})]})]}),u&&r&&!a&&(0,K.jsxs)(`div`,{className:`p-2.5 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary mb-3`,children:[(0,K.jsx)(`p`,{className:`text-xs text-bambu-gray mb-1`,children:n(`spoolman.linkedSpool`,`Linked spool`)}),(0,K.jsx)(`div`,{className:`flex items-center gap-2`,children:(0,K.jsxs)(`span`,{className:`text-sm text-white`,children:[`Spoolman #`,r.id,r.remaining_weight==null?``:` (${Math.round(r.remaining_weight)}g)`]})})]}),u&&a&&(0,K.jsxs)(`div`,{className:`p-2.5 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary mb-3`,children:[(0,K.jsx)(`p`,{className:`text-xs text-bambu-gray mb-1`,children:n(`inventory.assignedSpool`,`Assigned spool`)}),(0,K.jsxs)(`div`,{className:`flex items-center gap-2`,children:[a.rgba&&(0,K.jsx)(`span`,{className:`w-3 h-3 rounded-full border border-black/20 flex-shrink-0`,style:nf(a.rgba)}),(0,K.jsxs)(`span`,{className:`text-sm text-white`,children:[a.brand?`${a.brand} `:``,a.material,a.color_name?` - ${a.color_name}`:``]})]})]}),(0,K.jsxs)(`button`,{onClick:se,className:`w-full flex items-center gap-3 p-3 rounded-lg bg-bambu-dark border border-bambu-dark-tertiary hover:border-bambu-blue transition-colors text-left`,children:[(0,K.jsx)(Ul,{className:`w-5 h-5 text-bambu-blue flex-shrink-0`}),(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`p`,{className:`text-white font-medium`,children:n(`configureAmsSlot.title`)}),(0,K.jsx)(`p`,{className:`text-xs text-bambu-gray`,children:n(`spoolbuddy.ams.configureDesc`,`Set filament preset, K-profile, and color`)})]})]}),!u&&(ap(L?.tray)?null:t?(0,K.jsxs)(`button`,{onClick:ue,disabled:re.isPending,className:`w-full flex items-center gap-3 p-3 rounded-lg bg-bambu-dark border border-bambu-dark-tertiary hover:border-amber-500 transition-colors text-left`,children:[(0,K.jsx)(Du,{className:`w-5 h-5 text-amber-400 flex-shrink-0`}),(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`p`,{className:`text-amber-400 font-medium`,children:n(`inventory.unassignSpool`,`Unassign`)}),(0,K.jsx)(`p`,{className:`text-xs text-bambu-gray`,children:n(`spoolbuddy.ams.unassignDesc`,`Remove inventory spool from this slot`)})]})]}):(0,K.jsxs)(`button`,{onClick:ce,className:`w-full flex items-center gap-3 p-3 rounded-lg bg-bambu-dark border border-bambu-dark-tertiary hover:border-bambu-green transition-colors text-left`,children:[(0,K.jsx)(fl,{className:`w-5 h-5 text-bambu-green flex-shrink-0`}),(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`p`,{className:`text-white font-medium`,children:n(`inventory.assignSpool`)}),(0,K.jsx)(`p`,{className:`text-xs text-bambu-gray`,children:n(`spoolbuddy.ams.assignDesc`,`Track a spool from your inventory`)})]})]})),u&&(r?.id?(0,K.jsxs)(`button`,{onClick:()=>ie.mutate(r.id),disabled:ie.isPending,className:`w-full flex items-center gap-3 p-3 rounded-lg bg-bambu-dark border border-bambu-dark-tertiary hover:border-amber-500 transition-colors text-left active:opacity-50`,children:[(0,K.jsx)(Du,{className:`w-5 h-5 text-amber-400 flex-shrink-0`}),(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`p`,{className:`text-amber-400 font-medium`,children:n(`inventory.unassignSpool`)}),(0,K.jsx)(`p`,{className:`text-xs text-bambu-gray`,children:n(`spoolbuddy.ams.unlinkDesc`,`Remove Spoolman link from this slot`)})]})]}):a?(0,K.jsxs)(`button`,{onClick:()=>H.mutate(a.id),disabled:H.isPending,className:`w-full flex items-center gap-3 p-3 rounded-lg bg-bambu-dark border border-bambu-dark-tertiary hover:border-amber-500 transition-colors text-left active:opacity-50`,children:[(0,K.jsx)(Du,{className:`w-5 h-5 text-amber-400 flex-shrink-0`}),(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`p`,{className:`text-amber-400 font-medium`,children:n(`inventory.unassignSpool`)}),(0,K.jsx)(`p`,{className:`text-xs text-bambu-gray`,children:n(`spoolbuddy.ams.unassignDesc`,`Remove inventory spool from this slot`)})]})]}):(0,K.jsxs)(`button`,{onClick:le,className:`w-full flex items-center gap-3 p-3 rounded-lg bg-bambu-dark border border-bambu-dark-tertiary hover:border-bambu-green transition-colors text-left`,children:[(0,K.jsx)(zc,{className:`w-5 h-5 text-bambu-green flex-shrink-0`}),(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`p`,{className:`text-white font-medium`,children:n(`inventory.assignSpool`)}),(0,K.jsx)(`p`,{className:`text-xs text-bambu-gray`,children:n(`spoolbuddy.ams.linkDesc`,`Link a Spoolman spool to this slot`)})]})]}))]})]})]})})(),z&&(0,K.jsx)(bU,{isOpen:!!z,onClose:()=>{B(null),r.invalidateQueries({queryKey:[`spool-assignments`,e]}),r.invalidateQueries({queryKey:[`spool-assignments`]})},printerId:z.printerId,amsId:z.amsId,trayId:z.trayId,trayInfo:z.trayInfo,spoolmanEnabled:!!u}),V&&(0,K.jsx)(vU,{isOpen:!!V,onClose:()=>ee(null),tagUid:V.tagUid,trayUuid:V.trayUuid,printerId:V.printerId,amsId:V.amsId,trayId:V.trayId})]})}function C$e({type:e,deviceId:t,onClose:n}){let{t:r}=W(),[i,a]=(0,y.useState)(!1),[o,s]=(0,y.useState)(``),[c,l]=(0,y.useState)(``),[u,d]=(0,y.useState)(!1);(0,y.useEffect)(()=>{let e=e=>{e.key===`Escape`&&!i&&n()};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[i,n]);let f=(0,y.useCallback)(async()=>{a(!0),s(``),l(``),d(!0);try{s(r(`spoolbuddy.diagnostic.queuing`,`Queuing diagnostic on device... +In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}()}function w(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n1&&arguments[1]!==void 0?arguments[1]:e;this.caretPosition=e,this.caretPositionEnd=t}},{key:`getInputCandidates`,value:function(e){var t=this,n=this.options,r=n.layoutCandidates,i=n.layoutCandidatesCaseSensitiveMatch;if(!r||T(r)!==`object`)return{};var a=Object.keys(r).filter((function(n){var r=e.substring(0,t.getCaretPositionEnd()||0)||e,a=RegExp(`${t.utilities.escapeRegex(n)}\$`,i?`g`:`gi`);return!!C(r.matchAll(a)).length}));if(a.length>1){var o=a.sort((function(e,t){return t.length-e.length}))[0];return{candidateKey:o,candidateValue:r[o]}}if(a.length){var s=a[0];return{candidateKey:s,candidateValue:r[s]}}return{}}},{key:`showCandidatesBox`,value:function(e,t,n){var r=this;this.candidateBox&&this.candidateBox.show({candidateValue:t,targetElement:n,onSelect:function(t,n){var i=r.options,a=i.layoutCandidatesCaseSensitiveMatch,o=i.disableCandidateNormalization,s=i.enableLayoutCandidatesKeyPress,c=t;o||(c=t.normalize(`NFD`)),typeof r.options.beforeInputUpdate==`function`&&r.options.beforeInputUpdate(r);var l=r.getInput(r.options.inputName,!0),u=r.getCaretPositionEnd()||0,d=l.substring(0,u||0)||l,f=RegExp(`${r.utilities.escapeRegex(e)}\$`,a?`g`:`gi`),p=d.replace(f,c),m=l.replace(d,p),h=p.length-d.length,g=(u||l.length)+h;g<0&&(g=0),r.setInput(m,r.options.inputName,!0),r.setCaretPosition(g),s&&typeof r.options.onKeyPress==`function`&&r.options.onKeyPress(t,n),typeof r.options.onChange==`function`&&r.options.onChange(r.getInput(r.options.inputName,!0),n),typeof r.options.onChangeAll==`function`&&r.options.onChangeAll(r.getAllInputs(),n)}})}},{key:`handleButtonClicked`,value:function(e,t){var n=this.options,r=n.inputName,i=r===void 0?this.defaultName:r,a=n.debug;if(e!==`{//}`){this.input[i]||(this.input[i]=``),typeof this.options.beforeInputUpdate==`function`&&this.options.beforeInputUpdate(this);var o=this.utilities.getUpdatedInput(e,this.input[i],this.caretPosition,this.caretPositionEnd);if(this.utilities.isStandardButton(e)&&this.activeInputElement&&this.input[i]&&this.input[i]===o&&this.caretPosition===0&&this.caretPositionEnd===o.length)return this.setInput(``,this.options.inputName,!0),this.setCaretPosition(0),this.activeInputElement.value=``,this.activeInputElement.setSelectionRange(0,0),void this.handleButtonClicked(e,t);if(typeof this.options.onKeyPress==`function`&&this.options.onKeyPress(e,t),this.input[i]!==o&&(!this.options.inputPattern||this.options.inputPattern&&this.inputPatternIsValid(o))){if(this.options.maxLength&&this.utilities.handleMaxLength(this.input,o))return;var s=this.utilities.getUpdatedInput(e,this.input[i],this.caretPosition,this.caretPositionEnd,!0);if(this.setInput(s,this.options.inputName,!0),a&&console.log(`Input changed:`,this.getAllInputs()),this.options.debug&&console.log(`Caret at: `,this.getCaretPosition(),this.getCaretPositionEnd(),`(${this.keyboardDOMClass})`,t?.type),this.options.syncInstanceInputs&&this.syncInstanceInputs(),typeof this.options.onChange==`function`&&this.options.onChange(this.getInput(this.options.inputName,!0),t),typeof this.options.onChangeAll==`function`&&this.options.onChangeAll(this.getAllInputs(),t),t!=null&&t.target&&this.options.enableLayoutCandidates){var c,l=this.getInputCandidates(o),u=l.candidateKey,d=l.candidateValue;u&&d?this.showCandidatesBox(u,d,this.keyboardDOM):(c=this.candidateBox)==null||c.destroy()}}this.caretPositionEnd&&this.caretPosition!==this.caretPositionEnd&&(this.setCaretPosition(this.caretPositionEnd,this.caretPositionEnd),this.activeInputElement&&this.activeInputElement.setSelectionRange(this.caretPositionEnd,this.caretPositionEnd),this.options.debug&&console.log(`Caret position aligned`,this.caretPosition)),a&&console.log(`Key pressed:`,e)}}},{key:`getMouseHold`,value:function(){return this.isMouseHold}},{key:`setMouseHold`,value:function(e){this.options.syncInstanceInputs?this.dispatch((function(t){t.isMouseHold=e})):this.isMouseHold=e}},{key:`handleButtonMouseDown`,value:function(e,t){var n=this;t&&(this.options.preventMouseDownDefault&&t.preventDefault(),this.options.stopMouseDownPropagation&&t.stopPropagation(),t.target.classList.add(this.activeButtonClass)),this.holdInteractionTimeout&&clearTimeout(this.holdInteractionTimeout),this.holdTimeout&&clearTimeout(this.holdTimeout),this.setMouseHold(!0),this.options.disableButtonHold||(this.holdTimeout=window.setTimeout((function(){(n.getMouseHold()&&(!e.includes(`{`)&&!e.includes(`}`)||e===`{delete}`||e===`{backspace}`||e===`{bksp}`||e===`{space}`||e===`{tab}`)||e===`{arrowright}`||e===`{arrowleft}`||e===`{arrowup}`||e===`{arrowdown}`)&&(n.options.debug&&console.log(`Button held:`,e),n.handleButtonHold(e)),clearTimeout(n.holdTimeout)}),500))}},{key:`handleButtonMouseUp`,value:function(e,t){var n=this;t&&(this.options.preventMouseUpDefault&&t.preventDefault&&t.preventDefault(),this.options.stopMouseUpPropagation&&t.stopPropagation&&t.stopPropagation(),!(t.target===this.keyboardDOM||t.target&&this.keyboardDOM.contains(t.target)||this.candidateBox&&this.candidateBox.candidateBoxElement&&(t.target===this.candidateBox.candidateBoxElement||t.target&&this.candidateBox.candidateBoxElement.contains(t.target)))&&this.candidateBox&&this.candidateBox.destroy()),this.recurseButtons((function(e){e.classList.remove(n.activeButtonClass)})),this.setMouseHold(!1),this.holdInteractionTimeout&&clearTimeout(this.holdInteractionTimeout),e&&typeof this.options.onKeyReleased==`function`&&this.options.onKeyReleased(e,t)}},{key:`handleKeyboardContainerMouseDown`,value:function(e){this.options.preventMouseDownDefault&&e.preventDefault()}},{key:`handleButtonHold`,value:function(e){var t=this;this.holdInteractionTimeout&&clearTimeout(this.holdInteractionTimeout),this.holdInteractionTimeout=window.setTimeout((function(){t.getMouseHold()?(t.handleButtonClicked(e),t.handleButtonHold(e)):clearTimeout(t.holdInteractionTimeout)}),100)}},{key:`syncInstanceInputs`,value:function(){var e=this;this.dispatch((function(t){t.replaceInput(e.input),t.setCaretPosition(e.caretPosition,e.caretPositionEnd)}))}},{key:`clearInput`,value:function(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:this.options.inputName||this.defaultName;this.input[e]=``,this.setCaretPosition(0),this.options.syncInstanceInputs&&this.syncInstanceInputs()}},{key:`getInput`,value:function(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:this.options.inputName||this.defaultName,t=arguments.length>1&&arguments[1]!==void 0&&arguments[1];return this.options.syncInstanceInputs&&!t&&this.syncInstanceInputs(),this.options.rtl?`‫`+this.input[e].replace(`‫`,``).replace(`‬`,``)+`‬`:this.input[e]}},{key:`getAllInputs`,value:function(){var e=this,t={};return Object.keys(this.input).forEach((function(n){t[n]=e.getInput(n,!0)})),t}},{key:`setInput`,value:function(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.options.inputName||this.defaultName,n=arguments.length>2?arguments[2]:void 0;this.input[t]=e,!n&&this.options.syncInstanceInputs&&this.syncInstanceInputs()}},{key:`replaceInput`,value:function(e){this.input=e}},{key:`setOptions`,value:function(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},t=this.changedOptions(e);this.options=Object.assign(this.options,e),t.length&&(this.options.debug&&console.log(`changedOptions`,t),this.onSetOptions(t),this.render())}},{key:`changedOptions`,value:function(e){var t=this;return Object.keys(e).filter((function(n){return JSON.stringify(e[n])!==JSON.stringify(t.options[n])}))}},{key:`onSetOptions`,value:function(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];e.includes(`layoutName`)&&this.candidateBox&&this.candidateBox.destroy(),(e.includes(`layoutCandidatesPageSize`)||e.includes(`layoutCandidates`))&&this.candidateBox&&(this.candidateBox.destroy(),this.candidateBox=new S({utilities:this.utilities,options:this.options}))}},{key:`resetRows`,value:function(){this.keyboardRowsDOM&&this.keyboardRowsDOM.remove(),this.keyboardDOM.className=this.keyboardDOMClass,this.keyboardDOM.setAttribute(`data-skInstance`,this.currentInstanceName),this.buttonElements={}}},{key:`dispatch`,value:function(e){if(!window.SimpleKeyboardInstances)throw console.warn(`SimpleKeyboardInstances is not defined. Dispatch cannot be called.`),Error(`INSTANCES_VAR_ERROR`);return Object.keys(window.SimpleKeyboardInstances).forEach((function(t){e(window.SimpleKeyboardInstances[t],t)}))}},{key:`addButtonTheme`,value:function(e,t){var n=this;t&&e&&(e.split(` `).forEach((function(r){t.split(` `).forEach((function(t){n.options.buttonTheme||(n.options.buttonTheme=[]);var i=!1;n.options.buttonTheme.map((function(e){if(e!=null&&e.class.split(` `).includes(t)){i=!0;var n=e.buttons.split(` `);n.includes(r)||(i=!0,n.push(r),e.buttons=n.join(` `))}return e})),i||n.options.buttonTheme.push({class:t,buttons:e})}))})),this.render())}},{key:`removeButtonTheme`,value:function(e,t){var n=this;if(!e&&!t)return this.options.buttonTheme=[],void this.render();e&&Array.isArray(this.options.buttonTheme)&&this.options.buttonTheme.length&&(e.split(` `).forEach((function(e){var r;(r=n.options)==null||(r=r.buttonTheme)==null||r.map((function(r,i){if(r&&t&&t.includes(r.class)||!t){var a,o=r?.buttons.split(` `).filter((function(t){return t!==e}));r&&o!=null&&o.length?r.buttons=o.join(` `):((a=n.options.buttonTheme)==null||a.splice(i,1),r=null)}return r}))})),this.render())}},{key:`getButtonElement`,value:function(e){var t,n=this.buttonElements[e];return n&&(t=n.length>1?n:n[0]),t}},{key:`inputPatternIsValid`,value:function(e){var t,n=this.options.inputPattern;if((t=n instanceof RegExp?n:n[this.options.inputName||this.defaultName])&&e){var r=t.test(e);return this.options.debug&&console.log(`inputPattern ("${t}"): ${r?`passed`:`did not pass!`}`),r}return!0}},{key:`setEventListeners`,value:function(){if(this.isFirstKeyboardInstance||!this.allKeyboardInstances){this.options.debug&&console.log(`Caret handling started (${this.keyboardDOMClass})`);var e=this.options.physicalKeyboardHighlightPreventDefault,t=e!==void 0&&e;document.addEventListener(`keyup`,this.handleKeyUp,t),document.addEventListener(`keydown`,this.handleKeyDown,t),document.addEventListener(`mouseup`,this.handleMouseUp),document.addEventListener(`touchend`,this.handleTouchEnd),this.options.updateCaretOnSelectionChange&&document.addEventListener(`selectionchange`,this.handleSelectionChange),document.addEventListener(`select`,this.handleSelect)}}},{key:`handleKeyUp`,value:function(e){this.caretEventHandler(e),this.options.physicalKeyboardHighlight&&this.physicalKeyboard.handleHighlightKeyUp(e)}},{key:`handleKeyDown`,value:function(e){this.options.physicalKeyboardHighlight&&this.physicalKeyboard.handleHighlightKeyDown(e)}},{key:`handleMouseUp`,value:function(e){this.caretEventHandler(e)}},{key:`handleTouchEnd`,value:function(e){this.caretEventHandler(e)}},{key:`handleSelect`,value:function(e){this.caretEventHandler(e)}},{key:`handleSelectionChange`,value:function(e){navigator.userAgent.includes(`Firefox`)||this.caretEventHandler(e)}},{key:`caretEventHandler`,value:function(e){var t,n=this;e.target.tagName&&(t=e.target.tagName.toLowerCase()),this.dispatch((function(r){var i=e.target===r.keyboardDOM||e.target&&r.keyboardDOM.contains(e.target);if(n.options.syncInstanceInputs&&Array.isArray(e.path)&&(i=e.path.some((function(e){var t;return e==null||(t=e.hasAttribute)==null?void 0:t.call(e,`data-skInstance`)}))),(t===`textarea`||t===`input`&&[`text`,`search`,`url`,`tel`,`password`].includes(e.target.type))&&!r.options.disableCaretPositioning){var a=e.target.selectionStart,o=e.target.selectionEnd;r.options.rtl&&(a=r.utilities.getRtlOffset(a,r.getInput()),o=r.utilities.getRtlOffset(o,r.getInput())),r.setCaretPosition(a,o),r.activeInputElement=e.target,r.options.debug&&console.log(`Caret at: `,r.getCaretPosition(),r.getCaretPositionEnd(),e&&e.target.tagName.toLowerCase(),`(${r.keyboardDOMClass})`,e?.type)}else !r.options.disableCaretPositioning&&i||e?.type===`selectionchange`||(r.setCaretPosition(null),r.activeInputElement=null,r.options.debug&&console.log(`Caret position reset due to "${e?.type}" event`,e))}))}},{key:`recurseButtons`,value:function(e){var t=this;e&&Object.keys(this.buttonElements).forEach((function(n){return t.buttonElements[n].forEach(e)}))}},{key:`destroy`,value:function(){this.options.debug&&console.log(`Destroying simple-keyboard instance: ${this.currentInstanceName}`);var e=this.options.physicalKeyboardHighlightPreventDefault,t=e!==void 0&&e;document.removeEventListener(`keyup`,this.handleKeyUp,t),document.removeEventListener(`keydown`,this.handleKeyDown,t),document.removeEventListener(`mouseup`,this.handleMouseUp),document.removeEventListener(`touchend`,this.handleTouchEnd),document.removeEventListener(`select`,this.handleSelect),this.options.updateCaretOnSelectionChange&&document.removeEventListener(`selectionchange`,this.handleSelectionChange),document.onpointerup=null,document.ontouchend=null,document.ontouchcancel=null,document.onmouseup=null,this.recurseButtons((function(e){e&&=(e.onpointerdown=null,e.onpointerup=null,e.onpointercancel=null,e.ontouchstart=null,e.ontouchend=null,e.ontouchcancel=null,e.onclick=null,e.onmousedown=null,e.onmouseup=null,e.remove(),null)})),this.keyboardDOM.onpointerdown=null,this.keyboardDOM.ontouchstart=null,this.keyboardDOM.onmousedown=null,this.resetRows(),this.candidateBox&&=(this.candidateBox.destroy(),null),this.activeInputElement=null,this.keyboardDOM.removeAttribute(`data-skInstance`),this.keyboardDOM.innerHTML=``,window.SimpleKeyboardInstances[this.currentInstanceName]=null,delete window.SimpleKeyboardInstances[this.currentInstanceName],this.initialized=!1}},{key:`getButtonThemeClasses`,value:function(e){var t=this.options.buttonTheme,n=[];return Array.isArray(t)&&t.forEach((function(t){if(t&&t.class&&typeof t.class==`string`&&t.buttons&&typeof t.buttons==`string`){var r=t.class.split(` `);t.buttons.split(` `).includes(e)&&(n=[].concat(C(n),C(r)))}else console.warn(`Incorrect "buttonTheme". Please check the documentation.`,t)})),n}},{key:`setDOMButtonAttributes`,value:function(e,t){var n=this.options.buttonAttributes;Array.isArray(n)&&n.forEach((function(n){n.attribute&&typeof n.attribute==`string`&&n.value&&typeof n.value==`string`?n.buttons&&typeof n.buttons==`string`?n.buttons.split(` `).includes(e)&&t(n.attribute,n.value):t(n.attribute,n.value):console.warn(`Incorrect "buttonAttributes". Please check the documentation.`,n)}))}},{key:`onTouchDeviceDetected`,value:function(){this.processAutoTouchEvents(),this.disableContextualWindow()}},{key:`disableContextualWindow`,value:function(){window.oncontextmenu=function(e){var t;if((t=e.target.classList)!=null&&t.contains(`hg-button`))return e.preventDefault(),e.stopPropagation(),!1}}},{key:`processAutoTouchEvents`,value:function(){this.options.autoUseTouchEvents&&(this.options.useTouchEvents=!0,this.options.debug&&console.log(`autoUseTouchEvents: Touch device detected, useTouchEvents enabled.`))}},{key:`onInit`,value:function(){this.options.debug&&console.log(`${this.keyboardDOMClass} Initialized`),this.setEventListeners(),typeof this.options.onInit==`function`&&this.options.onInit(this)}},{key:`beforeFirstRender`,value:function(){this.utilities.isTouchDevice()&&this.onTouchDeviceDetected(),typeof this.options.beforeFirstRender==`function`&&this.options.beforeFirstRender(this),this.isFirstKeyboardInstance&&this.utilities.pointerEventsSupported()&&!this.options.useTouchEvents&&!this.options.useMouseEvents&&this.options.debug&&console.log(`Using PointerEvents as it is supported by this browser`),this.options.useTouchEvents&&this.options.debug&&console.log(`useTouchEvents has been enabled. Only touch events will be used.`)}},{key:`beforeRender`,value:function(){typeof this.options.beforeRender==`function`&&this.options.beforeRender(this)}},{key:`onRender`,value:function(){typeof this.options.onRender==`function`&&this.options.onRender(this)}},{key:`onModulesLoaded`,value:function(){typeof this.options.onModulesLoaded==`function`&&this.options.onModulesLoaded(this)}},{key:`loadModules`,value:function(){var e=this;Array.isArray(this.options.modules)&&(this.options.modules.forEach((function(t){var n=e.utilities.isConstructor(t)?new t(e):t(e);n.init&&n.init(e)})),this.keyboardPluginClasses=`modules-loaded`,this.render(),this.onModulesLoaded())}},{key:`getModuleProp`,value:function(e,t){return!!this.modules[e]&&this.modules[e][t]}},{key:`getModulesList`,value:function(){return Object.keys(this.modules)}},{key:`parseRowDOMContainers`,value:function(e,t,n,r){var i=this,a=Array.from(e.children),o=0;return a.length&&n.forEach((function(n,s){var c=r[s];if(!(c&&c>n))return!1;var l=n-o,u=c-o,d=document.createElement(`div`);d.className+=`hg-button-container`;var f=`${i.options.layoutName}-r${t}c${s}`;d.setAttribute(`data-skUID`,f);var p=a.splice(l,u-l+1);o+=u-l,p.forEach((function(e){return d.appendChild(e)})),a.splice(l,0,d),e.innerHTML=``,a.forEach((function(t){return e.appendChild(t)})),i.options.debug&&console.log(`rowDOMContainer`,p,l,u,o+1)})),e}},{key:`render`,value:function(){var e=this;this.resetRows(),this.initialized||this.beforeFirstRender(),this.beforeRender();var t=`hg-layout-${this.options.layoutName}`,n=this.options.layout||{default:["` 1 2 3 4 5 6 7 8 9 0 - = {bksp}",`{tab} q w e r t y u i o p [ ] \\`,`{lock} a s d f g h j k l ; ' {enter}`,`{shift} z x c v b n m , . / {shift}`,`.com @ {space}`],shift:[`~ ! @ # $ % ^ & * ( ) _ + {bksp}`,`{tab} Q W E R T Y U I O P { } |`,`{lock} A S D F G H J K L : " {enter}`,`{shift} Z X C V B N M < > ? {shift}`,`.com @ {space}`]},r=this.options.useTouchEvents||!1,i=r?`hg-touch-events`:``,a=this.options.useMouseEvents||!1,o=this.options.disableRowButtonContainers;this.keyboardDOM.className=this.getKeyboardClassString(this.options.theme,t,this.keyboardPluginClasses,i),this.keyboardDOM.setAttribute(`data-skInstance`,this.currentInstanceName),this.keyboardRowsDOM=document.createElement(`div`),this.keyboardRowsDOM.className=`hg-rows`,n[this.options.layoutName||this.defaultName].forEach((function(t,n){var i=t.split(` `);e.options.excludeFromLayout&&e.options.excludeFromLayout[e.options.layoutName||e.defaultName]&&(i=i.filter((function(t){return e.options.excludeFromLayout&&!e.options.excludeFromLayout[e.options.layoutName||e.defaultName].includes(t)})));var s=document.createElement(`div`);s.className+=`hg-row`;var c=[],l=[];i.forEach((function(t,i){var u,d=!o&&typeof t==`string`&&t.length>1&&t.indexOf(`[`)===0,f=!o&&typeof t==`string`&&t.length>1&&t.indexOf(`]`)===t.length-1;d&&(c.push(i),t=t.replace(/\[/g,``)),f&&(l.push(i),t=t.replace(/\]/g,``));var p=e.utilities.getButtonClass(t),m=e.utilities.getButtonDisplayName(t,e.options.display,e.options.mergeDisplay),h=e.options.useButtonTag?`button`:`div`,g=document.createElement(h);g.className+=`hg-button ${p}`,(u=g.classList).add.apply(u,C(e.getButtonThemeClasses(t))),e.setDOMButtonAttributes(t,(function(e,t){g.setAttribute(e,t)})),e.activeButtonClass=`hg-activeButton`,!e.utilities.pointerEventsSupported()||r||a?r?(g.ontouchstart=function(n){e.handleButtonClicked(t,n),e.handleButtonMouseDown(t,n)},g.ontouchend=function(n){e.handleButtonMouseUp(t,n)},g.ontouchcancel=function(n){e.handleButtonMouseUp(t,n)}):(g.onclick=function(n){e.setMouseHold(!1),typeof e.options.onKeyReleased==`function`||e.options.useMouseEvents&&e.options.clickOnMouseDown||e.handleButtonClicked(t,n)},g.onmousedown=function(n){(typeof e.options.onKeyReleased==`function`||e.options.useMouseEvents&&e.options.clickOnMouseDown)&&!e.isMouseHold&&e.handleButtonClicked(t,n),e.handleButtonMouseDown(t,n)},g.onmouseup=function(n){e.handleButtonMouseUp(t,n)}):(g.onpointerdown=function(n){e.handleButtonClicked(t,n),e.handleButtonMouseDown(t,n)},g.onpointerup=function(n){e.handleButtonMouseUp(t,n)},g.onpointercancel=function(n){e.handleButtonMouseUp(t,n)}),g.setAttribute(`data-skBtn`,t);var _=`${e.options.layoutName}-r${n}b${i}`;g.setAttribute(`data-skBtnUID`,_);var v=document.createElement(`span`);v.innerHTML=m,g.appendChild(v),e.buttonElements[t]||(e.buttonElements[t]=[]),e.buttonElements[t].push(g),s.appendChild(g)})),s=e.parseRowDOMContainers(s,n,c,l),e.keyboardRowsDOM.appendChild(s)})),this.keyboardDOM.appendChild(this.keyboardRowsDOM),this.onRender(),this.initialized||(this.initialized=!0,!this.utilities.pointerEventsSupported()||r||a?r?(document.ontouchend=function(t){return e.handleButtonMouseUp(void 0,t)},document.ontouchcancel=function(t){return e.handleButtonMouseUp(void 0,t)},this.keyboardDOM.ontouchstart=function(t){return e.handleKeyboardContainerMouseDown(t)}):r||(document.onmouseup=function(t){return e.handleButtonMouseUp(void 0,t)},this.keyboardDOM.onmousedown=function(t){return e.handleKeyboardContainerMouseDown(t)}):(document.onpointerup=function(t){return e.handleButtonMouseUp(void 0,t)},this.keyboardDOM.onpointerdown=function(t){return e.handleKeyboardContainerMouseDown(t)}),this.onInit())}}],t&&D(e.prototype,t),n&&D(e,n),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t,n}(),j=A;return r}()},442:function(t){t.exports=e}},n={};function r(e){var i=n[e];if(i!==void 0)return i.exports;var a=n[e]={exports:{}};return t[e].call(a.exports,a,a.exports,r),a.exports}r.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return r.d(t,{a:t}),t},r.d=function(e,t){for(var n in t)r.o(t,n)&&!r.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},r.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},r.r=function(e){typeof Symbol<`u`&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:`Module`}),Object.defineProperty(e,"__esModule",{value:!0})};var i={};return function(){r.r(i),r.d(i,{KeyboardReact:function(){return u},default:function(){return d}}),r(981);var e=r(442),t=r(548),n=r.n(t);function a(e){return a=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},a(e)}function o(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function s(e){for(var t=1;t{e?.(t)},[t,e]);let d=(0,y.useCallback)(e=>{if(a.current)return;let t=e.target;if(!t.closest(`[data-vkb="false"]`)){if(t instanceof HTMLInputElement){if(!VQe.has(t.type))return}else if(!(t instanceof HTMLTextAreaElement))return;c.current=t,n(!0),s(`default`),l.current?.setInput?.(c.current.value),setTimeout(()=>{(t.closest(`.bg-zinc-800, .rounded-lg, [data-vkb-group]`)??t).scrollIntoView({behavior:`smooth`,block:`nearest`})},100)}},[]),f=(0,y.useCallback)(()=>{setTimeout(()=>{let e=document.activeElement;e&&(u.current?.contains(e)||e===c.current)||(n(!1),c.current=null)},150)},[]);(0,y.useEffect)(()=>(document.addEventListener(`focusin`,d),document.addEventListener(`focusout`,f),()=>{document.removeEventListener(`focusin`,d),document.removeEventListener(`focusout`,f)}),[d,f]);let p=(0,y.useCallback)(()=>{a.current=!0,i(!0),c.current?.blur(),c.current=null,setTimeout(()=>{n(!1),i(!1),a.current=!1},400)},[]),m=(0,y.useCallback)(e=>{let t=c.current;if(t){if(e===`{shift}`){s(e=>e==="default"?`shift`:`default`);return}if(e===`{lock}`){s(e=>e==="default"?`shift`:`default`);return}if(e===`{close}`){p();return}e===`{bksp}`?W9(t,t.value.slice(0,-1)):e===`{space}`?W9(t,t.value+` `):(W9(t,t.value+e),o===`shift`&&s(`default`)),t.focus(),l.current?.setInput?.(t.value)}},[o,p]);return t?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`div`,{className:`fixed inset-0 z-[9998] bg-transparent`,onMouseDown:e=>{e.preventDefault(),e.stopPropagation(),r||p()},onTouchStart:e=>{e.preventDefault(),e.stopPropagation(),r||p()},onClick:e=>{e.preventDefault(),e.stopPropagation()}}),!r&&(0,K.jsx)(`div`,{ref:u,className:`relative z-[9999] shrink-0`,onMouseDown:e=>e.preventDefault(),onTouchStart:e=>{e.target.closest(`.hg-button`)||e.preventDefault()},children:(0,K.jsx)(BQe.default,{keyboardRef:e=>{l.current=e},layoutName:o,onKeyPress:m,theme:`simple-keyboard vkb-theme`,layout:{default:[`1 2 3 4 5 6 7 8 9 0 {bksp}`,`q w e r t y u i o p`,`{lock} a s d f g h j k l`,`{shift} z x c v b n m . @`,`{space} {close}`],shift:[`! @ # $ % ^ & * ( ) {bksp}`,`Q W E R T Y U I O P`,`{lock} A S D F G H J K L`,`{shift} Z X C V B N M , _`,`{space} {close}`]},display:{"{bksp}":`⌫`,"{close}":`✕ Close`,"{shift}":`⇧`,"{lock}":`⇪`,"{space}":` `}})})]}):null}function UQe(){of();let[e,t]=(0,y.useState)(null),[n,r]=(0,y.useState)(null),[i,a]=(0,y.useState)(100),{i18n:o}=W(),s=$n(),c=Xn(),l=zQe(),{setViewportSuppressed:u}=kd();(0,y.useEffect)(()=>(u(!0),()=>u(!1)),[u]);let{data:d}=q({queryKey:[`settings`],queryFn:Q.getSettings});(0,y.useEffect)(()=>{d?.language&&d.language!==o.language&&o.changeLanguage(d.language)},[d?.language,o]);let{data:f=[]}=q({queryKey:[`spoolbuddy-devices`],queryFn:()=>ud.getDevices(),refetchInterval:3e4}),p=f[0],m=l.deviceOnline||!!p?.online,h=(0,y.useMemo)(()=>({...l,deviceOnline:m}),[l,m]),g=(0,y.useRef)(!1);(0,y.useEffect)(()=>{p&&!g.current&&(a(p.display_brightness),g.current=!0)},[p]),(0,y.useEffect)(()=>{let e=document.documentElement,t=e.classList.contains(`dark`);return e.classList.add(`dark`),()=>{t||e.classList.remove(`dark`)}},[]);let{data:_}=q({queryKey:[`spoolbuddy-update-check`,p?.device_id],queryFn:()=>p?ud.checkDaemonUpdate(p.device_id):Promise.resolve(null),enabled:!!p,refetchInterval:300*1e3,staleTime:0}),v=(0,y.useRef)(null);(0,y.useEffect)(()=>{if(!m){let e=`SpoolBuddy device disconnected`;r({type:`warning`,message:e}),v.current=e}else if(_?.update_available&&_.latest_version){let e=`Update available: v${_.latest_version}`;r({type:`info`,message:e}),v.current=e}else v.current&&=(r(null),null)},[m,_?.update_available,_?.latest_version]);let b=!!(l.matchedSpool||l.unknownTagUid||l.unknownTrayUuid),x=(0,y.useRef)(!1);(0,y.useEffect)(()=>{b&&!x.current&&c.pathname!==`/spoolbuddy`&&s(`/spoolbuddy`),x.current=b},[b,c.pathname,s]);let{data:S=[]}=q({queryKey:[`printers`],queryFn:()=>Q.getPrinters()}),C=go({queries:S.map(e=>({queryKey:[`printerStatus`,e.id],queryFn:()=>Q.getPrinterStatus(e.id),refetchInterval:1e4,select:e=>({connected:e?.connected})}))}),w=(0,y.useMemo)(()=>S.filter((e,t)=>C[t]?.data?.connected),[S,C]),T=(0,y.useRef)(null),E=(0,y.useRef)(!1),D=(0,y.useRef)(null),O=(0,y.useCallback)(e=>{T.current={x:e.touches[0].clientX,y:e.touches[0].clientY},E.current=!1},[]),k=(0,y.useCallback)(n=>{if(!T.current)return;let r=n.changedTouches[0].clientX-T.current.x,i=n.changedTouches[0].clientY-T.current.y,a=T.current.y;if(T.current=null,E.current=!1,i>=50&&Math.abs(i)>Math.abs(r)&&a<120){N(!0);return}if(w.length<2||Math.abs(r)<50||Math.abs(i)>Math.abs(r))return;let o=w.findIndex(t=>t.id===e);t(w[r<0?(o+1)%w.length:(o-1+w.length)%w.length].id)},[w,e,t]);(0,y.useEffect)(()=>{let e=D.current;if(!e)return;let t=e=>{if(!T.current)return;let t=Math.abs(e.touches[0].clientX-T.current.x),n=Math.abs(e.touches[0].clientY-T.current.y);if(E.current){e.preventDefault();return}t>10&&t>n&&(E.current=!0,e.preventDefault())};return e.addEventListener(`touchmove`,t,{passive:!1}),()=>e.removeEventListener(`touchmove`,t)},[]);let[A,j]=(0,y.useState)(!1),[M,N]=(0,y.useState)(!1);return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsxs)(`div`,{ref:D,"data-spoolbuddy-kiosk":!0,className:`w-screen h-screen bg-bambu-dark text-white flex flex-col overflow-hidden`,style:{...i<100?{filter:`brightness(${i/100})`}:void 0,overscrollBehaviorX:`none`},onTouchStart:O,onTouchEnd:k,children:[(0,K.jsx)(`button`,{onClick:()=>N(!0),className:`w-full h-1.5 bg-bambu-dark-secondary flex justify-center items-center shrink-0 touch-none`,"aria-label":`Open quick menu`,children:(0,K.jsx)(`div`,{className:`w-8 h-0.5 rounded-full bg-zinc-600`})}),(0,K.jsx)(MQe,{selectedPrinterId:e,onPrinterChange:t,deviceOnline:m}),(0,K.jsx)(`main`,{className:`flex-1 overflow-y-auto`,children:(0,K.jsx)(kr,{context:{selectedPrinterId:e,setSelectedPrinterId:t,sbState:h,setAlert:r,displayBrightness:i,setDisplayBrightness:a}})}),!A&&(0,K.jsx)(FQe,{alert:n}),!A&&(0,K.jsx)(PQe,{}),(0,K.jsx)(HQe,{onVisibilityChange:j})]}),(0,K.jsx)(IQe,{isOpen:M,onClose:()=>N(!1),deviceId:p?.device_id??null,deviceOnline:m})]})}function G9({color:e,isEmpty:t,size:n=32}){return t?(0,K.jsx)(`div`,{className:`rounded-full border-2 border-dashed border-zinc-500 flex items-center justify-center`,style:{width:n,height:n},children:(0,K.jsx)(`div`,{className:`w-2 h-2 rounded-full bg-zinc-600`})}):(0,K.jsxs)(`svg`,{width:n,height:n,viewBox:`0 0 32 32`,children:[(0,K.jsx)(`circle`,{cx:`16`,cy:`16`,r:`14`,fill:e,stroke:`white`,strokeWidth:`1.5`,strokeOpacity:`0.7`}),(0,K.jsx)(`circle`,{cx:`16`,cy:`16`,r:`11`,fill:e,style:{filter:`brightness(0.85)`}})]})}var WQe=`spoolbuddy-default-core-weight`;function GQe(){try{let e=localStorage.getItem(WQe);if(e){let t=parseInt(e,10);if(t>=0&&t<=500)return t}}catch{}return 250}function KQe({spool:e,scaleWeight:t,onClose:n,onSyncWeight:r,onAssignToAms:i,isAssigned:a,onUnassignFromAms:o}){let{t:s}=W(),[c,l]=(0,y.useState)(!1),[u,d]=(0,y.useState)(!1),f=tf(e.rgba),p=e.core_weight&&e.core_weight>0?e.core_weight:GQe(),m=t===null?null:Math.round(Math.max(0,t)),h=m===null?null:Math.round(Math.max(0,m-p)),g=Math.round(e.label_weight||1e3),_=h===null?null:Math.min(100,Math.round(h/g*100)),v=_===null?`#808080`:_>50?`#22c55e`:_>20?`#eab308`:`#ef4444`,b=Math.max(0,(e.label_weight||0)-(e.weight_used||0))+p,x=m===null?null:m-b,S=x===null?null:Math.abs(x)<=50,C=async()=>{if(t!==null){l(!0);try{await ud.updateSpoolWeight(e.id,Math.round(t)),d(!0),r?.(),setTimeout(()=>d(!1),3e3)}catch(e){console.error(`Failed to sync weight:`,e)}finally{l(!1)}}};return(0,K.jsxs)(`div`,{className:`flex flex-col items-center space-y-4 max-w-md`,children:[(0,K.jsxs)(`div`,{className:`flex items-start gap-5`,children:[(0,K.jsxs)(`div`,{className:`relative shrink-0`,children:[(0,K.jsx)(G9,{color:f,isEmpty:!1,size:100}),_!==null&&(0,K.jsxs)(`div`,{className:`absolute -bottom-2 -right-2 px-2 py-0.5 rounded-full text-xs font-bold text-white shadow-lg`,style:{backgroundColor:v},children:[_,`%`]})]}),(0,K.jsxs)(`div`,{className:`flex-1 min-w-0 pt-1`,children:[(0,K.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,K.jsx)(`h3`,{className:`text-lg font-semibold text-zinc-100`,children:e.color_name||`Unknown color`}),(0,K.jsxs)(`span`,{className:`text-xs font-mono text-zinc-500 shrink-0`,children:[`#`,e.id]})]}),(0,K.jsxs)(`p`,{className:`text-sm text-zinc-400`,children:[e.brand,` • `,e.material,e.subtype&&` ${e.subtype}`]}),h!==null&&(0,K.jsxs)(`div`,{className:`mt-3`,children:[(0,K.jsxs)(`div`,{className:`flex items-baseline gap-2`,children:[(0,K.jsxs)(`span`,{className:`text-3xl font-bold font-mono text-zinc-100`,children:[h,`g`]}),(0,K.jsxs)(`span`,{className:`text-sm text-zinc-500`,children:[`/ `,g,`g`]})]}),(0,K.jsx)(`p`,{className:`text-xs text-zinc-500 mt-0.5`,children:s(`spoolbuddy.spool.remaining`,`Remaining`)}),(0,K.jsx)(`div`,{className:`mt-2 max-w-xs`,children:(0,K.jsx)(`div`,{className:`h-2 bg-zinc-700 rounded-full overflow-hidden`,children:(0,K.jsx)(`div`,{className:`h-full rounded-full transition-all duration-500`,style:{width:`${_}%`,backgroundColor:v}})})})]})]})]}),(0,K.jsxs)(`div`,{className:`grid grid-cols-2 gap-x-6 gap-y-2 text-sm bg-zinc-800 rounded-lg p-4 w-full`,children:[(0,K.jsxs)(`div`,{className:`flex justify-between`,children:[(0,K.jsx)(`span`,{className:`text-zinc-500`,children:s(`spoolbuddy.dashboard.grossWeight`,`Gross weight`)}),(0,K.jsx)(`span`,{className:`font-mono text-zinc-300`,children:m===null?`—`:`${m}g`})]}),(0,K.jsxs)(`div`,{className:`flex justify-between`,children:[(0,K.jsx)(`span`,{className:`text-zinc-500`,children:s(`spoolbuddy.spool.coreWeight`,`Core`)}),(0,K.jsxs)(`span`,{className:`font-mono text-zinc-300`,children:[p,`g`]})]}),(0,K.jsxs)(`div`,{className:`flex justify-between`,children:[(0,K.jsx)(`span`,{className:`text-zinc-500`,children:s(`spoolbuddy.dashboard.spoolSize`,`Spool size`)}),(0,K.jsxs)(`span`,{className:`font-mono text-zinc-300`,children:[g,`g`]})]}),(0,K.jsxs)(`div`,{className:`flex justify-between items-center`,children:[(0,K.jsx)(`span`,{className:`text-zinc-500`,children:s(`spoolbuddy.spool.scaleWeight`,`Scale`)}),m===null?(0,K.jsx)(`span`,{className:`text-zinc-500`,children:`—`}):(0,K.jsxs)(`span`,{className:`flex items-center gap-1 font-mono ${S?`text-green-500`:`text-yellow-500`}`,children:[m,`g`,S?(0,K.jsx)(ts,{className:`w-3.5 h-3.5`}):(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(wu,{className:`w-3.5 h-3.5`}),(0,K.jsx)(`button`,{onClick:C,className:`p-1 hover:bg-green-500/20 rounded transition-colors text-green-500`,title:s(`spoolbuddy.dashboard.syncWeight`,`Sync Weight`),children:(0,K.jsx)(kl,{className:`w-4 h-4`})})]})]})]}),(0,K.jsxs)(`div`,{className:`flex justify-between items-center`,children:[(0,K.jsx)(`span`,{className:`text-zinc-500`,children:s(`spoolbuddy.dashboard.tagId`,`Tag`)}),(0,K.jsx)(`span`,{className:`font-mono text-xs text-zinc-400 truncate max-w-[120px]`,title:e.tag_uid||``,children:e.tag_uid?e.tag_uid.slice(-8):`—`})]})]}),(0,K.jsxs)(`div`,{className:`flex gap-2 justify-center`,children:[i&&(0,K.jsx)(`button`,{onClick:a?void 0:i,disabled:!!a,className:`px-5 py-2.5 rounded-lg text-sm font-medium bg-green-600 text-white hover:bg-green-700 transition-colors min-h-[44px] disabled:opacity-50 disabled:cursor-not-allowed`,children:s(`spoolbuddy.modal.assignToAms`,`Assign to AMS`)}),o&&(0,K.jsxs)(`button`,{onClick:o,className:`px-5 py-2.5 rounded-lg text-sm font-medium bg-red-600/20 text-red-400 hover:bg-red-600/30 transition-colors min-h-[44px]`,children:[(0,K.jsx)(Du,{className:`w-4 h-4 inline mr-1`}),s(`inventory.unassignSpool`)]}),(0,K.jsx)(`button`,{onClick:C,disabled:t===null||c,className:`px-5 py-2.5 rounded-lg text-sm font-medium transition-colors min-h-[44px] ${u?`bg-green-600/20 text-green-400`:i?`bg-zinc-700 text-zinc-300 hover:bg-zinc-600 disabled:opacity-40 disabled:cursor-not-allowed`:`bg-green-600 text-white hover:bg-green-700 disabled:opacity-40 disabled:cursor-not-allowed`}`,children:c?`...`:u?s(`spoolbuddy.dashboard.weightSynced`,`Synced!`):s(`spoolbuddy.dashboard.syncWeight`,`Sync Weight`)}),n&&(0,K.jsx)(`button`,{onClick:n,className:`px-5 py-2.5 rounded-lg text-sm font-medium bg-zinc-700 text-zinc-300 hover:bg-zinc-600 transition-colors min-h-[44px]`,children:s(`spoolbuddy.dashboard.close`,`Close`)})]})]})}function qQe({tagUid:e,scaleWeight:t,coreWeight:n,onLinkSpool:r,onAddToInventory:i,onClose:a}){let{t:o}=W(),s=n??GQe(),c=t===null?null:Math.round(Math.max(0,t)),l=c===null?null:Math.round(Math.max(0,c-s));return(0,K.jsxs)(`div`,{className:`flex flex-col items-center text-center space-y-5`,children:[(0,K.jsx)(`div`,{className:`w-20 h-20 rounded-2xl bg-green-500/15 flex items-center justify-center`,children:(0,K.jsx)(`svg`,{className:`w-10 h-10 text-green-500`,fill:`none`,viewBox:`0 0 24 24`,stroke:`currentColor`,children:(0,K.jsx)(`path`,{strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:`2`,d:`M7 7h.01M7 3h5c.512 0 1.024.195 1.414.586l7 7a2 2 0 010 2.828l-7 7a2 2 0 01-2.828 0l-7-7A2 2 0 013 12V7a4 4 0 014-4z`})})}),(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`h3`,{className:`text-lg font-semibold text-zinc-100`,children:o(`spoolbuddy.dashboard.newTag`,`New Tag Detected`)}),(0,K.jsx)(`p`,{className:`text-sm text-zinc-500 font-mono mt-1`,children:e})]}),c!==null&&(0,K.jsxs)(`div`,{className:`text-sm text-zinc-400`,children:[(0,K.jsxs)(`span`,{className:`font-mono font-semibold`,children:[c,`g`]}),` `,o(`spoolbuddy.dashboard.onScale`,`on scale`),l!==null&&l>0&&(0,K.jsxs)(`span`,{className:`text-zinc-500`,children:[` • ~`,l,`g filament`]})]}),(0,K.jsxs)(`div`,{className:`flex flex-wrap gap-2 justify-center`,children:[i&&(0,K.jsx)(`button`,{onClick:i,className:`px-5 py-2.5 rounded-lg text-sm font-medium bg-green-600 text-white hover:bg-green-700 transition-colors min-h-[44px]`,children:o(`spoolbuddy.modal.addToInventory`,`Add to Inventory`)}),r&&(0,K.jsxs)(`button`,{onClick:r,className:`px-5 py-2.5 rounded-lg text-sm font-medium bg-zinc-700 text-zinc-300 hover:bg-zinc-600 transition-colors min-h-[44px]`,children:[(0,K.jsx)(`svg`,{className:`w-4 h-4 inline-block mr-1.5 -mt-0.5`,fill:`none`,viewBox:`0 0 24 24`,stroke:`currentColor`,children:(0,K.jsx)(`path`,{strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:`2`,d:`M13.828 10.172a4 4 0 00-5.656 0l-4 4a4 4 0 105.656 5.656l1.102-1.101m-.758-4.899a4 4 0 005.656 0l4-4a4 4 0 00-5.656-5.656l-1.1 1.1`})}),o(`inventory.assignSpool`,`Assign Spool`)]}),a&&(0,K.jsx)(`button`,{onClick:a,className:`px-5 py-2.5 rounded-lg text-sm font-medium bg-zinc-700 text-zinc-300 hover:bg-zinc-600 transition-colors min-h-[44px]`,children:o(`spoolbuddy.dashboard.close`,`Close`)})]})]})}function JQe(e){return e?`#${e.slice(0,6)}`:`#808080`}function YQe(e){return!e.tray_type||e.tray_type===``}function XQe(e){if(e.tray_type)return null;if(e.exists===!0)return`reset`;if(e.exists===!1)return`physical`;let t=e.state??null;return t===9||t===10?`physical`:`reset`}function ZQe(e){return e<=3?`AMS ${String.fromCharCode(65+e)}`:e>=128&&e<=135?`AMS HT ${String.fromCharCode(65+e-128)}`:`AMS ${e}`}function QQe({className:e}){return(0,K.jsx)(`svg`,{className:e,viewBox:`0 0 36 54`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,children:(0,K.jsx)(`path`,{d:`M17.8131 0.00538C18.4463 -0.15091 20.3648 3.14642 20.8264 3.84781C25.4187 10.816 35.3089 26.9368 35.9383 34.8694C37.4182 53.5822 11.882 61.3357 2.53721 45.3789C-1.73471 38.0791 0.016 32.2049 3.178 25.0232C6.99221 16.3662 12.6411 7.90372 17.8131 0.00538ZM18.3738 7.24807L17.5881 7.48441C14.4452 12.9431 10.917 18.2341 8.19369 23.9368C4.6808 31.29 1.18317 38.5479 7.69403 45.5657C17.3058 55.9228 34.9847 46.8808 31.4604 32.8681C29.2558 24.0969 22.4207 15.2913 18.3776 7.24807H18.3738Z`,fill:`#C3C2C1`})})}function $Qe({className:e}){return(0,K.jsxs)(`svg`,{className:e,viewBox:`0 0 35 53`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,children:[(0,K.jsx)(`path`,{d:`M17.3165 0.0038C17.932 -0.14959 19.7971 3.08645 20.2458 3.77481C24.7103 10.6135 34.3251 26.4346 34.937 34.2198C36.3757 52.5848 11.5505 60.1942 2.46584 44.534C-1.68714 37.3735 0.0148 31.6085 3.08879 24.5603C6.79681 16.0605 12.2884 7.75907 17.3165 0.0038ZM17.8615 7.11561L17.0977 7.34755C14.0423 12.7048 10.6124 17.8974 7.96483 23.4941C4.54975 30.7107 1.14949 37.8337 7.47908 44.721C16.8233 54.8856 34.01 46.0117 30.5838 32.2595C28.4405 23.6512 21.7957 15.0093 17.8652 7.11561H17.8615Z`,fill:`#C3C2C1`}),(0,K.jsx)(`path`,{d:`M5.03547 30.112C9.64453 30.4936 11.632 35.7985 16.4154 35.791C19.6339 35.7873 20.2161 33.2283 22.3853 31.6197C31.6776 24.7286 33.5835 37.4894 27.9881 44.4254C18.1878 56.5653 -1.16063 44.6013 5.03917 30.1158L5.03547 30.112Z`,fill:`#1F8FEB`})]})}function e$e({className:e}){return(0,K.jsxs)(`svg`,{className:e,viewBox:`0 0 36 54`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,children:[(0,K.jsx)(`path`,{d:`M17.9625 4.48059L4.77216 26.3154L2.08228 40.2175L10.0224 50.8414H23.1594L33.3246 42.1693V30.2455L17.9625 4.48059Z`,fill:`#1F8FEB`}),(0,K.jsx)(`path`,{d:`M17.7948 0.00538C18.4273 -0.15091 20.3438 3.14642 20.8048 3.84781C25.3921 10.816 35.2715 26.9368 35.9001 34.8694C37.3784 53.5822 11.8702 61.3357 2.53562 45.3789C-1.73163 38.0829 0.0134 32.2087 3.1757 25.027C6.98574 16.3662 12.6284 7.90372 17.7948 0.00538ZM18.3549 7.24807L17.57 7.48441C14.4306 12.9431 10.9063 18.2341 8.1859 23.9368C4.67686 31.29 1.18305 38.5479 7.68679 45.5657C17.2881 55.9228 34.9476 46.8808 31.4271 32.8681C29.2249 24.0969 22.3974 15.2913 18.3587 7.24807H18.3549Z`,fill:`#C3C2C1`})]})}function t$e({className:e}){return(0,K.jsxs)(`svg`,{className:e,viewBox:`0 0 12 20`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,children:[(0,K.jsx)(`path`,{d:`M6 0.5C4.6 0.5 3.5 1.6 3.5 3V12.1C2.6 12.8 2 13.9 2 15C2 17.2 3.8 19 6 19C8.2 19 10 17.2 10 15C10 13.9 9.4 12.8 8.5 12.1V3C8.5 1.6 7.4 0.5 6 0.5Z`,stroke:`#C3C2C1`,strokeWidth:`1`,fill:`none`}),(0,K.jsx)(`circle`,{cx:`6`,cy:`15`,r:`2.5`,stroke:`#C3C2C1`,strokeWidth:`1`,fill:`none`})]})}function n$e({className:e}){return(0,K.jsxs)(`svg`,{className:e,viewBox:`0 0 12 20`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,children:[(0,K.jsx)(`rect`,{x:`4.5`,y:`8`,width:`3`,height:`4.5`,fill:`#d4a017`,rx:`0.5`}),(0,K.jsx)(`circle`,{cx:`6`,cy:`15`,r:`2`,fill:`#d4a017`}),(0,K.jsx)(`path`,{d:`M6 0.5C4.6 0.5 3.5 1.6 3.5 3V12.1C2.6 12.8 2 13.9 2 15C2 17.2 3.8 19 6 19C8.2 19 10 17.2 10 15C10 13.9 9.4 12.8 8.5 12.1V3C8.5 1.6 7.4 0.5 6 0.5Z`,stroke:`#C3C2C1`,strokeWidth:`1`,fill:`none`})]})}function r$e({className:e}){return(0,K.jsxs)(`svg`,{className:e,viewBox:`0 0 12 20`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,children:[(0,K.jsx)(`rect`,{x:`4.5`,y:`3`,width:`3`,height:`9.5`,fill:`#c62828`,rx:`0.5`}),(0,K.jsx)(`circle`,{cx:`6`,cy:`15`,r:`2`,fill:`#c62828`}),(0,K.jsx)(`path`,{d:`M6 0.5C4.6 0.5 3.5 1.6 3.5 3V12.1C2.6 12.8 2 13.9 2 15C2 17.2 3.8 19 6 19C8.2 19 10 17.2 10 15C10 13.9 9.4 12.8 8.5 12.1V3C8.5 1.6 7.4 0.5 6 0.5Z`,stroke:`#C3C2C1`,strokeWidth:`1`,fill:`none`})]})}function i$e({humidity:e,goodThreshold:t=40,fairThreshold:n=60}){let r,i;return e<=t?(r=`#22a352`,i=QQe):e<=n?(r=`#d4a017`,i=$Qe):(r=`#c62828`,i=e$e),(0,K.jsxs)(`div`,{className:`flex items-center gap-0.5`,children:[(0,K.jsx)(i,{className:`w-3 h-3.5`}),(0,K.jsxs)(`span`,{className:`font-medium tabular-nums text-xs`,style:{color:r},children:[e,`%`]})]})}function a$e({temp:e,goodThreshold:t=28,fairThreshold:n=35}){let r,i;return e<=t?(r=`#22a352`,i=t$e):e<=n?(r=`#d4a017`,i=n$e):(r=`#c62828`,i=r$e),(0,K.jsxs)(`div`,{className:`flex items-center gap-0.5`,children:[(0,K.jsx)(i,{className:`w-3 h-3.5`}),(0,K.jsxs)(`span`,{className:`font-medium tabular-nums text-xs`,style:{color:r},children:[e,`°C`]})]})}function K9({side:e}){return(0,K.jsx)(`span`,{className:`inline-flex items-center justify-center w-4 h-4 text-[9px] font-bold rounded`,style:{backgroundColor:`#1a4d2e`,color:`#00ae42`},children:e})}function o$e({tray:e,slotIndex:t,isActive:n,fillOverride:r,spoolmanFill:i,onClick:a}){let o=YQe(e),s=XQe(e),c=JQe(e.tray_color),l=e.remain!==null&&e.remain!==void 0&&e.remain>=0?e.remain:null,u=i??(r===0&&l!==null&&l>0?null:r)??l;return(0,K.jsxs)(`div`,{className:`relative flex flex-col items-center p-2.5 rounded-lg transition-all ${n?`ring-2 ring-bambu-green`:``} ${a?`cursor-pointer hover:bg-white/5`:``}`,onClick:a,title:a?`AMS Slot ${t+1}`:void 0,children:[(0,K.jsxs)(`div`,{className:`relative w-16 h-16 mb-1`,children:[o?(0,K.jsx)(`div`,{className:`w-full h-full rounded-full border-2 border-dashed border-gray-500 flex items-center justify-center`,children:(0,K.jsx)(`div`,{className:`w-3 h-3 rounded-full bg-gray-600`})}):(0,K.jsxs)(`svg`,{viewBox:`0 0 56 56`,className:`w-full h-full`,children:[(0,K.jsx)(`circle`,{cx:`28`,cy:`28`,r:`26`,fill:c}),(0,K.jsx)(`circle`,{cx:`28`,cy:`28`,r:`20`,fill:c,style:{filter:`brightness(0.85)`}}),(0,K.jsx)(`ellipse`,{cx:`20`,cy:`20`,rx:`6`,ry:`4`,fill:`white`,opacity:`0.3`}),(0,K.jsx)(`circle`,{cx:`28`,cy:`28`,r:`8`,fill:`#2d2d2d`}),(0,K.jsx)(`circle`,{cx:`28`,cy:`28`,r:`5`,fill:`#1a1a1a`})]}),n&&(0,K.jsx)(`div`,{className:`absolute -bottom-1 left-1/2 -translate-x-1/2 w-2.5 h-2.5 bg-bambu-green rounded-full`})]}),(0,K.jsx)(`span`,{className:`text-sm text-white/70 truncate max-w-full`,title:s===`reset`?`Spool loaded — slot not configured`:void 0,children:o?s===`reset`?`?`:`Empty`:e.tray_type||`Unknown`}),!o&&u!==null&&u>=0&&(0,K.jsx)(`div`,{className:`w-full h-1 bg-bambu-dark-tertiary rounded-full overflow-hidden mt-1`,children:(0,K.jsx)(`div`,{className:`h-full rounded-full transition-all`,style:{width:`${u}%`,backgroundColor:Kf(u)}})}),(0,K.jsx)(`span`,{className:`absolute top-1 right-1 text-xs text-white/30`,children:t+1})]})}function s$e({unit:e,activeSlot:t,onConfigureSlot:n,isDualNozzle:r,nozzleSide:i,thresholds:a,fillOverrides:o,spoolmanFillOverrides:s}){let c=e.tray||[],l=e.is_ams_ht,u=l?1:4;return(0,K.jsxs)(`div`,{className:`bg-bambu-dark-secondary rounded-lg p-3`,children:[(0,K.jsxs)(`div`,{className:`flex items-center justify-between mb-2`,children:[(0,K.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,K.jsx)(`span`,{className:`text-white font-medium text-base`,children:ZQe(e.id)}),r&&i&&(0,K.jsx)(K9,{side:i})]}),(0,K.jsxs)(`div`,{className:`flex items-center gap-2`,children:[e.temp!=null&&(0,K.jsx)(a$e,{temp:e.temp,goodThreshold:a?.tempGood,fairThreshold:a?.tempFair}),e.humidity!=null&&(0,K.jsx)(i$e,{humidity:e.humidity,goodThreshold:a?.humidityGood,fairThreshold:a?.humidityFair})]})]}),(0,K.jsx)(`div`,{className:`grid ${l?`grid-cols-1 max-w-[100px] mx-auto`:`grid-cols-4`} gap-2`,children:Array.from({length:u}).map((r,i)=>{let a=c[i]||{id:i,tray_color:null,tray_type:``,tray_sub_brands:null,tray_id_name:null,tray_info_idx:null,remain:-1,k:null,cali_idx:null,tag_uid:null,tray_uuid:null,nozzle_temp_min:null,nozzle_temp_max:null};return(0,K.jsx)(o$e,{tray:a,slotIndex:i,isActive:t===i,fillOverride:o?.[`${e.id}-${i}`]??null,spoolmanFill:s?.[`${e.id}-${i}`]??null,onClick:n?()=>n(e.id,i,YQe(a)?null:a):void 0},i)})})]})}function q9(e){return e<=3?`AMS ${String.fromCharCode(65+e)}`:e>=128&&e<=135?`AMS HT ${String.fromCharCode(65+e-128)}`:`AMS ${e}`}function J9(e){return!e.tray_type||e.tray_type===``}function c$e(e){return e?`#${e.slice(0,6)}`:`#808080`}var Y9=e=>(e??``).trim().toUpperCase();function l$e(e,t){let n=Y9(e),r=Y9(t);return!n||!r?`none`:n===r?`exact`:r.includes(n)||n.includes(r)?`partial`:`none`}function u$e(e,t){let n=Y9(e),r=Y9(t);return!n||!r?!1:n===r}function d$e({isOpen:e,onClose:t,spool:n,printerId:r,spoolmanMode:i=!1}){let{t:a}=W(),o=to(),[s,c]=(0,y.useState)(null),[l,u]=(0,y.useState)(null),[d,f]=(0,y.useState)(!1),[p,m]=(0,y.useState)(null),[h,g]=(0,y.useState)(null);(0,y.useEffect)(()=>{e&&(c(null),u(null),f(!1),m(null),g(null))},[e]);let _=(0,y.useCallback)(e=>{e.key===`Escape`&&t()},[t]);(0,y.useEffect)(()=>(e&&document.addEventListener(`keydown`,_),()=>document.removeEventListener(`keydown`,_)),[e,_]);let{data:v}=q({queryKey:[`printerStatus`,r],queryFn:()=>Q.getPrinterStatus(r),enabled:e&&r!==null,refetchInterval:5e3}),{data:b}=q({queryKey:[`printer`,r],queryFn:()=>Q.getPrinter(r),enabled:e&&r!==null}),{data:x}=q({queryKey:[`settings`],queryFn:()=>Q.getSettings(),enabled:e,staleTime:300*1e3}),{data:S}=q({queryKey:[`spool-assignments`,r],queryFn:()=>Q.getAssignments(r),enabled:e&&r!==null,staleTime:30*1e3}),{data:C=[]}=q({queryKey:[`spoolman-slot-assignments`,r],queryFn:()=>Q.getSpoolmanSlotAssignments(r??void 0),enabled:e&&!!i&&r!==null,staleTime:30*1e3}),w=i?C.find(e=>e.spoolman_spool_id===n.id):void 0,T=(0,y.useMemo)(()=>{let e={};if(!S)return e;for(let t of S){let n=t.spool;if(n&&n.label_weight>0&&n.weight_used!=null){let r=Math.round(Math.max(0,n.label_weight-n.weight_used)/n.label_weight*100);e[`${t.ams_id}-${t.tray_id}`]=r}}return e},[S]),E=x?{humidityGood:Number(x.ams_humidity_good)||40,humidityFair:Number(x.ams_humidity_fair)||60,tempGood:Number(x.ams_temp_good)||28,tempFair:Number(x.ams_temp_fair)||35}:void 0,D=v?.connected??!1,O=(0,y.useMemo)(()=>v?.ams??[],[v?.ams]),k=(0,y.useMemo)(()=>O.filter(e=>!e.is_ams_ht),[O]),A=(0,y.useMemo)(()=>O.filter(e=>e.is_ams_ht),[O]),j=(0,y.useMemo)(()=>[...v?.vt_tray??[]].sort((e,t)=>(e.id??254)-(t.id??254)),[v?.vt_tray]),M=b?.nozzle_count===2||v?.temperatures?.nozzle_2!==void 0,N=(0,y.useRef)({});(0,y.useEffect)(()=>{v?.ams_extruder_map&&Object.keys(v.ams_extruder_map).length>0&&(N.current=v.ams_extruder_map)},[v?.ams_extruder_map]);let P=v?.ams_extruder_map&&Object.keys(v.ams_extruder_map).length>0?v.ams_extruder_map:N.current,F=(0,y.useCallback)(e=>{if(!M)return null;let t=P[String(e)],n=e>=128?e-128:e;return(t===void 0?n:t)===1?`L`:`R`},[M,P]),I=J({mutationFn:async({amsId:e,trayId:t})=>{if(!r)throw Error(`No printer selected`);return i?await Q.assignSpoolmanSlot({spoolman_spool_id:n.id,printer_id:r,ams_id:e,tray_id:t}):await Q.assignSpool({spool_id:n.id,printer_id:r,ams_id:e,tray_id:t})},onSuccess:e=>{u(`success`);let n=e&&`pending_config`in e&&e.pending_config;c(n?a(`spoolbuddy.modal.assignPendingInsert`,`Assigned. Slot will configure when you insert the spool.`):a(`spoolbuddy.modal.assignSuccess`,`Assigned!`)),o.invalidateQueries({queryKey:[`slotPresets`]}),o.invalidateQueries({queryKey:[`spoolman-slot-assignments`]}),o.invalidateQueries({queryKey:[`spoolman-slot-assignments-all`]}),setTimeout(()=>t(),n?2500:1500)},onError:e=>{u(`error`),c(e instanceof Error?e.message:a(`spoolbuddy.modal.assignError`,`Failed to assign spool.`))}}),L=I.isPending,R=(0,y.useCallback)((e,t)=>{if(e===254||e===255){let n=e===254?254:254+t;return j.find(e=>(e.id??254)===n)||null}return O.find(t=>t.id===e)?.tray?.find(e=>e.id===t)||null},[O,j]),z=(0,y.useCallback)((e,t)=>e<=3?`${q9(e)} ${a(`ams.slot`,`Slot`)} ${t+1}`:e>=128&&e<=135?q9(e):e===254?a(`printers.extL`,`Ext-L`):M?a(`printers.extR`,`Ext-R`):a(`printers.ext`,`Ext`),[a,M]),B=(0,y.useCallback)((e,t)=>{u(`info`),c(a(`spoolbuddy.modal.assigning`,`Configuring slot...`)),I.mutate({amsId:e,trayId:t})},[I,a]),V=(0,y.useCallback)((e,t)=>{if(!L){if(!x?.disable_filament_warnings){let r=R(e,t);if(r&&!J9(r)){let i=r.tray_sub_brands||r.tray_type||``,a=l$e(n.material,i),o=n.slicer_filament_name||n.slicer_filament,s=r.tray_type||``,c=u$e(o,s);if(a!==`exact`){let r;r=a===`none`&&!c?`material_profile`:a===`partial`&&!c?`partial_profile`:a===`none`?`material`:`partial`;let l=z(e,t);g({amsId:e,trayId:t}),m({type:r,spoolMaterial:n.material||``,trayMaterial:i||``,spoolProfile:o||void 0,trayProfile:s||void 0,location:l}),f(!0);return}}}B(e,t)}},[L,x?.disable_filament_warnings,n,R,z,B]),ee=(0,y.useCallback)(()=>{h&&(f(!1),m(null),B(h.amsId,h.trayId),g(null))},[h,B]),te=(0,y.useMemo)(()=>{let e=[];for(let t of A){let n=t.tray?.[0]||{id:0,tray_color:null,tray_type:``,tray_sub_brands:null,tray_id_name:null,tray_info_idx:null,remain:-1,k:null,cali_idx:null,tag_uid:null,tray_uuid:null,nozzle_temp_min:null,nozzle_temp_max:null},r=T[`${t.id}-0`]??null,i=n.remain!=null&&n.remain>=0?n.remain:null,a=r===0&&i!==null&&i>0?null:r;e.push({key:`ht-${t.id}`,label:q9(t.id),amsId:t.id,trayId:0,tray:n,isEmpty:J9(n),nozzleSide:F(t.id),effectiveFill:a??i})}for(let t of j){let n=t.id??254,r=n-254,i=T[`255-${r}`]??null,o=t.remain!=null&&t.remain>=0?t.remain:null,s=i===0&&o!==null&&o>0?null:i;e.push({key:`ext-${n}`,label:M?n===254?a(`printers.extL`,`Ext-L`):a(`printers.extR`,`Ext-R`):a(`printers.ext`,`Ext`),amsId:255,trayId:r,tray:t,isEmpty:J9(t),nozzleSide:M?n===254?`L`:`R`:null,effectiveFill:s??o})}return e},[A,j,M,a,F,T]);return e?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsxs)(`div`,{className:`fixed inset-0 z-[60] bg-bambu-dark flex flex-col`,children:[(0,K.jsxs)(`div`,{className:`flex items-center justify-between px-5 py-3 border-b border-zinc-800 shrink-0`,children:[(0,K.jsxs)(`div`,{className:`flex items-center gap-3 min-w-0`,children:[(0,K.jsx)(`div`,{className:`w-7 h-7 rounded-full shrink-0`,style:nf(n.rgba)}),(0,K.jsx)(`div`,{className:`min-w-0`,children:(0,K.jsxs)(`h2`,{className:`text-sm font-semibold text-zinc-100 truncate`,children:[a(`spoolbuddy.modal.assignToAmsTitle`,`Assign to AMS`),(0,K.jsxs)(`span`,{className:`font-normal text-zinc-500 ml-2`,children:[n.color_name||`Unknown`,` • `,n.brand,` `,n.material,n.subtype&&` ${n.subtype}`]}),(0,K.jsxs)(`span`,{className:`text-[10px] font-mono text-zinc-500 ml-2 shrink-0`,children:[`#`,n.id]})]})})]}),(0,K.jsx)(`button`,{onClick:t,disabled:L,className:`p-2 rounded-lg text-zinc-500 hover:text-zinc-300 hover:bg-zinc-800 transition-colors shrink-0 disabled:opacity-50`,children:(0,K.jsx)(Hu,{className:`w-5 h-5`})})]}),s&&(0,K.jsxs)(`div`,{className:`mx-5 mt-3 p-3 rounded-lg flex items-center gap-3 border shrink-0 ${l===`info`?`bg-blue-500/10 border-blue-500/40`:l===`success`?`bg-green-500/10 border-green-500/40`:`bg-red-500/10 border-red-500/40`}`,children:[l===`info`&&(0,K.jsx)(X,{className:`w-4 h-4 text-blue-400 animate-spin shrink-0`}),l===`success`&&(0,K.jsx)(ds,{className:`w-4 h-4 text-green-400 shrink-0`}),l===`error`&&(0,K.jsx)(_s,{className:`w-4 h-4 text-red-400 shrink-0`}),(0,K.jsx)(`span`,{className:`text-sm ${l===`info`?`text-blue-300`:l===`success`?`text-green-300`:`text-red-300`}`,children:s})]}),(0,K.jsx)(`div`,{className:`flex-1 flex flex-col gap-3 p-4 min-h-0 overflow-y-auto`,children:!D&&r?(0,K.jsx)(`div`,{className:`flex-1 flex items-center justify-center`,children:(0,K.jsx)(`div`,{className:`text-center text-white/50`,children:(0,K.jsx)(`p`,{className:`text-lg mb-2`,children:a(`spoolbuddy.ams.printerDisconnected`,`Printer disconnected`)})})}):O.length===0&&j.length===0?(0,K.jsx)(`div`,{className:`flex-1 flex items-center justify-center`,children:(0,K.jsxs)(`div`,{className:`text-center text-white/50`,children:[(0,K.jsx)(Ic,{className:`w-12 h-12 mx-auto mb-3 opacity-50`}),(0,K.jsx)(`p`,{className:`text-lg mb-2`,children:a(`spoolbuddy.ams.noData`,`No AMS detected`)}),(0,K.jsx)(`p`,{className:`text-sm`,children:a(`spoolbuddy.ams.connectAms`,`Connect an AMS to see filament slots`)})]})}):(0,K.jsxs)(K.Fragment,{children:[k.length>0&&(0,K.jsx)(`div`,{className:`grid grid-cols-1 md:grid-cols-2 gap-3 flex-1 min-h-0`,children:k.map(e=>(0,K.jsx)(s$e,{unit:e,activeSlot:w?.ams_id===e.id?w.tray_id??null:null,onConfigureSlot:(t,n)=>V(e.id,n),isDualNozzle:M,nozzleSide:F(e.id),thresholds:E,fillOverrides:T},e.id))}),te.length>0&&(0,K.jsx)(`div`,{className:`flex gap-2 shrink-0`,children:te.map(({key:e,label:t,amsId:n,trayId:r,tray:i,isEmpty:a,nozzleSide:o,effectiveFill:s})=>{let c=c$e(i.tray_color);return(0,K.jsxs)(`div`,{onClick:()=>V(n,r),className:`bg-bambu-dark-secondary rounded-lg px-3 py-2 cursor-pointer hover:bg-bambu-dark-secondary/80 transition-all flex items-center gap-2 ${w&&w.ams_id===n&&w.tray_id===r?`ring-2 ring-bambu-green`:``} ${L?`opacity-50 pointer-events-none`:``}`,children:[(0,K.jsx)(`div`,{className:`relative w-10 h-10 shrink-0`,children:a?(0,K.jsx)(`div`,{className:`w-full h-full rounded-full border-2 border-dashed border-gray-500 flex items-center justify-center`,children:(0,K.jsx)(`div`,{className:`w-1.5 h-1.5 rounded-full bg-gray-600`})}):(0,K.jsxs)(`svg`,{viewBox:`0 0 56 56`,className:`w-full h-full`,children:[(0,K.jsx)(`circle`,{cx:`28`,cy:`28`,r:`26`,fill:c}),(0,K.jsx)(`circle`,{cx:`28`,cy:`28`,r:`20`,fill:c,style:{filter:`brightness(0.85)`}}),(0,K.jsx)(`ellipse`,{cx:`20`,cy:`20`,rx:`6`,ry:`4`,fill:`white`,opacity:`0.3`}),(0,K.jsx)(`circle`,{cx:`28`,cy:`28`,r:`8`,fill:`#2d2d2d`}),(0,K.jsx)(`circle`,{cx:`28`,cy:`28`,r:`5`,fill:`#1a1a1a`})]})}),(0,K.jsxs)(`div`,{className:`min-w-0`,children:[(0,K.jsxs)(`div`,{className:`flex items-center gap-1`,children:[(0,K.jsx)(`span`,{className:`text-xs text-white/50 font-medium`,children:t}),o&&(0,K.jsx)(K9,{side:o})]}),(0,K.jsx)(`div`,{className:`text-sm text-white/80 truncate`,children:a?`Empty`:i.tray_type||`?`})]}),!a&&s!=null&&s>=0&&(0,K.jsx)(`div`,{className:`w-1.5 h-8 bg-bambu-dark-tertiary rounded-full overflow-hidden shrink-0 flex flex-col-reverse`,children:(0,K.jsx)(`div`,{className:`w-full rounded-full`,style:{height:`${s}%`,backgroundColor:Kf(s)}})})]},e)})})]})}),(0,K.jsx)(`div`,{className:`flex justify-end gap-3 px-5 py-3 border-t border-zinc-800 shrink-0`,children:(0,K.jsx)(`button`,{onClick:t,disabled:L,className:`px-5 py-2.5 rounded-lg text-sm font-medium bg-zinc-800 text-zinc-300 hover:bg-zinc-700 transition-colors min-h-[44px] disabled:opacity-50`,children:l===`success`?a(`spoolbuddy.dashboard.close`,`Close`):a(`spoolbuddy.modal.cancel`,`Cancel`)})})]}),d&&p&&(()=>{let e=``;return p.type===`material`?e=a(`inventory.assignMismatchMessage`,{spoolMaterial:p.spoolMaterial,trayMaterial:p.trayMaterial,location:p.location}):p.type===`partial`?e=a(`inventory.assignPartialMismatchMessage`,{spoolMaterial:p.spoolMaterial,trayMaterial:p.trayMaterial,location:p.location}):p.type===`material_profile`?e=`${a(`inventory.assignMismatchMessage`,{spoolMaterial:p.spoolMaterial,trayMaterial:p.trayMaterial,location:p.location})}\n\n${a(`inventory.assignProfileMismatchMessage`,{spoolProfile:p.spoolProfile||a(`common.unknown`),trayProfile:p.trayProfile||a(`common.unknown`),location:p.location})}`:p.type===`partial_profile`&&(e=`${a(`inventory.assignPartialMismatchMessage`,{spoolMaterial:p.spoolMaterial,trayMaterial:p.trayMaterial,location:p.location})}\n\n${a(`inventory.assignProfileMismatchMessage`,{spoolProfile:p.spoolProfile||a(`common.unknown`),trayProfile:p.trayProfile||a(`common.unknown`),location:p.location})}`),e=`${e}\n\n${a(`inventory.assignReconfigureNote`)}`,(0,K.jsx)(Rd,{title:a(`inventory.assignMismatchTitle`),message:e,confirmText:a(`inventory.assignMismatchConfirm`),variant:`warning`,isLoading:I.isPending,onConfirm:ee,onCancel:()=>{I.isPending||(f(!1),g(null),m(null))}})})()]}):null}function f$e({isOpen:e,onClose:t,tagId:n,untaggedSpools:r,onLink:i}){let{t:a}=W(),[o,s]=(0,y.useState)(null),c=(0,y.useCallback)(()=>{s(null),t()},[t]),l=(0,y.useCallback)(e=>{e.key===`Escape`&&c()},[c]);return(0,y.useEffect)(()=>(e&&(document.addEventListener(`keydown`,l),document.body.style.overflow=`hidden`),()=>{document.removeEventListener(`keydown`,l),document.body.style.overflow=``}),[e,l]),e?(0,K.jsx)(`div`,{className:`fixed inset-0 z-50 flex items-center justify-center bg-black/70 animate-fade-in`,onClick:c,children:(0,K.jsxs)(`div`,{className:`bg-zinc-800 rounded-xl shadow-2xl w-full max-w-lg mx-4 animate-slide-up`,onClick:e=>e.stopPropagation(),children:[(0,K.jsxs)(`div`,{className:`flex items-center justify-between px-5 py-4 border-b border-zinc-700`,children:[(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`h2`,{className:`text-base font-semibold text-zinc-100`,children:a(`spoolbuddy.dashboard.linkTagTitle`,`Link Tag to Spool`)}),(0,K.jsx)(`p`,{className:`text-sm text-zinc-500 font-mono`,children:n})]}),(0,K.jsx)(`button`,{onClick:c,className:`p-2 rounded-lg text-zinc-500 hover:text-zinc-300 hover:bg-zinc-700 transition-colors`,children:(0,K.jsx)(Hu,{className:`w-5 h-5`})})]}),(0,K.jsxs)(`div`,{className:`px-5 py-4 space-y-3 max-h-[400px] overflow-y-auto`,children:[(0,K.jsx)(`p`,{className:`text-sm text-zinc-400`,children:a(`spoolbuddy.dashboard.selectSpool`,`Select a spool to link this tag to:`)}),r.length===0?(0,K.jsx)(`div`,{className:`text-center py-8 text-zinc-500`,children:a(`spoolbuddy.dashboard.noUntagged`,`No spools without tags found`)}):(0,K.jsx)(`div`,{className:`space-y-2`,children:r.map(e=>(0,K.jsxs)(`button`,{type:`button`,onClick:()=>s(e),className:`w-full flex items-center gap-3 p-3 rounded-lg border-2 transition-all text-left ${o?.id===e.id?`border-green-500 bg-green-500/10`:`border-zinc-700 hover:border-green-500/50 hover:bg-zinc-700/50`}`,children:[(0,K.jsx)(G9,{color:tf(e.rgba),isEmpty:!1,size:40}),(0,K.jsxs)(`div`,{className:`flex-1 min-w-0`,children:[(0,K.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,K.jsx)(`div`,{className:`font-medium text-zinc-100 truncate`,children:e.color_name||`Unknown color`}),(0,K.jsxs)(`span`,{className:`text-[10px] font-mono text-zinc-500 shrink-0`,children:[`#`,e.id]})]}),(0,K.jsxs)(`div`,{className:`text-sm text-zinc-400 truncate`,children:[e.brand,` • `,e.material,e.subtype&&` ${e.subtype}`]})]}),(0,K.jsxs)(`div`,{className:`text-sm font-mono text-zinc-500`,children:[Math.max(0,e.label_weight-e.weight_used),`g`]})]},e.id))})]}),(0,K.jsxs)(`div`,{className:`flex justify-end gap-2 px-5 py-4 border-t border-zinc-700`,children:[(0,K.jsx)(`button`,{onClick:c,className:`px-4 py-2.5 rounded-lg text-sm font-medium bg-zinc-700 text-zinc-300 hover:bg-zinc-600 transition-colors min-h-[44px]`,children:a(`common.cancel`,`Cancel`)}),(0,K.jsx)(`button`,{onClick:()=>{o&&(i(o),s(null))},disabled:!o,className:`px-4 py-2.5 rounded-lg text-sm font-medium bg-green-600 text-white hover:bg-green-700 disabled:opacity-40 disabled:cursor-not-allowed transition-colors min-h-[44px]`,children:a(`spoolbuddy.dashboard.linkTag`,`Link Tag`)})]})]})}):null}function p$e(e){return e?e.replace(/[^0-9a-f]/gi,``).toUpperCase():``}function m$e(e,t){let n=p$e(e),r=p$e(t);return!n||!r?!1:n===r?!0:n.endsWith(r)||r.endsWith(n)}var h$e=[`#00AE42`,`#FF6B35`,`#3B82F6`,`#EF4444`,`#A855F7`,`#FBBF24`,`#14B8A6`,`#EC4899`,`#F97316`,`#22C55E`];function g$e(){let{t:e}=W(),[t,n]=(0,y.useState)(0);(0,y.useEffect)(()=>{let e=setInterval(()=>{n(e=>(e+1)%h$e.length)},5e3);return()=>clearInterval(e)},[]);let r=h$e[t];return(0,K.jsxs)(`div`,{className:`flex flex-col items-center text-center`,children:[(0,K.jsxs)(`div`,{className:`relative mb-6 flex items-center justify-center`,style:{width:160,height:160},children:[(0,K.jsx)(`div`,{className:`absolute inset-0 flex items-center justify-center pointer-events-none`,children:[0,1].map(e=>(0,K.jsx)(`div`,{className:`absolute rounded-full border spoolbuddy-optimized-ping`,style:{width:80,height:80,borderColor:`${r}4D`,transition:`border-color 140ms linear`,animationDelay:`${e*.8}s`}},e))}),(0,K.jsxs)(`div`,{className:`relative overflow-hidden rounded-full`,children:[(0,K.jsx)(`div`,{className:`absolute inset-0 rounded-full opacity-30 spoolbuddy-spool-glow`,style:{background:`radial-gradient(circle, ${r} 0%, transparent 70%)`}}),(0,K.jsx)(`div`,{className:`relative`,style:{transition:`opacity 140ms linear`},children:(0,K.jsx)(G9,{color:r,isEmpty:!1,size:100})})]})]}),(0,K.jsxs)(`div`,{className:`space-y-2`,children:[(0,K.jsx)(`p`,{className:`text-xl font-medium text-zinc-300`,children:e(`spoolbuddy.dashboard.readyToScan`,`Ready to scan`)}),(0,K.jsx)(`p`,{className:`text-sm text-zinc-500`,children:e(`spoolbuddy.dashboard.idleMessage`,`Place a spool on the scale to identify it`)})]}),(0,K.jsxs)(`div`,{className:`mt-6 flex items-center gap-2 text-sm text-zinc-600`,children:[(0,K.jsx)(`svg`,{className:`w-4 h-4`,fill:`none`,viewBox:`0 0 24 24`,stroke:`currentColor`,children:(0,K.jsx)(`path`,{strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:`2`,d:`M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z`})}),(0,K.jsx)(`span`,{children:e(`spoolbuddy.dashboard.nfcHint`,`NFC tag will be read automatically`)})]})]})}function _$e(){let{t:e}=W();return(0,K.jsxs)(`div`,{className:`flex flex-col items-center text-center`,children:[(0,K.jsx)(`div`,{className:`relative mb-6 flex items-center justify-center`,style:{width:160,height:160},children:(0,K.jsx)(`div`,{className:`w-24 h-24 rounded-full bg-zinc-800 flex items-center justify-center`,children:(0,K.jsx)(`svg`,{className:`w-12 h-12 text-zinc-600`,fill:`none`,viewBox:`0 0 24 24`,stroke:`currentColor`,children:(0,K.jsx)(`path`,{strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:`1.5`,d:`M18.364 5.636a9 9 0 010 12.728m0 0l-12.728-12.728m12.728 12.728L5.636 5.636m12.728 0a9 9 0 00-12.728 0m0 12.728a9 9 0 010-12.728`})})})}),(0,K.jsxs)(`div`,{className:`space-y-2`,children:[(0,K.jsx)(`p`,{className:`text-lg font-medium text-zinc-500`,children:e(`spoolbuddy.status.deviceOffline`,`Device Offline`)}),(0,K.jsx)(`p`,{className:`text-sm text-zinc-600`,children:e(`spoolbuddy.status.connectDisplay`,`Connect the SpoolBuddy display to scan spools`)})]}),(0,K.jsxs)(`div`,{className:`mt-6 flex items-center gap-2 text-xs text-zinc-600`,children:[(0,K.jsx)(`svg`,{className:`w-4 h-4`,fill:`none`,viewBox:`0 0 24 24`,stroke:`currentColor`,children:(0,K.jsx)(`path`,{strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:`2`,d:`M8.111 16.404a5.5 5.5 0 017.778 0M12 20h.01m-7.08-7.071c3.904-3.905 10.236-3.905 14.14 0M1.394 9.393c5.857-5.857 15.355-5.857 21.213 0`})}),(0,K.jsx)(`span`,{children:e(`spoolbuddy.status.waitingConnection`,`Waiting for device connection...`)})]})]})}function v$e(){let{sbState:e,selectedPrinterId:t}=nr(),{t:n}=W(),{showToast:r}=kd(),{data:i}=q({queryKey:[`spoolman-settings`],queryFn:Q.getSpoolmanSettings,staleTime:300*1e3}),a=i?.spoolman_enabled===`true`&&!!i?.spoolman_url,{data:o=[],refetch:s}=q({queryKey:a?[`spoolman-inventory-spools`]:[`inventory-spools`],queryFn:()=>a?Q.getSpoolmanInventorySpools(!1):Q.getSpools(!1),enabled:i!==void 0}),{data:c=[]}=q({queryKey:[`spoolman-slot-assignments`],queryFn:()=>Q.getSpoolmanSlotAssignments(),enabled:a,staleTime:3*1e3,refetchInterval:3*1e3,refetchIntervalInBackground:!1}),{data:l=[]}=q({queryKey:[`printers`],queryFn:()=>Q.getPrinters()}),u=go({queries:l.map(e=>({queryKey:[`printerStatus`,e.id],queryFn:()=>Q.getPrinterStatus(e.id),refetchInterval:1e4,select:e=>({connected:e?.connected,awaiting_plate_clear:e?.awaiting_plate_clear===!0})}))}),d=l.map((e,t)=>({printer:e,pending:u[t]?.data?.awaiting_plate_clear===!0})).filter(e=>e.pending),f=to(),p=J({mutationFn:e=>Q.clearPlate(e),onSuccess:(e,t)=>{f.setQueryData([`printerStatus`,t],e=>e&&{...e,awaiting_plate_clear:!1}),r(n(`spoolbuddy.dashboard.plateClearedToast`,`Plate marked as cleared`),`success`)},onError:()=>{r(n(`spoolbuddy.dashboard.plateClearFailed`,`Could not mark plate as cleared`),`error`)}}),m=J({mutationFn:e=>Q.unassignSpoolmanSlot(e),onSuccess:()=>{f.invalidateQueries({queryKey:[`spoolman-slot-assignments`]}),f.invalidateQueries({queryKey:[`spoolman-inventory-spools`]})},onError:()=>r(n(`inventory.unassignFailed`,`Failed to unassign spool`),`error`)}),[h,g]=(0,y.useState)(null),[_,v]=(0,y.useState)(null),[b,x]=(0,y.useState)(null),[S,C]=(0,y.useState)(!1),[w,T]=(0,y.useState)(!1),[E,D]=(0,y.useState)(!1),[O,k]=(0,y.useState)(!1),[A,j]=(0,y.useState)(null),M=e.matchedSpool?.tag_uid??e.unknownTagUid??null,N=e.weight,P=e.weightStable,F=(0,y.useRef)(null);N===null?F.current=null:(F.current===null||Math.abs(N-F.current)>=3||P)&&(F.current=N);let I=F.current,L=(0,y.useMemo)(()=>{if(e.matchedSpool?.id){let t=o.find(t=>t.id===e.matchedSpool?.id);if(t)return t}return h&&(o.find(e=>m$e(e.tag_uid,h))||A)||null},[h,e.matchedSpool,o,A]),R=(0,y.useMemo)(()=>{if(L&&!A)return L;let t=e.matchedSpool;return t?{id:t.id,tag_uid:t.tag_uid,material:t.material,subtype:t.subtype,color_name:t.color_name,rgba:t.rgba,brand:t.brand,label_weight:t.label_weight,core_weight:t.core_weight,weight_used:t.weight_used}:null},[L,A,e.matchedSpool]),z=a&&R!=null?c.some(e=>e.spoolman_spool_id===R.id):!1,B=(0,y.useMemo)(()=>a?o.filter(e=>!e.tag_uid&&!e.tray_uuid&&!e.archived_at):o.filter(e=>!e.tag_uid&&!e.archived_at),[o,a]);(0,y.useEffect)(()=>{if(M){let e=b===M;(h!==null&&h!==M||!e&&h!==M)&&(g(M),v(null),x(null),j(null)),!e&&N!==null&&P&&v(Math.round(Math.max(0,N)))}else b&&(g(null),x(null),v(null),j(null))},[M,N,P,h,b]);let V=()=>{x(h)},ee=async t=>{if(h)try{if(a){let i=e.unknownTagUid||void 0,a=!e.unknownTagUid&&e.unknownTrayUuid?e.unknownTrayUuid:void 0;if(!i&&!a){r(n(`spoolman.linkFailed`),`error`);return}let o=await Q.linkTagToSpoolmanSpool(t.id,{tray_uuid:a,tag_uid:i});if(!o){r(n(`spoolman.linkFailed`),`error`);return}let{id:s,material:c,subtype:l,color_name:u,rgba:d,brand:f,label_weight:p,core_weight:m,weight_used:h}=o;j({id:s,material:c,subtype:l,color_name:u,rgba:d,brand:f,label_weight:p,core_weight:m,weight_used:h}),r(n(`spoolman.linkSuccess`),`success`)}else await Q.linkTagToSpool(t.id,{tag_uid:h,tag_type:`generic`,data_origin:`nfc_link`});s()}catch(e){console.error(`Failed to link tag:`,e),r(n(`spoolman.linkFailed`),`error`)}finally{C(!1)}},te=async()=>{if(h){k(!0);try{let t=ne??_;if(a){let n=await Q.createSpoolmanInventorySpool({material:`PLA`,subtype:null,color_name:null,rgba:null,extra_colors:null,effect_type:null,brand:null,label_weight:1e3,core_weight:250,core_weight_catalog_id:null,weight_used:0,slicer_filament:null,slicer_filament_name:null,nozzle_temp_min:null,nozzle_temp_max:null,note:null,added_full:null,last_used:null,encode_time:null,tag_uid:null,tray_uuid:null,data_origin:null,tag_type:null,cost_per_kg:null,last_scale_weight:t===null?null:Math.round(t),last_weighed_at:t===null?null:new Date().toISOString(),category:null,low_stock_threshold_pct:null});await Q.linkTagToSpoolmanSpool(n.id,{tag_uid:e.unknownTagUid||void 0,tray_uuid:!e.unknownTagUid&&e.unknownTrayUuid?e.unknownTrayUuid:void 0})}else await Q.createSpool({material:`PLA`,subtype:null,color_name:null,rgba:null,extra_colors:null,effect_type:null,brand:null,label_weight:1e3,core_weight:250,core_weight_catalog_id:null,weight_used:0,slicer_filament:null,slicer_filament_name:null,nozzle_temp_min:null,nozzle_temp_max:null,note:null,added_full:null,last_used:null,encode_time:null,tag_uid:h,tray_uuid:null,data_origin:`spoolbuddy`,tag_type:`generic`,cost_per_kg:null,last_scale_weight:t===null?null:Math.round(t),last_weighed_at:t===null?null:new Date().toISOString(),category:null,low_stock_threshold_pct:null})}catch(e){let t=e instanceof Error?e.message:String(e);console.error(`Failed to quick-add spool:`,t),r(t||n(`spoolbuddy.errors.quickAddFailed`,`Failed to add spool`),`error`)}finally{D(!1),k(!1),s()}}},ne=N!==null&&(M===h||M===null&&h!==null)?N:null,re=o.length,ie=new Set(o.map(e=>e.material)).size,H=new Set(o.filter(e=>e.brand).map(e=>e.brand)).size;return(0,K.jsxs)(`div`,{className:`h-full flex flex-col p-4`,children:[(0,K.jsxs)(`div`,{className:`flex items-center gap-6 px-4 py-1.5 bg-zinc-800/50 rounded-xl border border-zinc-700/50 mb-3 shrink-0`,children:[(0,K.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,K.jsx)(`span`,{className:`text-xl font-bold text-zinc-100`,children:re}),(0,K.jsx)(`span`,{className:`text-sm text-zinc-500`,children:n(`spoolbuddy.inventory.spools`,`Spools`)})]}),(0,K.jsx)(`div`,{className:`w-px h-5 bg-zinc-700`}),(0,K.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,K.jsx)(`span`,{className:`text-xl font-bold text-zinc-100`,children:ie}),(0,K.jsx)(`span`,{className:`text-sm text-zinc-500`,children:n(`spoolbuddy.spool.material`,`Materials`)})]}),(0,K.jsx)(`div`,{className:`w-px h-5 bg-zinc-700`}),(0,K.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,K.jsx)(`span`,{className:`text-xl font-bold text-zinc-100`,children:H}),(0,K.jsx)(`span`,{className:`text-sm text-zinc-500`,children:n(`spoolbuddy.spool.brand`,`Brands`)})]})]}),(0,K.jsxs)(`div`,{className:`flex-1 flex gap-4 min-h-0`,children:[(0,K.jsxs)(`div`,{className:`w-5/12 flex flex-col min-h-0`,children:[(0,K.jsxs)(`div`,{className:`border border-dashed border-zinc-700/50 rounded-xl p-4`,children:[(0,K.jsx)(`h2`,{className:`text-sm font-semibold text-zinc-400 uppercase tracking-wide mb-3`,children:n(`spoolbuddy.dashboard.device`,`Device`)}),(0,K.jsxs)(`div`,{className:`space-y-2.5`,children:[(0,K.jsxs)(`div`,{className:`flex items-center gap-3`,children:[(0,K.jsx)(`div`,{className:`w-2.5 h-2.5 rounded-full ${e.deviceOnline?`bg-green-500`:`bg-red-500`}`}),(0,K.jsx)(`span`,{className:`text-base text-zinc-400`,children:e.deviceOnline?n(`spoolbuddy.status.online`,`Online`):n(`spoolbuddy.status.offline`,`Disconnected`)})]}),(0,K.jsxs)(`div`,{className:`flex items-center justify-between p-3 bg-zinc-800/50 rounded-lg`,children:[(0,K.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,K.jsx)(`svg`,{className:`w-4 h-4 ${e.deviceOnline?`text-green-500`:`text-zinc-500`}`,fill:`none`,viewBox:`0 0 24 24`,stroke:`currentColor`,children:(0,K.jsx)(`path`,{strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:`2`,d:`M3 6l3 1m0 0l-3 9a5.002 5.002 0 006.001 0M6 7l3 9M6 7l6-2m6 2l3-1m-3 1l-3 9a5.002 5.002 0 006.001 0M18 7l3 9m-3-9l-6-2m0-2v2m0 16V5m0 16H9m3 0h3`})}),(0,K.jsx)(`span`,{className:`text-sm text-zinc-500`,children:n(`spoolbuddy.spool.scaleWeight`,`Scale`)})]}),(0,K.jsx)(`span`,{className:`text-lg font-mono font-semibold text-zinc-100`,children:I===null?`—`:`${Math.abs(I)<=20?0:Math.round(Math.max(0,I))}g`})]}),(0,K.jsxs)(`div`,{className:`flex items-center justify-between p-3 bg-zinc-800/50 rounded-lg`,children:[(0,K.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,K.jsx)(`svg`,{className:`w-4 h-4 ${e.deviceOnline?`text-green-500`:`text-zinc-500`}`,fill:`none`,viewBox:`0 0 24 24`,stroke:`currentColor`,children:(0,K.jsx)(`path`,{strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:`2`,d:`M7 7h.01M7 3h5c.512 0 1.024.195 1.414.586l7 7a2 2 0 010 2.828l-7 7a2 2 0 01-2.828 0l-7-7A2 2 0 013 12V7a4 4 0 014-4z`})}),(0,K.jsx)(`span`,{className:`text-sm text-zinc-500`,children:`NFC`})]}),(0,K.jsx)(`span`,{className:`text-sm font-medium ${M?`text-green-500`:`text-zinc-500`}`,children:M?n(`spoolbuddy.dashboard.tagDetected`,`Tag detected`):n(`spoolbuddy.dashboard.noTag`,`No tag`)})]})]})]}),l.length>0&&(0,K.jsxs)(`div`,{className:`mt-3 border border-dashed border-zinc-700/50 rounded-xl p-4`,children:[(0,K.jsx)(`h2`,{className:`text-sm font-semibold text-zinc-400 uppercase tracking-wide mb-2.5`,children:n(`spoolbuddy.dashboard.printers`,`Printers`)}),(0,K.jsx)(`div`,{className:`flex flex-wrap gap-2 overflow-hidden`,children:l.map((e,t)=>{let n=u[t]?.data?.connected??!1;return(0,K.jsxs)(`div`,{className:`flex items-center gap-1.5 px-2.5 py-1 bg-zinc-800/50 rounded-lg`,title:`${e.name} — ${n?`Online`:`Offline`}`,children:[(0,K.jsx)(`div`,{className:`w-2 h-2 rounded-full shrink-0 ${n?`bg-green-500`:`bg-zinc-600`}`}),(0,K.jsx)(`span`,{className:`text-xs text-zinc-400 truncate max-w-[100px]`,children:e.name})]},e.id)})}),d.length>0&&(0,K.jsx)(`div`,{className:`mt-2 flex flex-wrap gap-2`,"data-testid":`plate-clear-section`,"aria-label":n(`spoolbuddy.dashboard.plateReadyLabel`,`Plates ready to clear`),children:d.map(({printer:e})=>(0,K.jsxs)(`button`,{type:`button`,onClick:()=>p.mutate(e.id),disabled:p.isPending,"data-testid":`plate-clear-button-${e.id}`,title:n(`spoolbuddy.dashboard.plateReady`,`Plate ready: {{name}}`,{name:e.name}),className:`flex items-center gap-1.5 px-2.5 py-1 rounded-lg bg-amber-500/10 hover:bg-amber-500/20 active:bg-amber-500/30 border border-amber-500/30 text-amber-200 transition-colors disabled:opacity-60 disabled:cursor-wait`,children:[(0,K.jsxs)(`svg`,{className:`w-3 h-3 shrink-0`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2.5`,strokeLinecap:`round`,strokeLinejoin:`round`,"aria-hidden":`true`,children:[(0,K.jsx)(`path`,{d:`M12 9v4`}),(0,K.jsx)(`path`,{d:`M12 17h.01`}),(0,K.jsx)(`path`,{d:`M10.29 3.86 1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z`})]}),(0,K.jsx)(`span`,{className:`text-xs truncate max-w-[100px]`,children:e.name}),(0,K.jsx)(`span`,{className:`text-xs opacity-70`,"aria-hidden":`true`,children:`·`}),(0,K.jsx)(`span`,{className:`text-xs font-medium`,children:n(`spoolbuddy.dashboard.plateClearAction`,`Clear`)})]},e.id))})]})]}),(0,K.jsx)(`div`,{className:`w-7/12 min-h-0`,children:(0,K.jsxs)(`div`,{className:`border border-dashed border-zinc-700/50 rounded-xl p-6 h-full flex flex-col`,children:[(0,K.jsx)(`h2`,{className:`text-sm font-semibold text-zinc-400 uppercase tracking-wide mb-4 shrink-0`,children:n(`spoolbuddy.dashboard.currentSpool`,`Current Spool`)}),(0,K.jsx)(`div`,{className:`flex-1 flex items-center justify-center min-h-0`,children:e.deviceOnline?(L||e.matchedSpool)&&h&&b!==h?(0,K.jsx)(KQe,{spool:(()=>{let t=L??e.matchedSpool;return{id:t.id,tag_uid:h,material:t.material,subtype:t.subtype,color_name:t.color_name,rgba:t.rgba,brand:t.brand,label_weight:t.label_weight,core_weight:t.core_weight,weight_used:t.weight_used}})(),scaleWeight:ne??_,onSyncWeight:()=>s(),onAssignToAms:()=>T(!0),isAssigned:z,onUnassignFromAms:z&&L?.id!=null?()=>m.mutate(L.id):void 0,onClose:V}):M&&h&&!L&&!e.matchedSpool&&b!==h?(0,K.jsx)(qQe,{tagUid:h,scaleWeight:ne??_,onLinkSpool:B.length>0?()=>C(!0):void 0,onAddToInventory:()=>D(!0),onClose:V}):(0,K.jsx)(g$e,{}):(0,K.jsx)(_$e,{})})]})})]}),R&&!A&&h&&(0,K.jsx)(d$e,{isOpen:w,onClose:()=>T(!1),spool:R,printerId:t,spoolmanMode:a}),h&&(0,K.jsx)(f$e,{isOpen:S,onClose:()=>C(!1),tagId:h,untaggedSpools:B,onLink:ee}),E&&h&&(0,K.jsx)(`div`,{className:`fixed inset-0 z-50 flex items-center justify-center bg-black/60`,children:(0,K.jsxs)(`div`,{className:`bg-zinc-800 rounded-2xl p-6 mx-4 max-w-sm w-full border border-zinc-700`,children:[(0,K.jsx)(`h3`,{className:`text-lg font-semibold text-zinc-100 mb-3`,children:n(`spoolbuddy.modal.addToInventory`,`Add to Inventory`)}),(0,K.jsxs)(`div`,{className:`flex gap-2.5 p-3 bg-amber-500/10 border border-amber-500/20 rounded-lg mb-4`,children:[(0,K.jsx)(`svg`,{className:`w-5 h-5 text-amber-500 shrink-0 mt-0.5`,fill:`none`,viewBox:`0 0 24 24`,stroke:`currentColor`,children:(0,K.jsx)(`path`,{strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:`2`,d:`M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z`})}),(0,K.jsx)(`p`,{className:`text-sm text-amber-200/80`,children:n(`spoolbuddy.modal.quickAddHint`,`For best results, add the spool in the Bambuddy web interface first (with material, color, brand), then use "Assign Spool" here to assign the NFC tag.`)})]}),(0,K.jsx)(`p`,{className:`text-sm text-zinc-400 mb-1`,children:n(`spoolbuddy.modal.quickAddDesc`,`This will create a basic PLA spool entry with this NFC tag. You can edit the details later in Bambuddy.`)}),(0,K.jsx)(`p`,{className:`text-xs text-zinc-500 font-mono mb-5`,children:h}),(0,K.jsxs)(`div`,{className:`flex gap-3`,children:[(0,K.jsx)(`button`,{onClick:()=>D(!1),className:`flex-1 px-4 py-2.5 rounded-lg text-sm font-medium bg-zinc-700 text-zinc-300 hover:bg-zinc-600 transition-colors min-h-[44px]`,children:n(`common.cancel`,`Cancel`)}),(0,K.jsx)(`button`,{onClick:te,disabled:O,className:`flex-1 px-4 py-2.5 rounded-lg text-sm font-medium bg-green-600 text-white hover:bg-green-700 disabled:opacity-50 transition-colors min-h-[44px]`,children:O?n(`common.saving`,`Saving...`):n(`spoolbuddy.modal.addAnyway`,`Add Anyway`)})]})]})})]})}function y$e(e){return e<=3?`AMS ${String.fromCharCode(65+e)}`:e>=128&&e<=135?`AMS HT ${String.fromCharCode(65+e-128)}`:`AMS ${e}`}function b$e(e){return e?{O1D:`H2D`,O1E:`H2D Pro`,O2D:`H2D Pro`,O1C:`H2C`,O1C2:`H2C`,O1S:`H2S`,"BL-P001":`X1C`,"BL-P002":`X1`,"BL-P003":`X1E`,N6:`X2D`,N9:`A2L`,C11:`P1S`,C12:`P1P`,C13:`P2S`,N2S:`A1`,N1:`A1 Mini`,X1C:`X1C`,X1:`X1`,X1E:`X1E`,X2D:`X2D`,P1S:`P1S`,P1P:`P1P`,P2S:`P2S`,A1:`A1`,"A1 Mini":`A1 Mini`,A2L:`A2L`,H2D:`H2D`,"H2D Pro":`H2D Pro`,H2C:`H2C`,H2S:`H2S`}[e]||e:``}function X9(e){return!e.tray_type||e.tray_type===``}function x$e(e){return e?`#${e.slice(0,6)}`:`#808080`}function S$e(){let{selectedPrinterId:e,setAlert:t}=nr(),{t:n}=W(),r=to(),{showToast:i}=kd(),{data:a}=q({queryKey:[`printerStatus`,e],queryFn:()=>Q.getPrinterStatus(e),enabled:e!==null,staleTime:30*1e3}),{data:o}=q({queryKey:[`printer`,e],queryFn:()=>Q.getPrinter(e),enabled:e!==null,staleTime:60*1e3}),{data:s}=q({queryKey:[`slotPresets`,e],queryFn:()=>Q.getSlotPresets(e),enabled:e!==null,staleTime:120*1e3}),{data:c}=q({queryKey:[`settings`],queryFn:()=>Q.getSettings(),staleTime:300*1e3}),{data:l}=q({queryKey:[`spoolman-status`],queryFn:Q.getSpoolmanStatus,staleTime:60*1e3}),u=l?.enabled&&l?.connected,{data:d}=q({queryKey:[`linked-spools`],queryFn:Q.getLinkedSpools,enabled:!!u,staleTime:30*1e3}),f=d?.linked,{data:p=[]}=q({queryKey:[`spoolman-slot-assignments-all`],queryFn:()=>Q.getSpoolmanSlotAssignments(),enabled:!!u,staleTime:30*1e3}),{data:m=[]}=q({queryKey:[`spoolman-inventory-spools`],queryFn:()=>Q.getSpoolmanInventorySpools(!1),enabled:!!u,staleTime:30*1e3}),{data:h}=q({queryKey:[`spool-assignments`,e],queryFn:()=>Q.getAssignments(e),enabled:e!==null,staleTime:30*1e3}),g=(0,y.useMemo)(()=>{let e={};if(!h)return e;for(let t of h){let n=t.spool;if(n&&n.label_weight>0&&n.weight_used!=null){let r=Math.round(Math.max(0,n.label_weight-n.weight_used)/n.label_weight*100);e[`${t.ams_id}-${t.tray_id}`]=r}}return e},[h]),_=o?.serial_number??``,v=(0,y.useCallback)((t,n,r)=>{if(e!==null&&p.length&&m.length){let r=p.find(r=>r.printer_id===e&&r.ams_id===t&&r.tray_id===n);if(r){let e=m.find(e=>e.id===r.spoolman_spool_id);if(e&&(e.label_weight??0)>0)return Math.round(Math.max(0,e.label_weight-e.weight_used)/e.label_weight*100)}}if(f&&_){let e=(r?.tray_uuid||r?.tag_uid||Xf(_,t,n))?.toUpperCase(),i=qf(e?f[e]:void 0);if(i!==null)return i}return null},[f,_,e,p,m]),b=a?.connected??!1,x=(0,y.useRef)({});(0,y.useEffect)(()=>{e&&a?.ams&&a.ams.length>0&&(x.current[e]=a.ams)},[a?.ams,e]);let S=(0,y.useMemo)(()=>{let t=a?.ams;return t&&t.length>0?t:(e?x.current[e]:null)??[]},[a?.ams,e]),C=(0,y.useMemo)(()=>S.filter(e=>!e.is_ams_ht),[S]),w=(0,y.useMemo)(()=>S.filter(e=>e.is_ams_ht),[S]),T=(0,y.useMemo)(()=>{let e={};if(!f||!_)return e;for(let t of C)for(let n=0;n<(t.tray?.length??0);n++){let r=t.tray[n],i=v(t.id,n,X9(r)?null:r);i!==null&&(e[`${t.id}-${n}`]=i)}return e},[f,_,C,v]),E=(0,y.useRef)(void 0),D=a?.tray_now;D!==void 0&&D!==255?E.current=D:D===255&&(E.current=void 0);let O=D!==void 0&&D!==255?D:E.current,k=o?.nozzle_count===2||a?.temperatures?.nozzle_2!==void 0,A=(0,y.useMemo)(()=>[...a?.vt_tray??[]].sort((e,t)=>(e.id??254)-(t.id??254)),[a?.vt_tray]),j=c?{humidityGood:Number(c.ams_humidity_good)||40,humidityFair:Number(c.ams_humidity_fair)||60,tempGood:Number(c.ams_temp_good)||28,tempFair:Number(c.ams_temp_fair)||35}:void 0,M=(0,y.useRef)({});(0,y.useEffect)(()=>{a?.ams_extruder_map&&Object.keys(a.ams_extruder_map).length>0&&(M.current=a.ams_extruder_map)},[a?.ams_extruder_map]);let N=a?.ams_extruder_map&&Object.keys(a.ams_extruder_map).length>0?a.ams_extruder_map:M.current,P=(0,y.useCallback)(e=>{if(!k)return null;let t=N[String(e)],n=e>=128?e-128:e;return(t===void 0?n:t)===1?`L`:`R`},[k,N]),[F,I]=(0,y.useState)(null),[L,R]=(0,y.useState)(null),[z,B]=(0,y.useState)(null),[V,ee]=(0,y.useState)(null),te=(0,y.useCallback)((e,t)=>h?.find(n=>n.ams_id===Number(e)&&n.tray_id===Number(t)),[h]),ne=(0,y.useCallback)((e,t,n)=>{if(!f||!_)return;let r=(n?.tray_uuid||n?.tag_uid||Xf(_,e,t))?.toUpperCase();return r?f[r]:void 0},[f,_]),re=J({mutationFn:({printerId:e,amsId:t,trayId:n})=>Q.unassignSpool(e,t,n),onSuccess:()=>{r.invalidateQueries({queryKey:[`spool-assignments`,e]}),r.invalidateQueries({queryKey:[`spool-assignments`]}),i(n(`inventory.unassignSuccess`,`Spool unassigned`),`success`),R(null)}}),ie=J({mutationFn:e=>Q.unlinkSpool(e),onSuccess:e=>{i(n(`spoolman.unlinkSuccess`)||e?.message,`success`),r.invalidateQueries({queryKey:[`linked-spools`]}),r.invalidateQueries({queryKey:[`unlinked-spools`]}),r.invalidateQueries({queryKey:[`spoolman-slot-assignments`]}),r.invalidateQueries({queryKey:[`spoolman-slot-assignments-all`]}),r.invalidateQueries({queryKey:[`spoolman-inventory-spools`]}),R(null)},onError:e=>{i(e.message||n(`spoolman.unlinkFailed`),`error`)}}),H=J({mutationFn:e=>Q.unassignSpoolmanSlot(e),onSuccess:()=>{i(n(`inventory.unassignSuccess`,`Spool unassigned`),`success`),r.invalidateQueries({queryKey:[`spoolman-slot-assignments`]}),r.invalidateQueries({queryKey:[`spoolman-slot-assignments-all`]}),r.invalidateQueries({queryKey:[`spoolman-inventory-spools`]}),r.invalidateQueries({queryKey:[`unlinked-spools`]}),r.invalidateQueries({queryKey:[`linked-spools`]}),R(null)},onError:e=>{i(e.message||n(`inventory.assignFailed`,`Failed to unassign spool`),`error`)}}),ae=(0,y.useCallback)(e=>O===void 0?null:e<=3&&Math.floor(O/4)===e?O%4:e>=128&&e<=135&&O===Gf(e,0,!1)?0:null,[O]),oe=(0,y.useCallback)((e,t,n)=>{let r=Gf(e,t,!1),i=s?.[r],a=N[String(e)],o=e>=128?e-128:e,c=a===void 0?o:a;R({amsId:e,trayId:t,trayCount:n&&e>=128?1:4,tray:n,trayType:n?.tray_type||void 0,trayColor:n?.tray_color||void 0,traySubBrands:n?.tray_sub_brands||void 0,trayInfoIdx:n?.tray_info_idx||void 0,extruderId:k?c:void 0,caliIdx:n?.cali_idx,savedPresetId:i?.preset_id,location:`${y$e(e)} Slot ${t+1}`})},[s,N,k]),U=(0,y.useCallback)(e=>{let t=e.id??254,n=t-254,r=s?.[1020+n];R({amsId:255,trayId:n,trayCount:1,tray:X9(e)?null:e,trayType:e.tray_type||void 0,trayColor:e.tray_color||void 0,traySubBrands:e.tray_sub_brands||void 0,trayInfoIdx:e.tray_info_idx||void 0,extruderId:k?+(t===254):void 0,caliIdx:e.cali_idx,savedPresetId:r?.preset_id,location:k?t===254?`Ext-L`:`Ext-R`:`External`})},[s,k]),se=(0,y.useCallback)(()=>{if(!L)return;let{tray:e,location:t,...n}=L;R(null),I(n)},[L]),ce=(0,y.useCallback)(()=>{if(!L||!e)return;let{amsId:t,trayId:n,trayType:r,trayColor:i,location:a}=L;R(null),B({printerId:e,amsId:t,trayId:n,trayInfo:{type:r||``,material:r,color:i?.slice(0,6)||``,location:a}})},[L,e]),le=(0,y.useCallback)(()=>{if(!L||!e)return;let{amsId:t,trayId:n,tray:r}=L,i=(r?.tray_uuid||r?.tag_uid||Xf(_,t,n))?.toUpperCase()||``;R(null),ee({tagUid:r?.tag_uid||i,trayUuid:r?.tray_uuid||``,printerId:e,amsId:t,trayId:n})},[L,e,_]),ue=(0,y.useCallback)(()=>{if(!L||!e)return;let{amsId:t,trayId:n}=L;re.mutate({printerId:e,amsId:t,trayId:n})},[L,e,re]);(0,y.useEffect)(()=>{if(!b&&e){t({type:`warning`,message:n(`spoolbuddy.ams.printerDisconnected`,`Printer disconnected`)});return}for(let e of S){let n=e.tray||[];for(let r=0;r=0&&i.remain<15&&i.tray_type){let n=e.id===254||e.id===255,a=!n&&e.id>=128,o=Wf(e.id,r,a,n);t({type:`warning`,message:`Low Filament: ${i.tray_type} (${o}) - ${i.remain}% remaining`});return}}}t(null)},[S,b,e,t,n]);let de=(0,y.useMemo)(()=>{let e=[];for(let t of w){let n=t.tray?.[0]||{id:0,tray_color:null,tray_type:``,tray_sub_brands:null,tray_id_name:null,tray_info_idx:null,remain:-1,k:null,cali_idx:null,tag_uid:null,tray_uuid:null,nozzle_temp_min:null,nozzle_temp_max:null},r=v(t.id,0,X9(n)?null:n),i=g[`${t.id}-0`]??null,a=n.remain!=null&&n.remain>=0?n.remain:null,o=i===0&&a!==null&&a>0?null:i;e.push({key:`ht-${t.id}`,label:y$e(t.id),tray:n,isEmpty:X9(n),isActive:ae(t.id)===0,temp:t.temp,humidity:t.humidity,nozzleSide:P(t.id),effectiveFill:r??o??a,onClick:()=>oe(t.id,0,X9(n)?null:n)})}for(let t of A){let r=t.id??254,i=k&&O===254?r===254&&a?.active_extruder===1||r===255&&a?.active_extruder===0:O===r,o=r-254,s=v(255,o,X9(t)?null:t),c=g[`255-${o}`]??null,l=t.remain!=null&&t.remain>=0?t.remain:null,u=c===0&&l!==null&&l>0?null:c;e.push({key:`ext-${r}`,label:k?r===254?n(`printers.extL`,`Ext-L`):n(`printers.extR`,`Ext-R`):n(`printers.ext`,`Ext`),tray:t,isEmpty:X9(t),isActive:i,nozzleSide:null,effectiveFill:s??u??l,onClick:()=>U(t)})}return e},[w,A,k,O,a?.active_extruder,n,ae,P,oe,U,g,v]);return(0,K.jsxs)(`div`,{className:`h-full flex flex-col p-4`,children:[(0,K.jsx)(`div`,{className:`flex-1 min-h-0`,children:e?b?S.length===0&&A.length===0?(0,K.jsx)(`div`,{className:`flex-1 flex items-center justify-center h-full`,children:(0,K.jsxs)(`div`,{className:`text-center text-white/50`,children:[(0,K.jsx)(Ic,{className:`w-12 h-12 mx-auto mb-3 opacity-50`}),(0,K.jsx)(`p`,{className:`text-lg mb-2`,children:n(`spoolbuddy.ams.noData`,`No AMS detected`)}),(0,K.jsx)(`p`,{className:`text-sm`,children:n(`spoolbuddy.ams.connectAms`,`Connect an AMS to see filament slots`)})]})}):(0,K.jsxs)(`div`,{className:`flex flex-col gap-3 h-full`,children:[(0,K.jsx)(`div`,{className:`grid grid-cols-1 md:grid-cols-2 gap-3`,children:C.map(e=>(0,K.jsx)(s$e,{unit:e,activeSlot:ae(e.id),onConfigureSlot:oe,isDualNozzle:k,nozzleSide:P(e.id),thresholds:j,fillOverrides:g,spoolmanFillOverrides:T},e.id))}),de.length>0&&(0,K.jsx)(`div`,{className:`grid grid-cols-2 md:grid-cols-4 gap-3`,children:de.map(({key:e,label:t,tray:n,isEmpty:r,isActive:i,temp:a,humidity:o,nozzleSide:s,effectiveFill:c,onClick:l})=>{let u=x$e(n.tray_color);return(0,K.jsxs)(`div`,{className:`bg-bambu-dark-secondary rounded-lg px-3 py-2 cursor-pointer hover:bg-bambu-dark-secondary/80 transition-all flex items-center gap-3 ${i?`ring-2 ring-bambu-green`:``}`,onClick:l,children:[(0,K.jsxs)(`div`,{className:`relative w-10 h-10 flex-shrink-0`,children:[r?(0,K.jsx)(`div`,{className:`w-full h-full rounded-full border-2 border-dashed border-gray-500 flex items-center justify-center`,children:(0,K.jsx)(`div`,{className:`w-1.5 h-1.5 rounded-full bg-gray-600`})}):(0,K.jsxs)(`svg`,{viewBox:`0 0 56 56`,className:`w-full h-full`,children:[(0,K.jsx)(`circle`,{cx:`28`,cy:`28`,r:`26`,fill:u}),(0,K.jsx)(`circle`,{cx:`28`,cy:`28`,r:`20`,fill:u,style:{filter:`brightness(0.85)`}}),(0,K.jsx)(`ellipse`,{cx:`20`,cy:`20`,rx:`6`,ry:`4`,fill:`white`,opacity:`0.3`}),(0,K.jsx)(`circle`,{cx:`28`,cy:`28`,r:`8`,fill:`#2d2d2d`}),(0,K.jsx)(`circle`,{cx:`28`,cy:`28`,r:`5`,fill:`#1a1a1a`})]}),i&&(0,K.jsx)(`div`,{className:`absolute -bottom-0.5 left-1/2 -translate-x-1/2 w-1.5 h-1.5 bg-bambu-green rounded-full`})]}),(0,K.jsxs)(`div`,{className:`min-w-0`,children:[(0,K.jsxs)(`div`,{className:`flex items-center gap-1`,children:[(0,K.jsx)(`span`,{className:`text-xs text-white/50 font-medium truncate`,children:t}),s&&(0,K.jsx)(K9,{side:s})]}),(0,K.jsx)(`div`,{className:`text-sm text-white/80 truncate`,children:r?`Empty`:n.tray_type||`?`}),(a!=null||o!=null)&&(0,K.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[a!=null&&(0,K.jsx)(a$e,{temp:a,goodThreshold:j?.tempGood,fairThreshold:j?.tempFair}),o!=null&&(0,K.jsx)(i$e,{humidity:o,goodThreshold:j?.humidityGood,fairThreshold:j?.humidityFair})]})]}),!r&&c!=null&&c>=0&&(0,K.jsx)(`div`,{className:`w-1.5 h-8 bg-bambu-dark-tertiary rounded-full overflow-hidden flex-shrink-0 flex flex-col-reverse`,children:(0,K.jsx)(`div`,{className:`w-full rounded-full`,style:{height:`${c}%`,backgroundColor:Kf(c)}})})]},e)})})]}):(0,K.jsx)(`div`,{className:`flex-1 flex items-center justify-center h-full`,children:(0,K.jsx)(`div`,{className:`text-center text-white/50`,children:(0,K.jsx)(`p`,{className:`text-lg mb-2`,children:n(`spoolbuddy.ams.printerDisconnected`,`Printer disconnected`)})})}):(0,K.jsx)(`div`,{className:`flex-1 flex items-center justify-center h-full`,children:(0,K.jsxs)(`div`,{className:`text-center text-white/50`,children:[(0,K.jsx)(`p`,{className:`text-lg mb-2`,children:n(`spoolbuddy.ams.noPrinter`,`No printer selected`)}),(0,K.jsx)(`p`,{className:`text-sm`,children:n(`spoolbuddy.ams.selectPrinter`,`Select a printer from the top bar`)})]})})}),F&&e&&(0,K.jsx)(YU,{isOpen:!!F,onClose:()=>I(null),printerId:e,slotInfo:F,printerModel:b$e(o?.model??null)||void 0,nozzleDiameter:ip(a,F.amsId),fullScreen:!0,onSuccess:()=>{r.invalidateQueries({queryKey:[`slotPresets`,e]}),r.invalidateQueries({queryKey:[`printerStatus`,e]})}}),L&&e&&(()=>{let t=te(L.amsId,L.trayId),r=ne(L.amsId,L.trayId,L.tray),i=u?p.find(t=>t.printer_id===e&&t.ams_id===L.amsId&&t.tray_id===L.trayId):void 0,a=i?m.find(e=>e.id===i.spoolman_spool_id)??null:null;return(0,K.jsxs)(`div`,{className:`fixed inset-0 z-50 flex items-center justify-center`,children:[(0,K.jsx)(`div`,{className:`absolute inset-0 bg-black/60 backdrop-blur-sm`,onClick:()=>R(null)}),(0,K.jsxs)(`div`,{className:`relative w-full max-w-sm mx-4 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl`,children:[(0,K.jsxs)(`div`,{className:`flex items-center justify-between p-4 border-b border-bambu-dark-tertiary`,children:[(0,K.jsxs)(`div`,{className:`flex items-center gap-2`,children:[L.trayColor&&(0,K.jsx)(`span`,{className:`w-4 h-4 rounded-full border border-black/20`,style:{backgroundColor:`#${L.trayColor.slice(0,6)}`}}),(0,K.jsx)(`h2`,{className:`text-lg font-semibold text-white`,children:L.location}),L.traySubBrands&&(0,K.jsxs)(`span`,{className:`text-sm text-bambu-gray`,children:[`(`,L.traySubBrands,`)`]})]}),(0,K.jsx)(`button`,{onClick:()=>R(null),className:`p-1 text-bambu-gray hover:text-white rounded transition-colors`,children:(0,K.jsx)(Hu,{className:`w-5 h-5`})})]}),(0,K.jsxs)(`div`,{className:`p-4 space-y-2`,children:[!u&&t?.spool&&(0,K.jsxs)(`div`,{className:`p-2.5 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary mb-3`,children:[(0,K.jsx)(`p`,{className:`text-xs text-bambu-gray mb-1`,children:n(`inventory.assignedSpool`,`Assigned spool`)}),(0,K.jsxs)(`div`,{className:`flex items-center gap-2`,children:[t.spool.rgba&&(0,K.jsx)(`span`,{className:`w-3 h-3 rounded-full border border-black/20 flex-shrink-0`,style:nf(t.spool.rgba)}),(0,K.jsxs)(`span`,{className:`text-sm text-white`,children:[t.spool.brand?`${t.spool.brand} `:``,t.spool.material,t.spool.color_name?` - ${t.spool.color_name}`:``]}),(0,K.jsxs)(`span`,{className:`text-[10px] font-mono text-zinc-500 shrink-0 ml-auto`,children:[`#`,t.spool.id]})]})]}),u&&r&&!a&&(0,K.jsxs)(`div`,{className:`p-2.5 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary mb-3`,children:[(0,K.jsx)(`p`,{className:`text-xs text-bambu-gray mb-1`,children:n(`spoolman.linkedSpool`,`Linked spool`)}),(0,K.jsx)(`div`,{className:`flex items-center gap-2`,children:(0,K.jsxs)(`span`,{className:`text-sm text-white`,children:[`Spoolman #`,r.id,r.remaining_weight==null?``:` (${Math.round(r.remaining_weight)}g)`]})})]}),u&&a&&(0,K.jsxs)(`div`,{className:`p-2.5 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary mb-3`,children:[(0,K.jsx)(`p`,{className:`text-xs text-bambu-gray mb-1`,children:n(`inventory.assignedSpool`,`Assigned spool`)}),(0,K.jsxs)(`div`,{className:`flex items-center gap-2`,children:[a.rgba&&(0,K.jsx)(`span`,{className:`w-3 h-3 rounded-full border border-black/20 flex-shrink-0`,style:nf(a.rgba)}),(0,K.jsxs)(`span`,{className:`text-sm text-white`,children:[a.brand?`${a.brand} `:``,a.material,a.color_name?` - ${a.color_name}`:``]})]})]}),(0,K.jsxs)(`button`,{onClick:se,className:`w-full flex items-center gap-3 p-3 rounded-lg bg-bambu-dark border border-bambu-dark-tertiary hover:border-bambu-blue transition-colors text-left`,children:[(0,K.jsx)(Ul,{className:`w-5 h-5 text-bambu-blue flex-shrink-0`}),(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`p`,{className:`text-white font-medium`,children:n(`configureAmsSlot.title`)}),(0,K.jsx)(`p`,{className:`text-xs text-bambu-gray`,children:n(`spoolbuddy.ams.configureDesc`,`Set filament preset, K-profile, and color`)})]})]}),!u&&(ap(L?.tray)?null:t?(0,K.jsxs)(`button`,{onClick:ue,disabled:re.isPending,className:`w-full flex items-center gap-3 p-3 rounded-lg bg-bambu-dark border border-bambu-dark-tertiary hover:border-amber-500 transition-colors text-left`,children:[(0,K.jsx)(Du,{className:`w-5 h-5 text-amber-400 flex-shrink-0`}),(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`p`,{className:`text-amber-400 font-medium`,children:n(`inventory.unassignSpool`,`Unassign`)}),(0,K.jsx)(`p`,{className:`text-xs text-bambu-gray`,children:n(`spoolbuddy.ams.unassignDesc`,`Remove inventory spool from this slot`)})]})]}):(0,K.jsxs)(`button`,{onClick:ce,className:`w-full flex items-center gap-3 p-3 rounded-lg bg-bambu-dark border border-bambu-dark-tertiary hover:border-bambu-green transition-colors text-left`,children:[(0,K.jsx)(fl,{className:`w-5 h-5 text-bambu-green flex-shrink-0`}),(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`p`,{className:`text-white font-medium`,children:n(`inventory.assignSpool`)}),(0,K.jsx)(`p`,{className:`text-xs text-bambu-gray`,children:n(`spoolbuddy.ams.assignDesc`,`Track a spool from your inventory`)})]})]})),u&&(r?.id?(0,K.jsxs)(`button`,{onClick:()=>ie.mutate(r.id),disabled:ie.isPending,className:`w-full flex items-center gap-3 p-3 rounded-lg bg-bambu-dark border border-bambu-dark-tertiary hover:border-amber-500 transition-colors text-left active:opacity-50`,children:[(0,K.jsx)(Du,{className:`w-5 h-5 text-amber-400 flex-shrink-0`}),(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`p`,{className:`text-amber-400 font-medium`,children:n(`inventory.unassignSpool`)}),(0,K.jsx)(`p`,{className:`text-xs text-bambu-gray`,children:n(`spoolbuddy.ams.unlinkDesc`,`Remove Spoolman link from this slot`)})]})]}):a?(0,K.jsxs)(`button`,{onClick:()=>H.mutate(a.id),disabled:H.isPending,className:`w-full flex items-center gap-3 p-3 rounded-lg bg-bambu-dark border border-bambu-dark-tertiary hover:border-amber-500 transition-colors text-left active:opacity-50`,children:[(0,K.jsx)(Du,{className:`w-5 h-5 text-amber-400 flex-shrink-0`}),(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`p`,{className:`text-amber-400 font-medium`,children:n(`inventory.unassignSpool`)}),(0,K.jsx)(`p`,{className:`text-xs text-bambu-gray`,children:n(`spoolbuddy.ams.unassignDesc`,`Remove inventory spool from this slot`)})]})]}):(0,K.jsxs)(`button`,{onClick:le,className:`w-full flex items-center gap-3 p-3 rounded-lg bg-bambu-dark border border-bambu-dark-tertiary hover:border-bambu-green transition-colors text-left`,children:[(0,K.jsx)(zc,{className:`w-5 h-5 text-bambu-green flex-shrink-0`}),(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`p`,{className:`text-white font-medium`,children:n(`inventory.assignSpool`)}),(0,K.jsx)(`p`,{className:`text-xs text-bambu-gray`,children:n(`spoolbuddy.ams.linkDesc`,`Link a Spoolman spool to this slot`)})]})]}))]})]})]})})(),z&&(0,K.jsx)(bU,{isOpen:!!z,onClose:()=>{B(null),r.invalidateQueries({queryKey:[`spool-assignments`,e]}),r.invalidateQueries({queryKey:[`spool-assignments`]})},printerId:z.printerId,amsId:z.amsId,trayId:z.trayId,trayInfo:z.trayInfo,spoolmanEnabled:!!u}),V&&(0,K.jsx)(vU,{isOpen:!!V,onClose:()=>ee(null),tagUid:V.tagUid,trayUuid:V.trayUuid,printerId:V.printerId,amsId:V.amsId,trayId:V.trayId})]})}function C$e({type:e,deviceId:t,onClose:n}){let{t:r}=W(),[i,a]=(0,y.useState)(!1),[o,s]=(0,y.useState)(``),[c,l]=(0,y.useState)(``),[u,d]=(0,y.useState)(!1);(0,y.useEffect)(()=>{let e=e=>{e.key===`Escape`&&!i&&n()};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[i,n]);let f=(0,y.useCallback)(async()=>{a(!0),s(``),l(``),d(!0);try{s(r(`spoolbuddy.diagnostic.queuing`,`Queuing diagnostic on device... `)),await ud.queueDiagnostics(t,e);let n=null,i=0;for(;i<60&&!n;){await new Promise(e=>setTimeout(e,500));try{n=await ud.getDiagnosticResult(t,e);break}catch{i++,i%4==0&&s(e=>e+`.`)}}if(!n)throw Error(`Diagnostic timed out - device did not report results`);s(n.output),n.success||l(`Exit code: ${n.exit_code}`)}catch(e){l(e instanceof Error?e.message:`Unknown error`),s(``)}finally{a(!1)}},[e,t,r]);return(0,K.jsx)(`div`,{className:`fixed inset-0 z-50 flex items-center justify-center bg-black/70 animate-fade-in`,onClick:n,children:(0,K.jsxs)(`div`,{className:`bg-zinc-800 rounded-lg shadow-xl w-full max-w-2xl mx-4 max-h-[80vh] flex flex-col animate-slide-up`,onClick:e=>e.stopPropagation(),children:[(0,K.jsxs)(`div`,{className:`flex justify-between items-center p-4 border-b border-zinc-700`,children:[(0,K.jsx)(`h2`,{className:`text-lg font-semibold text-white`,children:e===`scale`?r(`spoolbuddy.diagnostic.scaleTitle`,`Scale Diagnostic`):e===`read_tag`?r(`spoolbuddy.diagnostic.readTagTitle`,`Read Tag Diagnostic`):r(`spoolbuddy.diagnostic.nfcTitle`,`NFC Reader Diagnostic`)}),(0,K.jsx)(`button`,{onClick:n,className:`text-zinc-400 hover:text-white transition-colors`,"aria-label":`Close`,children:(0,K.jsx)(Hu,{size:20})})]}),(0,K.jsx)(`div`,{className:`flex-1 overflow-auto p-4 bg-black/50 font-mono text-sm`,children:i?(0,K.jsxs)(`div`,{className:`flex items-center gap-2 text-green-400`,children:[(0,K.jsx)(`div`,{className:`animate-spin w-4 h-4 border-2 border-green-400 border-t-transparent rounded-full`}),(0,K.jsx)(`span`,{children:r(`spoolbuddy.diagnostic.running`,`Running diagnostic on device...`)})]}):o?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`div`,{className:`text-green-400 whitespace-pre-wrap break-words`,children:o}),c&&(0,K.jsxs)(`div`,{className:`text-red-400 mt-2`,children:[`❌ `,c]})]}):u?(0,K.jsx)(`div`,{children:c?(0,K.jsxs)(`div`,{className:`text-red-400`,children:[`ERROR: `,c]}):(0,K.jsx)(`span`,{className:`text-green-400`,children:r(`spoolbuddy.diagnostic.completed`,`Diagnostic completed successfully.`)})}):(0,K.jsxs)(`div`,{className:`text-zinc-500`,children:[r(`spoolbuddy.diagnostic.clickStart`,`Click "Run Diagnostic" to start the hardware diagnostic on`),` `,t,`.`]})}),(0,K.jsxs)(`div`,{className:`flex gap-2 p-4 border-t border-zinc-700 bg-zinc-800`,children:[(0,K.jsx)(`button`,{onClick:f,disabled:i,className:`flex-1 flex items-center justify-center gap-2 bg-green-600 hover:bg-green-700 disabled:bg-gray-600 disabled:cursor-not-allowed px-4 py-2 rounded font-semibold text-white transition-colors`,children:i?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`div`,{className:`animate-spin w-4 h-4 border-2 border-white border-t-transparent rounded-full`}),r(`spoolbuddy.diagnostic.runningBtn`,`Running...`)]}):u?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(Ml,{size:16}),r(`spoolbuddy.diagnostic.runAgain`,`Run Again`)]}):(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(xl,{size:16}),r(`spoolbuddy.diagnostic.runBtn`,`Run Diagnostic`)]})}),(0,K.jsx)(`button`,{onClick:n,className:`px-4 py-2 rounded bg-zinc-700 hover:bg-zinc-600 text-white font-semibold transition-colors`,children:r(`spoolbuddy.diagnostic.close`,`Close`)})]})]})})}function w$e(e){return e<60?`${e}s`:e<3600?`${Math.floor(e/60)}m`:`${Math.floor(e/3600)}h ${Math.floor(e%3600/60)}m`}function T$e(e){if(!e)return`-`;let t=Ef(e);return t?t.toLocaleDateString(void 0,{month:`short`,day:`numeric`})+` `+t.toLocaleTimeString(void 0,{hour:`2-digit`,minute:`2-digit`}):`-`}var E$e=[{label:`Off`,value:0},{label:`1m`,value:60},{label:`2m`,value:120},{label:`5m`,value:300},{label:`10m`,value:600},{label:`30m`,value:1800}];function D$e({device:e}){let{t}=W(),[n,r]=(0,y.useState)(null),[i,a]=(0,y.useState)(``),[o,s]=(0,y.useState)(``),[c,l]=(0,y.useState)(!1),[u,d]=(0,y.useState)(null);return(0,y.useEffect)(()=>{!i&&e.backend_url&&a(e.backend_url)},[e.backend_url,i]),(0,K.jsxs)(`div`,{className:`space-y-2`,children:[(0,K.jsxs)(`div`,{className:`grid grid-cols-2 gap-2`,children:[(0,K.jsxs)(`div`,{className:`bg-zinc-800 rounded-lg p-3`,children:[(0,K.jsx)(`h3`,{className:`text-sm font-semibold text-zinc-300 mb-2`,children:t(`spoolbuddy.settings.nfcReader`,`NFC Reader`)}),(0,K.jsxs)(`div`,{className:`space-y-1.5 text-xs`,children:[(0,K.jsxs)(`div`,{className:`flex justify-between`,children:[(0,K.jsx)(`span`,{className:`text-zinc-500`,children:t(`spoolbuddy.settings.type`,`Type`)}),(0,K.jsx)(`span`,{className:`text-zinc-300 font-mono`,children:e.nfc_reader_type||`N/A`})]}),(0,K.jsxs)(`div`,{className:`flex justify-between`,children:[(0,K.jsx)(`span`,{className:`text-zinc-500`,children:t(`spoolbuddy.settings.connection`,`Connection`)}),(0,K.jsx)(`span`,{className:`text-zinc-300 font-mono`,children:e.nfc_connection||`N/A`})]}),(0,K.jsxs)(`div`,{className:`flex justify-between items-center`,children:[(0,K.jsx)(`span`,{className:`text-zinc-500`,children:t(`spoolbuddy.status.status`,`Status`)}),(0,K.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,K.jsx)(`div`,{className:`w-2 h-2 rounded-full ${e.nfc_ok?`bg-green-500`:e.nfc_reader_type?`bg-red-500`:`bg-zinc-600`}`}),(0,K.jsx)(`span`,{className:e.nfc_ok?`text-green-400`:e.nfc_reader_type?`text-red-400`:`text-zinc-500`,children:e.nfc_ok?t(`spoolbuddy.status.nfcReady`,`Ready`):e.nfc_reader_type?t(`common.error`,`Error`):t(`spoolbuddy.settings.notConnected`,`N/A`)})]})]})]})]}),(0,K.jsxs)(`div`,{className:`bg-zinc-800 rounded-lg p-3`,children:[(0,K.jsx)(`h3`,{className:`text-sm font-semibold text-zinc-300 mb-2`,children:t(`spoolbuddy.settings.deviceInfo`,`Device Info`)}),(0,K.jsxs)(`div`,{className:`space-y-1.5 text-xs`,children:[(0,K.jsxs)(`div`,{className:`flex justify-between`,children:[(0,K.jsx)(`span`,{className:`text-zinc-500`,children:t(`spoolbuddy.settings.hostname`,`Host`)}),(0,K.jsx)(`span`,{className:`text-zinc-300 truncate ml-2`,children:e.hostname})]}),(0,K.jsxs)(`div`,{className:`flex justify-between`,children:[(0,K.jsx)(`span`,{className:`text-zinc-500`,children:`IP`}),(0,K.jsx)(`span`,{className:`text-zinc-300`,children:e.ip_address})]}),(0,K.jsxs)(`div`,{className:`flex justify-between`,children:[(0,K.jsx)(`span`,{className:`text-zinc-500`,children:t(`spoolbuddy.settings.uptime`,`Uptime`)}),(0,K.jsx)(`span`,{className:`text-zinc-300`,children:w$e(e.uptime_s)})]}),(0,K.jsxs)(`div`,{className:`flex justify-between`,children:[(0,K.jsx)(`span`,{className:`text-zinc-500`,children:`ID`}),(0,K.jsx)(`span`,{className:`text-zinc-400 font-mono truncate ml-2`,children:e.device_id})]})]})]})]}),(0,K.jsxs)(`div`,{className:`grid grid-cols-2 gap-2`,children:[(0,K.jsxs)(`div`,{className:`bg-zinc-800 rounded-lg p-3 space-y-2`,children:[(0,K.jsx)(`h3`,{className:`text-sm font-semibold text-zinc-300`,children:t(`spoolbuddy.settings.systemConfig`,`Backend & Auth`)}),(0,K.jsx)(`input`,{value:i,onChange:e=>a(e.target.value),placeholder:`http://192.168.1.100:5000`,className:`w-full px-2 py-1.5 rounded bg-zinc-900 border border-zinc-700 text-zinc-100 text-xs`}),(0,K.jsxs)(`div`,{className:`flex gap-2`,children:[(0,K.jsx)(`input`,{type:`password`,value:o,onChange:e=>s(e.target.value),placeholder:t(`spoolbuddy.settings.apiTokenPlaceholder`,`API token`),className:`flex-1 px-2 py-1.5 rounded bg-zinc-900 border border-zinc-700 text-zinc-100 text-xs`}),(0,K.jsx)(`button`,{onClick:async()=>{if(!i.trim()){d({type:`error`,text:t(`spoolbuddy.settings.systemFieldsRequired`,`Backend URL is required.`)});return}l(!0),d(null);try{await ud.updateSystemConfig(e.device_id,i.trim(),o.trim()||void 0),d({type:`ok`,text:t(`spoolbuddy.settings.systemQueued`,`Config queued.`)})}catch(e){d({type:`error`,text:e instanceof Error?e.message:t(`common.error`,`Error`)})}finally{l(!1)}},disabled:c,className:`px-3 py-1.5 rounded bg-green-700 hover:bg-green-600 disabled:bg-zinc-700 text-xs font-medium text-zinc-100`,children:t(`spoolbuddy.settings.saveConfig`,`Save`)})]}),u&&(0,K.jsx)(`div`,{className:`text-xs ${u.type===`ok`?`text-green-400`:`text-red-400`}`,children:u.text})]}),(0,K.jsxs)(`div`,{className:`bg-zinc-800 rounded-lg p-3 flex flex-col gap-2`,children:[(0,K.jsxs)(`button`,{onClick:()=>r(`nfc`),className:`flex-1 bg-blue-700 hover:bg-blue-600 transition-colors rounded-lg p-2 flex items-center gap-2`,children:[(0,K.jsx)(Fu,{className:`w-4 h-4 text-blue-300 shrink-0`}),(0,K.jsx)(`span`,{className:`text-xs font-medium text-blue-100`,children:t(`spoolbuddy.settings.nfcDiagnostic`,`NFC Diagnostic`)})]}),(0,K.jsxs)(`button`,{onClick:()=>r(`scale`),className:`flex-1 bg-yellow-700 hover:bg-yellow-600 transition-colors rounded-lg p-2 flex items-center gap-2`,children:[(0,K.jsx)(Wu,{className:`w-4 h-4 text-yellow-300 shrink-0`}),(0,K.jsx)(`span`,{className:`text-xs font-medium text-yellow-100`,children:t(`spoolbuddy.settings.scaleDiagnostic`,`Scale Diagnostic`)})]}),(0,K.jsxs)(`button`,{onClick:()=>r(`read_tag`),className:`flex-1 bg-emerald-700 hover:bg-emerald-600 transition-colors rounded-lg p-2 flex items-center gap-2`,children:[(0,K.jsx)(ec,{className:`w-4 h-4 text-emerald-300 shrink-0`}),(0,K.jsx)(`span`,{className:`text-xs font-medium text-emerald-100`,children:t(`spoolbuddy.settings.readTagDiagnostic`,`Read Tag`)})]})]})]}),n&&e&&(0,K.jsx)(C$e,{type:n,deviceId:e.device_id,onClose:()=>r(null)})]})}function O$e({device:e,onBrightnessChange:t}){let{t:n}=W(),[r,i]=(0,y.useState)(e.display_brightness),[a,o]=(0,y.useState)(e.display_blank_timeout),[s,c]=(0,y.useState)(!1),l=(0,y.useRef)(void 0),u=(0,y.useRef)(void 0);(0,y.useEffect)(()=>{i(e.display_brightness),o(e.display_blank_timeout)},[e.display_brightness,e.display_blank_timeout]);let d=(0,y.useCallback)(()=>{c(!0),u.current&&clearTimeout(u.current),u.current=setTimeout(()=>c(!1),1500)},[]),f=(0,y.useCallback)((t,n)=>{l.current&&clearTimeout(l.current),l.current=setTimeout(()=>{ud.updateDisplay(e.device_id,t,n).then(()=>d()).catch(e=>console.error(`Failed to update display:`,e))},300)},[e.device_id,d]),p=e=>{i(e),t(e),f(e,a)},m=e=>{o(e),f(r,e)};return(0,K.jsxs)(`div`,{className:`space-y-4`,children:[(0,K.jsxs)(`div`,{className:`bg-zinc-800 rounded-lg p-4`,children:[(0,K.jsxs)(`div`,{className:`flex items-center justify-between mb-3`,children:[(0,K.jsx)(`h3`,{className:`text-sm font-semibold text-zinc-300`,children:n(`spoolbuddy.settings.brightness`,`Brightness`)}),s&&(0,K.jsxs)(`span`,{className:`text-xs text-green-400 flex items-center gap-1 animate-pulse`,children:[(0,K.jsx)(`svg`,{className:`w-3 h-3`,fill:`none`,viewBox:`0 0 24 24`,stroke:`currentColor`,strokeWidth:3,children:(0,K.jsx)(`path`,{strokeLinecap:`round`,strokeLinejoin:`round`,d:`M5 13l4 4L19 7`})}),n(`spoolbuddy.settings.saved`,`Saved`)]})]}),(0,K.jsxs)(`div`,{className:`flex items-center gap-3`,children:[(0,K.jsx)(`svg`,{className:`w-4 h-4 text-zinc-500 flex-shrink-0`,fill:`none`,viewBox:`0 0 24 24`,stroke:`currentColor`,strokeWidth:2,children:(0,K.jsx)(`path`,{strokeLinecap:`round`,strokeLinejoin:`round`,d:`M12 3v1m0 16v1m9-9h-1M4 12H3m15.364 6.364l-.707-.707M6.343 6.343l-.707-.707m12.728 0l-.707.707M6.343 17.657l-.707.707M16 12a4 4 0 11-8 0 4 4 0 018 0z`})}),(0,K.jsx)(`input`,{type:`range`,min:0,max:100,value:r,onChange:e=>p(parseInt(e.target.value)),className:`flex-1 h-2 bg-zinc-700 rounded-lg appearance-none cursor-pointer accent-green-500`}),(0,K.jsxs)(`span`,{className:`text-sm font-mono text-zinc-400 w-10 text-right`,children:[r,`%`]})]}),!e.has_backlight&&(0,K.jsx)(`p`,{className:`text-xs text-zinc-600 mt-2`,children:n(`spoolbuddy.settings.noBacklight`,`No DSI backlight detected. Brightness control requires a DSI display.`)})]}),(0,K.jsxs)(`div`,{className:`bg-zinc-800 rounded-lg p-4`,children:[(0,K.jsx)(`h3`,{className:`text-sm font-semibold text-zinc-300 mb-1`,children:n(`spoolbuddy.settings.screenBlank`,`Screen Blank Timeout`)}),(0,K.jsx)(`p`,{className:`text-xs text-zinc-500 mb-3`,children:n(`spoolbuddy.settings.screenBlankDesc`,`Screen turns off after inactivity. Touch to wake.`)}),(0,K.jsx)(`div`,{className:`grid grid-cols-3 gap-2`,children:E$e.map(e=>(0,K.jsx)(`button`,{onClick:()=>m(e.value),className:`px-3 py-2 rounded-lg text-sm font-medium transition-colors min-h-[40px] ${a===e.value?`bg-green-600 text-white`:`bg-zinc-700 text-zinc-300 hover:bg-zinc-600`}`,children:e.label},e.value))})]}),(0,K.jsx)(`p`,{className:`text-xs text-zinc-600 text-center`,children:n(`spoolbuddy.settings.displayNote`,`Brightness is applied as a software filter.`)})]})}function k$e({step:e,labels:t}){return(0,K.jsxs)(`div`,{className:`flex flex-col items-center w-16 shrink-0 pt-1`,children:[(0,K.jsx)(`div`,{className:`flex items-center justify-center w-7 h-7 rounded-full text-xs font-bold ${e===`tare`?`bg-green-600 text-white`:`bg-green-600/20 text-green-400`}`,children:e===`weight`?(0,K.jsx)(`svg`,{className:`w-3.5 h-3.5`,fill:`none`,viewBox:`0 0 24 24`,stroke:`currentColor`,strokeWidth:3,children:(0,K.jsx)(`path`,{strokeLinecap:`round`,strokeLinejoin:`round`,d:`M5 13l4 4L19 7`})}):`1`}),(0,K.jsx)(`span`,{className:`text-[10px] mt-0.5 ${e===`tare`?`text-green-400 font-medium`:`text-green-400/60`}`,children:t.tare}),(0,K.jsx)(`div`,{className:`w-px h-5 my-1 ${e===`weight`?`bg-green-600/40`:`bg-zinc-700`}`}),(0,K.jsx)(`div`,{className:`flex items-center justify-center w-7 h-7 rounded-full text-xs font-bold ${e===`weight`?`bg-green-600 text-white`:`bg-zinc-700 text-zinc-500`}`,children:`2`}),(0,K.jsx)(`span`,{className:`text-[10px] mt-0.5 ${e===`weight`?`text-green-400 font-medium`:`text-zinc-600`}`,children:t.weight})]})}function A$e({device:e,weight:t,weightStable:n,rawAdc:r}){let{t:i}=W(),a=to(),[o,s]=(0,y.useState)(`idle`),[c,l]=(0,y.useState)(`500`),[u,d]=(0,y.useState)(null),[f,p]=(0,y.useState)(!1),[m,h]=(0,y.useState)(null),[g,_]=(0,y.useState)(null),v=(0,y.useRef)(null);(0,y.useEffect)(()=>()=>{v.current&&clearTimeout(v.current)},[]);let b=(0,y.useCallback)(e=>{v.current&&clearTimeout(v.current),v.current=setTimeout(()=>h(null),e)},[]);(0,y.useEffect)(()=>{if(!g)return;let e=()=>Date.now()-g.startedAtMs,t=setInterval(()=>{a.invalidateQueries({queryKey:[`spoolbuddy-devices`]})},1e3),n=setTimeout(()=>{_(null),h({type:`error`,msg:i(`spoolbuddy.settings.tareTimedOut`,`Tare timed out — is the SpoolBuddy daemon running?`)}),b(5e3)},Math.max(0,15e3-e()));return()=>{clearInterval(t),clearTimeout(n)}},[g,a,i,b]),(0,y.useEffect)(()=>{g&&(e?.last_calibrated_at??null)!==g.snapshot&&(_(null),h({type:`ok`,msg:i(`spoolbuddy.settings.tareComplete`,`Tare complete!`)}),b(3e3))},[e?.last_calibrated_at,g,i,b]);let x=e=>{e===`backspace`?l(e=>e.slice(0,-1)||``):e===`.`&&!c.includes(`.`)?l(e=>e+`.`):e>=`0`&&e<=`9`&&l(t=>t===`0`?e:t+e)};return o===`idle`?(0,K.jsxs)(`div`,{className:`flex flex-col h-full`,children:[(0,K.jsxs)(`div`,{className:`bg-zinc-800 rounded-lg p-3 mb-3`,children:[(0,K.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,K.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,K.jsx)(`div`,{className:`w-2 h-2 rounded-full ${n?`bg-green-500`:`bg-amber-500 animate-pulse`}`}),(0,K.jsx)(`span`,{className:`text-lg font-mono text-zinc-200`,children:t===null?`-- g`:`${t.toFixed(1)} g`})]}),(0,K.jsxs)(`div`,{className:`text-xs text-zinc-500 text-right`,children:[(0,K.jsxs)(`span`,{children:[i(`spoolbuddy.settings.tareOffset`,`Tare`),`: `,e.tare_offset]}),(0,K.jsx)(`span`,{className:`mx-1.5`,children:`·`}),(0,K.jsxs)(`span`,{children:[i(`spoolbuddy.settings.calFactor`,`Factor`),`: `,e.calibration_factor.toFixed(2)]})]})]}),e.last_calibrated_at&&(0,K.jsxs)(`div`,{className:`text-xs text-zinc-600 mt-1`,children:[i(`spoolbuddy.settings.lastCalibrated`,`Last calibrated`),`: `,T$e(e.last_calibrated_at)]})]}),m&&(0,K.jsx)(`div`,{className:`rounded-lg px-3 py-2 mb-3 text-sm ${m.type===`ok`?`bg-green-900/30 text-green-300 border border-green-800`:`bg-red-900/30 text-red-300 border border-red-800`}`,children:m.msg}),(0,K.jsxs)(`div`,{className:`flex gap-2`,children:[(0,K.jsxs)(`button`,{onClick:async()=>{p(!0),h(null),v.current&&=(clearTimeout(v.current),null);let t=e?.last_calibrated_at??null;try{await ud.tare(e.device_id),h({type:`ok`,msg:i(`spoolbuddy.settings.tareSet`,`Tare command sent. Waiting for device...`)}),_({snapshot:t,startedAtMs:Date.now()})}catch{h({type:`error`,msg:i(`spoolbuddy.settings.tareFailed`,`Failed to send tare command`)}),b(5e3)}finally{p(!1)}},disabled:f,className:`flex-1 px-4 py-2.5 rounded-lg text-sm font-medium bg-zinc-700 text-zinc-200 hover:bg-zinc-600 disabled:opacity-40 transition-colors min-h-[44px] flex items-center justify-center gap-2`,children:[f&&(0,K.jsxs)(`svg`,{className:`w-4 h-4 animate-spin`,viewBox:`0 0 24 24`,fill:`none`,children:[(0,K.jsx)(`circle`,{className:`opacity-25`,cx:`12`,cy:`12`,r:`10`,stroke:`currentColor`,strokeWidth:`4`}),(0,K.jsx)(`path`,{className:`opacity-75`,fill:`currentColor`,d:`M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z`})]}),i(`spoolbuddy.weight.tare`,`Tare`)]}),(0,K.jsx)(`button`,{onClick:()=>{s(`tare`),h(null)},className:`flex-1 px-4 py-2.5 rounded-lg text-sm font-medium bg-green-600 text-white hover:bg-green-700 transition-colors min-h-[44px]`,children:i(`spoolbuddy.weight.calibrate`,`Calibrate`)})]})]}):(0,K.jsxs)(`div`,{className:`flex gap-3`,children:[(0,K.jsx)(k$e,{step:o,labels:{tare:i(`spoolbuddy.weight.tare`,`Tare`),weight:i(`spoolbuddy.settings.knownWeight`,`Known weight`)}}),(0,K.jsxs)(`div`,{className:`flex-1 min-w-0`,children:[(0,K.jsxs)(`div`,{className:`flex items-center gap-2 bg-zinc-800 rounded-lg px-3 py-1.5 mb-1.5`,children:[(0,K.jsx)(`div`,{className:`w-2 h-2 rounded-full shrink-0 ${n?`bg-green-500`:`bg-amber-500 animate-pulse`}`}),(0,K.jsx)(`span`,{className:`text-sm font-mono text-zinc-200`,children:t===null?`-- g`:`${t.toFixed(1)} g`}),(0,K.jsx)(`span`,{className:`text-xs ml-auto ${n?`text-green-400`:`text-amber-400`}`,children:n?i(`spoolbuddy.settings.stable`,`Stable`):i(`spoolbuddy.settings.settling`,`Settling...`)})]}),m&&(0,K.jsx)(`div`,{className:`rounded-lg px-3 py-1.5 mb-1.5 text-xs ${m.type===`ok`?`bg-green-900/30 text-green-300 border border-green-800`:`bg-red-900/30 text-red-300 border border-red-800`}`,children:m.msg}),o===`tare`?(0,K.jsx)(`p`,{className:`text-sm text-zinc-300 mb-3`,children:i(`spoolbuddy.settings.calStep1`,`Remove all items from the scale and press Set Zero.`)}):(0,K.jsxs)(K.Fragment,{children:[(0,K.jsxs)(`div`,{className:`flex items-center gap-2 mb-1.5`,children:[(0,K.jsx)(`span`,{className:`text-xs text-zinc-400 shrink-0`,children:i(`spoolbuddy.settings.knownWeight`,`Known weight`)}),(0,K.jsxs)(`div`,{className:`flex-1 bg-zinc-900 border border-zinc-600 rounded px-3 py-1 text-right text-lg font-mono text-zinc-100`,children:[c||`0`,(0,K.jsx)(`span`,{className:`text-zinc-500 ml-1`,children:`g`})]})]}),(0,K.jsx)(`div`,{className:`grid grid-cols-4 gap-1 mb-1.5`,children:[`7`,`8`,`9`,`backspace`,`4`,`5`,`6`,`.`,`1`,`2`,`3`,`0`].map(e=>(0,K.jsx)(`button`,{onClick:()=>x(e),className:`rounded text-lg font-medium transition-colors h-[48px] active:scale-95 ${e===`backspace`?`bg-zinc-700 text-zinc-300 hover:bg-zinc-600`:`bg-zinc-800 text-zinc-100 hover:bg-zinc-700 border border-zinc-700`}`,children:e===`backspace`?`⌫`:e},e))})]}),(0,K.jsxs)(`div`,{className:`flex gap-2`,children:[(0,K.jsx)(`button`,{onClick:()=>{s(`idle`),h(null)},className:`flex-1 px-4 py-2 rounded-lg text-sm bg-zinc-700 text-zinc-300 hover:bg-zinc-600 transition-colors h-[40px]`,children:i(`common.cancel`,`Cancel`)}),(0,K.jsxs)(`button`,{onClick:async()=>{if(o===`tare`){p(!0),h(null);try{d(r),await ud.tare(e.device_id),h({type:`ok`,msg:i(`spoolbuddy.settings.zeroSet`,`Zero point set. Place known weight on scale.`)}),s(`weight`)}catch{h({type:`error`,msg:i(`spoolbuddy.settings.tareFailed`,`Failed to send tare command`)})}finally{p(!1)}}else if(o===`weight`){let t=parseFloat(c);if(r===null||!t||t<=0)return;p(!0),h(null);try{await ud.setCalibrationFactor(e.device_id,t,r,u??void 0),h({type:`ok`,msg:i(`spoolbuddy.settings.calibrationDone`,`Calibration complete!`)}),b(3e3),s(`idle`)}catch{h({type:`error`,msg:i(`spoolbuddy.settings.calibrationFailed`,`Calibration failed`)}),b(5e3)}finally{p(!1)}}},disabled:f,className:`flex-1 px-4 py-2 rounded-lg text-sm font-medium bg-green-600 text-white hover:bg-green-700 disabled:opacity-40 transition-colors h-[40px] flex items-center justify-center gap-2`,children:[f&&(0,K.jsxs)(`svg`,{className:`w-4 h-4 animate-spin`,viewBox:`0 0 24 24`,fill:`none`,children:[(0,K.jsx)(`circle`,{className:`opacity-25`,cx:`12`,cy:`12`,r:`10`,stroke:`currentColor`,strokeWidth:`4`}),(0,K.jsx)(`path`,{className:`opacity-75`,fill:`currentColor`,d:`M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z`})]}),o===`tare`?i(`spoolbuddy.settings.setZero`,`Set Zero`):i(`spoolbuddy.settings.calibrateNow`,`Calibrate`)]})]})]})]})}function j$e({device:e}){let{t}=W(),[n,r]=(0,y.useState)(null),[i,a]=(0,y.useState)(null),[o,s]=(0,y.useState)(!1),[c,l]=(0,y.useState)(!1),u=e.update_status===`pending`||e.update_status===`updating`;(0,y.useEffect)(()=>{u&&n===`applying`&&r(null)},[u,n]),(0,y.useEffect)(()=>{let e=()=>{u&&setTimeout(()=>window.location.reload(),1e3)};return window.addEventListener(`spoolbuddy-online`,e),()=>window.removeEventListener(`spoolbuddy-online`,e)},[u]);let{data:d,refetch:f}=q({queryKey:[`spoolbuddy-update-check`,e.device_id],queryFn:()=>ud.checkDaemonUpdate(e.device_id),staleTime:0}),{data:p}=q({queryKey:[`spoolbuddy-ssh-key`],queryFn:()=>ud.getSSHPublicKey(),enabled:o,staleTime:1/0}),m=async()=>{r(`checking`),a(null);try{await f()}finally{r(null)}},h=async()=>{r(`applying`),a(null);try{await ud.triggerUpdate(e.device_id)}catch(e){a(e instanceof Error?e.message:`Failed to trigger update`),r(null)}},g=n!=null||u,_=()=>{p?.public_key&&(navigator.clipboard.writeText(p.public_key),l(!0),setTimeout(()=>l(!1),2e3))},v=e.firmware_version||(d?.current_version&&d.current_version!==`0.0.0`?d.current_version:null);return(0,K.jsxs)(`div`,{className:`space-y-3`,children:[(0,K.jsxs)(`div`,{className:`bg-zinc-800 rounded-lg p-3 space-y-3`,children:[(0,K.jsxs)(`div`,{className:`flex justify-between items-center text-sm`,children:[(0,K.jsx)(`span`,{className:`text-zinc-500`,children:t(`spoolbuddy.settings.currentVersion`,`Current Version`)}),(0,K.jsx)(`span`,{className:`text-zinc-200 font-mono`,children:v||(0,K.jsx)(`span`,{className:`text-zinc-500 italic text-xs`,children:t(`spoolbuddy.settings.versionPending`,`Waiting for daemon...`)})})]}),g?(0,K.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,K.jsxs)(`svg`,{className:`w-4 h-4 animate-spin text-green-400 flex-shrink-0`,viewBox:`0 0 24 24`,fill:`none`,children:[(0,K.jsx)(`circle`,{className:`opacity-25`,cx:`12`,cy:`12`,r:`10`,stroke:`currentColor`,strokeWidth:`4`}),(0,K.jsx)(`path`,{className:`opacity-75`,fill:`currentColor`,d:`M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z`})]}),(0,K.jsx)(`span`,{className:`text-green-300 text-xs`,children:n===`checking`?t(`spoolbuddy.settings.checking`,`Checking for updates...`):e.update_message||t(`spoolbuddy.settings.updateWaiting`,`Updating...`)})]}):e.update_status===`error`?(0,K.jsx)(`p`,{className:`text-xs text-red-300`,children:e.update_message||t(`spoolbuddy.settings.updateFailed`,`Update failed`)}):i?(0,K.jsx)(`p`,{className:`text-xs text-red-300`,children:i}):d?.update_available?(0,K.jsxs)(`p`,{className:`text-xs text-green-300`,children:[t(`spoolbuddy.settings.updateAvailable`,`Update available`),`: `,v,` → `,d.latest_version]}):null,!g&&(d?.update_available?(0,K.jsx)(`button`,{onClick:h,disabled:!e.online,className:`w-full px-3 py-2 rounded-lg text-sm font-medium bg-green-600 text-white hover:bg-green-700 disabled:opacity-40 transition-colors`,children:e.online?t(`spoolbuddy.settings.applyUpdate`,`Apply Update`):t(`spoolbuddy.settings.deviceOffline`,`Device Offline`)}):(0,K.jsxs)(`div`,{className:`flex gap-2`,children:[(0,K.jsx)(`button`,{onClick:m,className:`flex-1 px-3 py-2 rounded-lg text-xs font-medium bg-zinc-700 text-zinc-300 hover:bg-zinc-600 transition-colors`,children:t(`spoolbuddy.settings.checkUpdates`,`Check for Updates`)}),(0,K.jsx)(`button`,{onClick:h,disabled:!e.online,className:`px-3 py-2 rounded-lg text-xs font-medium bg-zinc-700 text-zinc-400 hover:bg-zinc-600 hover:text-zinc-200 disabled:opacity-40 transition-colors`,children:t(`spoolbuddy.settings.forceUpdate`,`Force Update`)})]}))]}),(0,K.jsxs)(`div`,{className:`bg-zinc-800 rounded-lg p-3`,children:[(0,K.jsxs)(`button`,{onClick:()=>s(!o),className:`w-full flex justify-between items-center text-xs`,children:[(0,K.jsx)(`span`,{className:`font-medium text-zinc-400`,children:t(`spoolbuddy.settings.sshSetup`,`SSH Setup`)}),(0,K.jsx)(`svg`,{className:`w-3 h-3 text-zinc-500 transition-transform ${o?`rotate-180`:``}`,fill:`none`,viewBox:`0 0 24 24`,stroke:`currentColor`,strokeWidth:2,children:(0,K.jsx)(`path`,{strokeLinecap:`round`,strokeLinejoin:`round`,d:`M19 9l-7 7-7-7`})})]}),o&&(0,K.jsxs)(`div`,{className:`mt-2 space-y-2`,children:[(0,K.jsx)(`p`,{className:`text-xs text-zinc-500`,children:t(`spoolbuddy.settings.sshDescription`,`SSH key is deployed automatically. For manual setup, add this key to ~/.ssh/authorized_keys on the device.`)}),p?.public_key?(0,K.jsxs)(`div`,{className:`relative`,children:[(0,K.jsx)(`pre`,{className:`bg-zinc-900 rounded p-2 text-[10px] text-zinc-400 font-mono break-all whitespace-pre-wrap`,children:p.public_key}),(0,K.jsx)(`button`,{onClick:_,className:`absolute top-1 right-1 px-1.5 py-0.5 rounded text-[10px] bg-zinc-700 text-zinc-300 hover:bg-zinc-600 transition-colors`,children:c?t(`common.copied`,`Copied!`):t(`common.copy`,`Copy`)})]}):(0,K.jsx)(`span`,{className:`text-[10px] text-zinc-500 italic`,children:t(`spoolbuddy.settings.sshKeyLoading`,`Loading...`)})]})]})]})}function M$e({percent:e,color:t}){return(0,K.jsx)(`div`,{className:`w-full h-2 bg-zinc-700 rounded-full overflow-hidden`,children:(0,K.jsx)(`div`,{className:`h-full rounded-full transition-all ${t}`,style:{width:`${Math.min(100,Math.max(0,e))}%`}})})}function N$e(e){let t=Math.floor(e/86400),n=Math.floor(e%86400/3600),r=Math.floor(e%3600/60);return t>0?`${t}d ${n}h ${r}m`:n>0?`${n}h ${r}m`:`${r}m`}function P$e({device:e}){let{t}=W(),n=e.system_stats;if(!n)return(0,K.jsx)(`div`,{className:`flex items-center justify-center h-32`,children:(0,K.jsx)(`p`,{className:`text-sm text-zinc-500`,children:t(`spoolbuddy.settings.systemStatsWaiting`,`Waiting for system stats...`)})});let r=n.memory,i=n.disk,a=(n.cpu_temp_c??0)>=80?`text-red-400`:(n.cpu_temp_c??0)>=65?`text-amber-400`:`text-green-400`,o=(r?.percent??0)>=90?`bg-red-500`:(r?.percent??0)>=70?`bg-amber-500`:`bg-green-500`,s=(i?.percent??0)>=90?`bg-red-500`:(i?.percent??0)>=70?`bg-amber-500`:`bg-green-500`;return(0,K.jsxs)(`div`,{className:`space-y-2`,children:[(0,K.jsxs)(`div`,{className:`grid grid-cols-2 gap-2`,children:[(0,K.jsxs)(`div`,{className:`bg-zinc-800 rounded-lg p-3`,children:[(0,K.jsx)(`h3`,{className:`text-sm font-semibold text-zinc-300 mb-2`,children:`CPU`}),(0,K.jsxs)(`div`,{className:`space-y-1.5 text-xs`,children:[(0,K.jsxs)(`div`,{className:`flex justify-between`,children:[(0,K.jsx)(`span`,{className:`text-zinc-500`,children:t(`spoolbuddy.settings.cores`,`Cores`)}),(0,K.jsx)(`span`,{className:`text-zinc-300 font-mono`,children:n.cpu_count??`-`})]}),(0,K.jsxs)(`div`,{className:`flex justify-between`,children:[(0,K.jsx)(`span`,{className:`text-zinc-500`,children:t(`spoolbuddy.settings.loadAvg`,`Load Avg`)}),(0,K.jsx)(`span`,{className:`text-zinc-300 font-mono`,children:n.load_avg?n.load_avg.join(` / `):`-`})]}),(0,K.jsxs)(`div`,{className:`flex justify-between`,children:[(0,K.jsx)(`span`,{className:`text-zinc-500`,children:t(`spoolbuddy.settings.temp`,`Temp`)}),(0,K.jsx)(`span`,{className:`font-mono font-medium ${a}`,children:n.cpu_temp_c==null?`-`:`${n.cpu_temp_c}\u00B0C`})]})]})]}),(0,K.jsxs)(`div`,{className:`bg-zinc-800 rounded-lg p-3`,children:[(0,K.jsx)(`h3`,{className:`text-sm font-semibold text-zinc-300 mb-2`,children:t(`spoolbuddy.settings.memory`,`Memory`)}),r?(0,K.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,K.jsx)(M$e,{percent:r.percent??0,color:o}),(0,K.jsxs)(`div`,{className:`space-y-1 text-xs`,children:[(0,K.jsxs)(`div`,{className:`flex justify-between`,children:[(0,K.jsx)(`span`,{className:`text-zinc-500`,children:t(`spoolbuddy.settings.used`,`Used`)}),(0,K.jsxs)(`span`,{className:`text-zinc-300 font-mono`,children:[r.used_mb,` / `,r.total_mb,` MB`]})]}),(0,K.jsxs)(`div`,{className:`flex justify-between`,children:[(0,K.jsx)(`span`,{className:`text-zinc-500`,children:t(`spoolbuddy.settings.available`,`Free`)}),(0,K.jsxs)(`span`,{className:`text-zinc-300 font-mono`,children:[r.available_mb,` MB`]})]})]})]}):(0,K.jsx)(`span`,{className:`text-xs text-zinc-500`,children:`-`})]})]}),(0,K.jsx)(`div`,{className:`bg-zinc-800 rounded-lg px-3 py-2`,children:(0,K.jsxs)(`div`,{className:`flex items-center gap-3`,children:[(0,K.jsx)(`h3`,{className:`text-sm font-semibold text-zinc-300 shrink-0`,children:t(`spoolbuddy.settings.disk`,`Disk`)}),i?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`div`,{className:`flex-1`,children:(0,K.jsx)(M$e,{percent:i.percent??0,color:s})}),(0,K.jsxs)(`span`,{className:`text-xs text-zinc-300 font-mono shrink-0`,children:[i.used_gb,` / `,i.total_gb,` GB`]})]}):(0,K.jsx)(`span`,{className:`text-xs text-zinc-500`,children:`-`})]})}),(0,K.jsxs)(`div`,{className:`grid grid-cols-2 gap-2`,children:[(0,K.jsxs)(`div`,{className:`bg-zinc-800 rounded-lg p-3`,children:[(0,K.jsx)(`h3`,{className:`text-sm font-semibold text-zinc-300 mb-1.5`,children:t(`spoolbuddy.settings.osInfo`,`OS`)}),(0,K.jsxs)(`div`,{className:`space-y-1 text-xs`,children:[n.os?.os&&(0,K.jsxs)(`div`,{className:`flex justify-between`,children:[(0,K.jsx)(`span`,{className:`text-zinc-500`,children:t(`spoolbuddy.settings.distro`,`Distro`)}),(0,K.jsx)(`span`,{className:`text-zinc-300 truncate ml-2`,children:n.os.os})]}),n.os?.kernel&&(0,K.jsxs)(`div`,{className:`flex justify-between`,children:[(0,K.jsx)(`span`,{className:`text-zinc-500`,children:t(`spoolbuddy.settings.kernel`,`Kernel`)}),(0,K.jsx)(`span`,{className:`text-zinc-300 font-mono truncate ml-2`,children:n.os.kernel})]}),n.os?.arch&&(0,K.jsxs)(`div`,{className:`flex justify-between`,children:[(0,K.jsx)(`span`,{className:`text-zinc-500`,children:t(`spoolbuddy.settings.arch`,`Arch`)}),(0,K.jsx)(`span`,{className:`text-zinc-300 font-mono`,children:n.os.arch})]})]})]}),(0,K.jsxs)(`div`,{className:`bg-zinc-800 rounded-lg p-3`,children:[(0,K.jsx)(`h3`,{className:`text-sm font-semibold text-zinc-300 mb-1.5`,children:t(`spoolbuddy.settings.runtime`,`Runtime`)}),(0,K.jsxs)(`div`,{className:`space-y-1 text-xs`,children:[n.os?.python&&(0,K.jsxs)(`div`,{className:`flex justify-between`,children:[(0,K.jsx)(`span`,{className:`text-zinc-500`,children:`Python`}),(0,K.jsx)(`span`,{className:`text-zinc-300 font-mono`,children:n.os.python})]}),n.system_uptime_s!=null&&(0,K.jsxs)(`div`,{className:`flex justify-between`,children:[(0,K.jsx)(`span`,{className:`text-zinc-500`,children:t(`spoolbuddy.settings.systemUptime`,`Uptime`)}),(0,K.jsx)(`span`,{className:`text-zinc-300`,children:N$e(n.system_uptime_s)})]})]})]})]})]})}function F$e(){let{sbState:e,setDisplayBrightness:t}=nr(),{t:n}=W(),[r,i]=(0,y.useState)(`device`),{data:a=[]}=q({queryKey:[`spoolbuddy-devices`],queryFn:()=>ud.getDevices(),refetchInterval:1e4}),o=e.deviceId?a.find(t=>t.device_id===e.deviceId)??a[0]:a[0],s=[{id:`device`,label:n(`spoolbuddy.settings.tabDevice`,`Device`)},{id:`display`,label:n(`spoolbuddy.settings.tabDisplay`,`Display`)},{id:`scale`,label:n(`spoolbuddy.settings.tabScale`,`Scale`)},{id:`updates`,label:n(`spoolbuddy.settings.tabUpdates`,`Updates`)},{id:`system`,label:n(`spoolbuddy.settings.tabSystem`,`System`)}];return(0,K.jsxs)(`div`,{className:`h-full flex flex-col p-4`,children:[(0,K.jsx)(`h1`,{className:`text-xl font-semibold text-zinc-100 mb-3`,children:n(`spoolbuddy.nav.settings`,`Settings`)}),(0,K.jsx)(`div`,{className:`flex gap-1 bg-zinc-800/50 rounded-lg p-1 mb-4`,children:s.map(e=>(0,K.jsx)(`button`,{onClick:()=>i(e.id),className:`flex-1 px-2 py-2 rounded-md text-sm font-medium transition-colors min-h-[36px] ${r===e.id?`bg-zinc-700 text-zinc-100`:`text-zinc-500 hover:text-zinc-300`}`,children:e.label},e.id))}),(0,K.jsx)(`div`,{className:`flex-1 min-h-0 overflow-y-auto`,children:o?(0,K.jsxs)(K.Fragment,{children:[r===`device`&&(0,K.jsx)(D$e,{device:o}),r===`display`&&(0,K.jsx)(O$e,{device:o,onBrightnessChange:t}),r===`scale`&&(0,K.jsx)(A$e,{device:o,weight:e.weight,weightStable:e.weightStable,rawAdc:e.rawAdc}),r===`updates`&&(0,K.jsx)(j$e,{device:o}),r===`system`&&(0,K.jsx)(P$e,{device:o})]}):(0,K.jsx)(`div`,{className:`flex items-center justify-center h-32`,children:(0,K.jsx)(`div`,{className:`text-center text-zinc-500`,children:(0,K.jsx)(`p`,{className:`text-sm`,children:n(`spoolbuddy.settings.noDevice`,`No SpoolBuddy device found`)})})})})]})}function I$e({device:e,weight:t,weightStable:n,rawAdc:r}){let{t:i}=W(),[a,o]=(0,y.useState)(!1),[s,c]=(0,y.useState)(`idle`),[l,u]=(0,y.useState)(`500`),[d,f]=(0,y.useState)(null),[p,m]=(0,y.useState)(!1),h=e=>{e===`backspace`?u(e=>e.slice(0,-1)||``):e===`.`&&!l.includes(`.`)?u(e=>e+`.`):e>=`0`&&e<=`9`&&u(t=>t===`0`?e:t+e)};return(0,K.jsxs)(`div`,{className:`space-y-4`,children:[(0,K.jsxs)(`div`,{className:`bg-zinc-800 rounded-lg p-4`,children:[(0,K.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,K.jsx)(`span`,{className:`text-sm text-zinc-400`,children:i(`spoolbuddy.settings.currentWeight`,`Current weight`)}),(0,K.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,K.jsx)(`div`,{className:`w-2 h-2 rounded-full ${n?`bg-green-500`:`bg-amber-500 animate-pulse`}`}),(0,K.jsx)(`span`,{className:`text-lg font-mono text-zinc-200`,children:t===null?`-- g`:`${t.toFixed(1)} g`})]})]}),(0,K.jsxs)(`div`,{className:`grid grid-cols-2 gap-4 mt-3 text-xs`,children:[(0,K.jsxs)(`div`,{className:`flex justify-between`,children:[(0,K.jsx)(`span`,{className:`text-zinc-500`,children:i(`spoolbuddy.settings.tareOffset`,`Tare offset`)}),(0,K.jsx)(`span`,{className:`text-zinc-400 font-mono`,children:e.tare_offset})]}),(0,K.jsxs)(`div`,{className:`flex justify-between`,children:[(0,K.jsx)(`span`,{className:`text-zinc-500`,children:i(`spoolbuddy.settings.calFactor`,`Cal. factor`)}),(0,K.jsx)(`span`,{className:`text-zinc-400 font-mono`,children:e.calibration_factor.toFixed(2)})]})]})]}),s===`idle`?(0,K.jsxs)(`div`,{className:`flex gap-2`,children:[(0,K.jsx)(`button`,{onClick:async()=>{m(!0);try{await ud.tare(e.device_id)}catch(e){console.error(`Failed to tare:`,e)}finally{m(!1)}},disabled:p,className:`flex-1 px-4 py-2.5 rounded-lg text-sm font-medium bg-zinc-700 text-zinc-200 hover:bg-zinc-600 disabled:opacity-40 transition-colors min-h-[44px]`,children:p?`...`:i(`spoolbuddy.weight.tare`,`Tare`)}),(0,K.jsx)(`button`,{onClick:()=>{c(`tare`)},className:`flex-1 px-4 py-2.5 rounded-lg text-sm font-medium bg-green-600 text-white hover:bg-green-700 transition-colors min-h-[44px]`,children:i(`spoolbuddy.weight.calibrate`,`Calibrate`)})]}):(0,K.jsxs)(`div`,{className:`bg-zinc-800 border border-zinc-700 rounded-lg p-3 space-y-2`,children:[(0,K.jsx)(`div`,{className:`text-sm font-medium text-zinc-200`,children:s===`tare`?i(`spoolbuddy.settings.calStep1`,`Step 1: Remove all items from the scale`):i(`spoolbuddy.settings.calStep2`,`Step 2: Place known weight on scale`)}),s===`weight`&&(0,K.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,K.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,K.jsx)(`span`,{className:`text-xs text-zinc-400`,children:i(`spoolbuddy.settings.knownWeight`,`Known weight (g)`)}),(0,K.jsxs)(`div`,{className:`flex-1 bg-zinc-900 border border-zinc-600 rounded px-3 py-1.5 text-right text-base font-mono text-zinc-100`,children:[l||`0`,(0,K.jsx)(`span`,{className:`text-zinc-500 ml-1`,children:`g`})]})]}),(0,K.jsx)(`div`,{className:`grid grid-cols-4 gap-1`,children:[`7`,`8`,`9`,`backspace`,`4`,`5`,`6`,`.`,`1`,`2`,`3`,`0`].map(e=>(0,K.jsx)(`button`,{onClick:()=>h(e),className:`py-2 rounded text-sm font-medium transition-colors min-h-[36px] ${e===`backspace`?`bg-zinc-700 text-zinc-300 hover:bg-zinc-600`:`bg-zinc-800 text-zinc-100 hover:bg-zinc-700 border border-zinc-700`}`,children:e===`backspace`?`⌫`:e},e))})]}),(0,K.jsxs)(`div`,{className:`flex gap-2`,children:[(0,K.jsx)(`button`,{onClick:()=>c(`idle`),className:`flex-1 px-4 py-2 rounded-lg text-sm bg-zinc-700 text-zinc-300 hover:bg-zinc-600 transition-colors min-h-[40px]`,children:i(`common.cancel`,`Cancel`)}),(0,K.jsx)(`button`,{onClick:async()=>{if(s===`tare`){o(!0);try{f(r),await ud.tare(e.device_id),c(`weight`)}catch(e){console.error(`Failed to tare:`,e)}finally{o(!1)}}else if(s===`weight`){let t=parseFloat(l);if(r===null||!t||t<=0)return;o(!0);try{await ud.setCalibrationFactor(e.device_id,t,r,d??void 0),c(`idle`)}catch(e){console.error(`Failed to calibrate:`,e)}finally{o(!1)}}},disabled:a,className:`flex-1 px-4 py-2 rounded-lg text-sm font-medium bg-green-600 text-white hover:bg-green-700 disabled:opacity-40 transition-colors min-h-[40px]`,children:a?`...`:s===`tare`?i(`spoolbuddy.settings.setZero`,`Set Zero`):i(`spoolbuddy.settings.calibrateNow`,`Calibrate`)})]})]})]})}function L$e(){let{sbState:e}=nr(),{t}=W(),n=$n(),{data:r=[]}=q({queryKey:[`spoolbuddy-devices`],queryFn:()=>ud.getDevices(),refetchInterval:1e4}),i=e.deviceId?r.find(t=>t.device_id===e.deviceId)??r[0]:r[0];return(0,K.jsxs)(`div`,{className:`h-full flex flex-col p-4`,children:[(0,K.jsxs)(`div`,{className:`flex items-center gap-3 mb-4`,children:[(0,K.jsx)(`button`,{onClick:()=>n(`/spoolbuddy/settings`),className:`p-1.5 rounded-lg text-zinc-400 hover:text-zinc-200 hover:bg-zinc-800 transition-colors`,children:(0,K.jsx)(`svg`,{className:`w-5 h-5`,fill:`none`,viewBox:`0 0 24 24`,stroke:`currentColor`,strokeWidth:2,children:(0,K.jsx)(`path`,{strokeLinecap:`round`,strokeLinejoin:`round`,d:`M15 19l-7-7 7-7`})})}),(0,K.jsx)(`h1`,{className:`text-xl font-semibold text-zinc-100`,children:t(`spoolbuddy.settings.scaleCalibration`,`Scale Calibration`)})]}),(0,K.jsx)(`div`,{className:`flex-1 min-h-0 overflow-y-auto`,children:i?(0,K.jsx)(I$e,{device:i,weight:e.weight,weightStable:e.weightStable,rawAdc:e.rawAdc}):(0,K.jsx)(`div`,{className:`flex items-center justify-center h-32`,children:(0,K.jsx)(`div`,{className:`text-center text-zinc-500`,children:(0,K.jsx)(`p`,{className:`text-sm`,children:t(`spoolbuddy.settings.noDevice`,`No SpoolBuddy device found`)})})})})]})}var R$e=[`PLA`,`PETG`,`ABS`,`ASA`,`TPU`,`PA`,`PC`,`PVA`,`HIPS`];function z$e(){let{t:e}=W(),{showToast:t}=kd(),{sbState:n}=nr(),[r,i]=(0,y.useState)(`existing`),[a,o]=(0,y.useState)(null),[s,c]=(0,y.useState)(``),[l,u]=(0,y.useState)(`idle`),[d,f]=(0,y.useState)(``),[p,m]=(0,y.useState)(!1),[h,g]=(0,y.useState)(!1),[_,v]=(0,y.useState)(null),{data:b}=q({queryKey:[`spoolman-settings`],queryFn:Q.getSpoolmanSettings,staleTime:300*1e3}),x=b!==void 0,S=b?.spoolman_enabled===`true`&&!!b?.spoolman_url,{data:C=[],refetch:w}=q({queryKey:[S?`spoolman-inventory-spools`:`inventory-spools`,`write-tag`],queryFn:()=>S?Q.getSpoolmanInventorySpools(!1):Q.getSpools(!1),refetchInterval:1e4,enabled:x}),{data:T=[]}=q({queryKey:[`spoolbuddy-devices`],queryFn:()=>ud.getDevices(),refetchInterval:5e3}),{data:E}=q({queryKey:[`settings`],queryFn:Q.getSettings}),D=T[0],O=n.deviceOnline,k=cf(E?.currency||`USD`),A=(0,y.useMemo)(()=>{let e;if(r===`existing`)e=C.filter(e=>!e.tag_uid&&!e.archived_at);else if(r===`replace`)e=C.filter(e=>(e.tag_uid||e.tray_uuid)&&!e.archived_at);else return[];if(s){let t=s.toLowerCase();e=e.filter(e=>e.material?.toLowerCase().includes(t)||e.color_name?.toLowerCase().includes(t)||e.brand?.toLowerCase().includes(t)||e.subtype?.toLowerCase().includes(t))}return e},[C,r,s]),j=(0,y.useCallback)(e=>{let t=e.detail;(t.sak??t.data?.sak)===0&&(g(!0),v(t.tag_uid??t.data?.tag_uid??null))},[]),M=(0,y.useCallback)(e=>{let t=e.detail;g(!0),v(t.tag_uid??t.data?.tag_uid??null)},[]),N=(0,y.useCallback)(()=>{g(!1),v(null)},[]),P=(0,y.useCallback)(t=>{let n=t.detail;(n.spool_id===a?.id||n.data?.spool_id===a?.id)&&(u(`success`),f(e(`spoolbuddy.writeTag.writeSuccess`,`Tag written successfully!`)),w(),setTimeout(()=>{u(`idle`),o(null),f(``)},5e3))},[a,e,w]),F=(0,y.useCallback)(t=>{let n=t.detail;(n.spool_id===a?.id||n.data?.spool_id===a?.id)&&(u(`error`),f(n.message??n.data?.message??e(`spoolbuddy.writeTag.writeFailed`,`Write failed`)))},[a,e]);(0,y.useEffect)(()=>(window.addEventListener(`spoolbuddy-unknown-tag`,j),window.addEventListener(`spoolbuddy-tag-matched`,M),window.addEventListener(`spoolbuddy-tag-removed`,N),window.addEventListener(`spoolbuddy-tag-written`,P),window.addEventListener(`spoolbuddy-tag-write-failed`,F),()=>{window.removeEventListener(`spoolbuddy-unknown-tag`,j),window.removeEventListener(`spoolbuddy-tag-matched`,M),window.removeEventListener(`spoolbuddy-tag-removed`,N),window.removeEventListener(`spoolbuddy-tag-written`,P),window.removeEventListener(`spoolbuddy-tag-write-failed`,F)}),[j,M,N,P,F]),(0,y.useEffect)(()=>{o(null),u(`idle`),f(``),c(``)},[r]);let I=async()=>{if(!(!a||!D)){u(`writing`),f(e(`spoolbuddy.writeTag.waiting`,`Waiting for SpoolBuddy...`));try{let e=await ud.writeTag(D.device_id,a.id);if(e?.warnings?.length)for(let n of e.warnings)t(n,`warning`)}catch{u(`error`),f(e(`spoolbuddy.writeTag.queueFailed`,`Failed to queue write command`))}}},L=async()=>{if(D){try{await ud.cancelWrite(D.device_id)}catch{}u(`idle`),f(``)}},R=async()=>{if(!(!a||!B$e(a))){m(!0),u(`idle`),f(``);try{S?await Q.linkTagToSpoolmanSpool(a.id,{tag_uid:``,tray_uuid:``}):await Q.linkTagToSpool(a.id,{tag_uid:``,tray_uuid:``,data_origin:`manual`}),await w(),o(null),u(`success`),f(e(`spoolbuddy.writeTag.untagSuccess`,`Tag removed from spool`)),setTimeout(()=>{u(`idle`),f(``)},2500)}catch{u(`error`),f(e(`spoolbuddy.writeTag.untagFailed`,`Failed to remove tag from spool`))}finally{m(!1)}}},z=(0,y.useCallback)(e=>{o(e),u(`idle`),f(``),w()},[w]),B=a&&O&&l!==`writing`&&l!==`success`;return(0,K.jsxs)(`div`,{className:`flex flex-col h-full`,children:[(0,K.jsx)(`div`,{className:`flex border-b border-bambu-dark-tertiary shrink-0`,children:[{key:`existing`,label:e(`spoolbuddy.writeTag.tabExisting`,`Existing Spool`)},{key:`new`,label:e(`spoolbuddy.writeTag.tabNew`,`New Spool`)},{key:`replace`,label:e(`spoolbuddy.writeTag.tabReplace`,`Replace Tag`)}].map(e=>(0,K.jsx)(`button`,{onClick:()=>i(e.key),className:`flex-1 py-3 text-sm font-medium transition-colors ${r===e.key?`text-bambu-green border-b-2 border-bambu-green bg-bambu-dark`:`text-zinc-400 hover:text-zinc-200 hover:bg-bambu-dark-tertiary`}`,children:e.label},e.key))}),(0,K.jsxs)(`div`,{className:`flex flex-1 overflow-hidden`,children:[(0,K.jsx)(`div`,{className:`flex-1 flex flex-col overflow-hidden border-r border-bambu-dark-tertiary`,children:r===`new`?(0,K.jsx)(H$e,{currencySymbol:k,onCreated:z,selectedSpool:a,spoolmanMode:S,t:e}):(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`div`,{className:`p-3 shrink-0`,children:(0,K.jsx)(`input`,{type:`text`,value:s,onChange:e=>c(e.target.value),placeholder:e(`spoolbuddy.writeTag.searchPlaceholder`,`Search by material, color, brand...`),className:`w-full px-3 py-2 bg-bambu-dark-tertiary border border-bambu-dark-tertiary rounded text-sm text-white placeholder-zinc-500 focus:outline-none focus:border-bambu-green`})}),(0,K.jsx)(`div`,{className:`flex-1 overflow-y-auto px-3 pb-3 space-y-2`,children:A.length===0?(0,K.jsx)(`div`,{className:`text-center text-zinc-500 py-8 text-sm`,children:r===`existing`?e(`spoolbuddy.writeTag.noUntaggedSpools`,`No spools without tags`):e(`spoolbuddy.writeTag.noTaggedSpools`,`No spools with tags`)}):A.map(e=>(0,K.jsx)(V$e,{spool:e,selected:a?.id===e.id,showTag:r===`replace`,onClick:()=>{o(e),u(`idle`),f(``)}},e.id))})]})}),(0,K.jsx)(`div`,{className:`w-[340px] flex flex-col items-center justify-center p-6 shrink-0`,children:(0,K.jsx)(U$e,{writeStatus:l,writeMessage:d,selectedSpool:a,tagOnReader:h,tagUid:_,deviceOnline:O,canWrite:!!B,isReplace:r===`replace`,canUntag:r===`replace`&&!!a&&B$e(a),untagging:p,onWrite:I,onUntag:R,onCancel:L,onRetry:()=>{u(`idle`),f(``)},t:e})})]})]})}function B$e(e){return!!(e.tag_uid||e.tray_uuid)}function V$e({spool:e,selected:t,showTag:n,onClick:r}){let i=Math.max(0,e.label_weight-e.weight_used),a=e.label_weight>0?Math.round(i/e.label_weight*100):0;return(0,K.jsxs)(`button`,{onClick:r,className:`w-full flex items-center gap-3 p-3 rounded-lg text-left transition-colors ${t?`bg-bambu-green/15 border border-bambu-green/50`:`bg-bambu-dark-secondary hover:bg-bambu-dark-tertiary border border-transparent`}`,children:[(0,K.jsx)(`div`,{className:`w-8 h-8 rounded-full shrink-0 border border-white/10`,style:e.rgba?nf(e.rgba):{backgroundColor:`#666`}}),(0,K.jsxs)(`div`,{className:`flex-1 min-w-0`,children:[(0,K.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,K.jsxs)(`span`,{className:`text-sm font-medium text-white truncate`,children:[e.brand?`${e.brand} `:``,e.material,e.subtype?` ${e.subtype}`:``]}),(0,K.jsxs)(`span`,{className:`text-[10px] font-mono text-zinc-500 shrink-0`,children:[`#`,e.id]})]}),(0,K.jsxs)(`div`,{className:`flex items-center gap-2 text-xs text-zinc-400`,children:[e.color_name&&(0,K.jsx)(`span`,{children:e.color_name}),(0,K.jsxs)(`span`,{children:[i,`g / `,e.label_weight,`g (`,a,`%)`]})]}),n&&e.tag_uid&&(0,K.jsx)(`div`,{className:`text-xs text-zinc-500 mt-0.5 font-mono`,children:e.tag_uid})]}),t&&(0,K.jsx)(`svg`,{className:`w-5 h-5 text-bambu-green shrink-0`,fill:`currentColor`,viewBox:`0 0 20 20`,children:(0,K.jsx)(`path`,{fillRule:`evenodd`,d:`M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z`,clipRule:`evenodd`})})]})}function H$e({currencySymbol:e,onCreated:t,selectedSpool:n,spoolmanMode:r,t:i}){let{data:a=[]}=q({queryKey:[r?`spoolman-inventory-spools`:`inventory-spools`,`write-tag-form`],queryFn:()=>r?Q.getSpoolmanInventorySpools(!0):Q.getSpools(!0)}),{data:o}=q({queryKey:[`settings`],queryFn:Q.getSettings}),[s,c]=(0,y.useState)(`simple`),[l,u]=(0,y.useState)(`filament`),[d,f]=(0,y.useState)(x9),[p,m]=(0,y.useState)({}),[h,g]=(0,y.useState)(!1),[_,v]=(0,y.useState)(1),[b,x]=(0,y.useState)(!1),[S,C]=(0,y.useState)(null),[w,T]=(0,y.useState)(!1),[E,D]=(0,y.useState)(!1),[O,k]=(0,y.useState)([]),[A,j]=(0,y.useState)([]),[M,N]=(0,y.useState)([]),[P,F]=(0,y.useState)([]),[I,L]=(0,y.useState)([]),[R,z]=(0,y.useState)(``),[B,V]=(0,y.useState)([]),[ee,te]=(0,y.useState)([]),[ne,re]=(0,y.useState)(new Set),[ie,H]=(0,y.useState)(new Set);(0,y.useEffect)(()=>{V(LU())},[]),(0,y.useEffect)(()=>{let e=!1;return(async()=>{if(s===`full`){D(!0);try{let[t,n]=await Promise.allSettled([(async()=>(await Q.getCloudStatus()).is_authenticated?{connected:!0,presets:await Q.getFilamentPresets()}:{connected:!1,presets:[]})(),(async()=>(await Q.orcaCloudStatus()).connected?{connected:!0,presets:(await Q.orcaCloudListProfiles()).filament}:{connected:!1,presets:[]})()]);if(e)return;let r=t.status===`fulfilled`&&t.value.connected,i=n.status===`fulfilled`&&n.value.connected,a=t.status===`fulfilled`?t.value.presets:[],o=n.status===`fulfilled`?n.value.presets:[];T(r||i),k([...a,...o])}catch{e||T(!1)}finally{e||D(!1)}Q.getSpoolCatalog().then(t=>{e||F(t)}).catch(()=>void 0),Q.getColorCatalog().then(t=>{e||L(t)}).catch(()=>void 0),Q.getLocalPresets().then(t=>{e||j(t.filament)}).catch(()=>void 0),Q.getBuiltinFilaments().then(t=>{e||N(t)}).catch(()=>void 0);try{let t=await Q.getPrinters(),n=await Promise.all(t.map(e=>Q.getPrinterStatus(e.id).catch(()=>null))),r=[];for(let e=0;e({cali_idx:e.slot_id,filament_id:e.filament_id,setting_id:e.setting_id||``,name:e.name,k_value:parseFloat(e.k_value)||0,n_coef:parseFloat(e.n_coef)||0,extruder_id:e.extruder_id,nozzle_diameter:e.nozzle_diameter}))}catch{}r.push({printer:{...i,connected:a},calibrations:o})}e||te(r)}catch{}}})(),()=>{e=!0}},[s]),(0,y.useEffect)(()=>{ee.length>0&&H(new Set(ee.map(e=>String(e.printer.id))))},[ee]);let ae=(0,y.useMemo)(()=>FU(O,new Set,A,M),[O,A,M]),oe=(0,y.useMemo)(()=>IU(d.slicer_filament,ae),[d.slicer_filament,ae]),U=(0,y.useMemo)(()=>{let e=PU(O,A),t=I.map(e=>e.manufacturer?.trim()).filter(e=>!!e);return Array.from(new Set([...e,...t])).sort((e,t)=>e.localeCompare(t))},[O,A,I]),se=(0,y.useMemo)(()=>{let e=I.map(e=>e.material?.trim()).filter(e=>!!e);return Array.from(new Set([...DU,...e])).sort((e,t)=>e.localeCompare(t))},[I]),ce=(0,y.useMemo)(()=>{let e=[];for(let t of I){let n=t.manufacturer?.trim(),r=t.material?.trim();n&&r&&e.push({brand:n,material:r})}for(let t of O){let n=NU(t.name);n.brand&&n.material&&e.push({brand:n.brand,material:n.material})}for(let t of A){let n=NU(t.name),r=t.filament_vendor?.trim()||n.brand,i=n.material;r&&i&&e.push({brand:r,material:i})}return e},[O,I,A]),le=(0,y.useMemo)(()=>{let e=new Map;for(let t of ce){let n=t.brand.toLowerCase(),r=t.material.toLowerCase();e.has(n)||e.set(n,new Set),e.get(n).add(r)}return e},[ce]),ue=(0,y.useMemo)(()=>{let e=new Map;for(let t of ce){let n=t.brand.toLowerCase(),r=t.material.toLowerCase();e.has(r)||e.set(r,new Set),e.get(r).add(n)}return e},[ce]),de=(0,y.useMemo)(()=>{if(!d.material)return U;let e=d.material.toLowerCase(),t=ue.get(e);return!t||t.size===0?U:U.filter(e=>t.has(e.toLowerCase()))},[U,d.material,ue]),fe=(0,y.useMemo)(()=>{if(!d.brand)return se;let e=d.brand.toLowerCase(),t=le.get(e);return!t||t.size===0?se:se.filter(e=>t.has(e.toLowerCase()))},[se,d.brand,le]),pe=(e,t)=>{f(n=>({...n,[e]:t})),p[e]&&m(t=>({...t,[e]:void 0}))},me=e=>{V(t=>RU(e,t))},he=async e=>{let t=r?Q.saveSpoolmanKProfiles:Q.saveSpoolKProfiles;if(ne.size===0){try{await t(e,[])}catch{}return}let n=[];for(let e of ne){let[t,r,i]=e.split(`:`),a=parseInt(t),o=parseInt(r),s=i===`null`?0:parseInt(i),c=ee.find(e=>e.printer.id===a);if(c){let e=c.calibrations.find(e=>e.cali_idx===o);e&&n.push({printer_id:a,extruder:s,nozzle_diameter:e.nozzle_diameter||`0.4`,k_value:e.k_value,name:e.name||null,cali_idx:e.cali_idx,setting_id:e.setting_id||null})}}n.length>0&&await t(e,n)},ge=async()=>{C(null);let e=xZe(d,s===`simple`?!0:h);if(!e.isValid){m(e.errors),u(`filament`);return}let n=oe?.displayName||R||null,a={material:d.material,subtype:d.subtype||null,brand:d.brand||null,color_name:d.color_name||null,rgba:d.rgba||null,extra_colors:d.extra_colors||null,effect_type:d.effect_type||null,label_weight:d.label_weight,core_weight:d.core_weight,core_weight_catalog_id:d.core_weight_catalog_id,weight_used:d.weight_used,slicer_filament:d.slicer_filament||null,slicer_filament_name:n,nozzle_temp_min:null,nozzle_temp_max:null,note:d.note||null,cost_per_kg:d.cost_per_kg,added_full:null,last_used:null,encode_time:null,tag_uid:null,tray_uuid:null,data_origin:null,tag_type:null,last_scale_weight:null,last_weighed_at:null,category:d.category.trim()||null,low_stock_threshold_pct:d.low_stock_threshold_pct};x(!0);try{if(_>1){let e=r?await Q.bulkCreateSpoolmanInventorySpools(a,_):await Q.bulkCreateSpools(a,_),n=r&&e&&typeof e==`object`&&`created`in e?e.created:e;for(let e of n)await he(e.id);n.length>0&&t(n[0])}else{let e=r?await Q.createSpoolmanInventorySpool(a):await Q.createSpool(a);await he(e.id),t(e)}}catch{C(i(`spoolbuddy.writeTag.createFailed`,`Failed to create spool`))}finally{x(!1)}},_e=`#${(d.rgba||`808080FF`).slice(0,6)}`;return(0,K.jsxs)(`div`,{className:`p-3 space-y-3 overflow-y-auto h-full`,children:[(0,K.jsxs)(`div`,{className:`flex items-center justify-between px-2 py-2 bg-bambu-dark-secondary rounded-lg border border-bambu-dark-tertiary`,children:[(0,K.jsx)(`span`,{className:`text-sm text-zinc-200`,children:i(`spoolbuddy.writeTag.viewMode`,`View`)}),(0,K.jsxs)(`div`,{className:`flex rounded-lg overflow-hidden border border-bambu-dark-tertiary`,children:[(0,K.jsx)(`button`,{type:`button`,onClick:()=>c(`simple`),className:`px-3 py-1.5 text-xs font-medium ${s===`simple`?`bg-bambu-green/20 text-bambu-green`:`bg-bambu-dark text-zinc-400`}`,children:i(`spoolbuddy.writeTag.simpleView`,`Simple`)}),(0,K.jsx)(`button`,{type:`button`,onClick:()=>c(`full`),className:`px-3 py-1.5 text-xs font-medium ${s===`full`?`bg-bambu-green/20 text-bambu-green`:`bg-bambu-dark text-zinc-400`}`,children:i(`spoolbuddy.writeTag.fullView`,`Full`)})]})]}),s===`simple`?n?(0,K.jsxs)(`div`,{className:`flex flex-col items-center justify-center h-full p-6 text-center bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg`,children:[(0,K.jsx)(`div`,{className:`w-12 h-12 rounded-full mb-4 border border-white/10`,style:n.rgba?nf(n.rgba):{backgroundColor:`#666`}}),(0,K.jsxs)(`p`,{className:`text-white font-medium`,children:[n.brand?`${n.brand} `:``,n.material]}),n.color_name&&(0,K.jsx)(`p`,{className:`text-zinc-400 text-sm`,children:n.color_name}),(0,K.jsxs)(`p`,{className:`text-zinc-500 text-xs mt-1`,children:[n.label_weight,`g`]}),(0,K.jsx)(`p`,{className:`text-bambu-green text-sm mt-4`,children:i(`spoolbuddy.writeTag.spoolCreated`,`Spool created! Ready to write.`)})]}):(0,K.jsxs)(`div`,{className:`p-4 space-y-4 overflow-y-auto bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg`,children:[(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`label`,{className:`block text-xs text-zinc-400 mb-1`,children:i(`spoolbuddy.writeTag.material`,`Material`)}),(0,K.jsx)(`select`,{value:d.material,onChange:e=>pe(`material`,e.target.value),className:`w-full px-3 py-2 bg-bambu-dark-tertiary border border-bambu-dark-tertiary rounded text-sm text-white focus:outline-none focus:border-bambu-green`,children:R$e.map(e=>(0,K.jsx)(`option`,{value:e,children:e},e))})]}),(0,K.jsxs)(`div`,{className:`flex gap-3`,children:[(0,K.jsxs)(`div`,{className:`flex-1`,children:[(0,K.jsx)(`label`,{className:`block text-xs text-zinc-400 mb-1`,children:i(`spoolbuddy.writeTag.colorName`,`Color Name`)}),(0,K.jsx)(`input`,{type:`text`,value:d.color_name,onChange:e=>pe(`color_name`,e.target.value),placeholder:`Jade White`,className:`w-full px-3 py-2 bg-bambu-dark-tertiary border border-bambu-dark-tertiary rounded text-sm text-white placeholder-zinc-500 focus:outline-none focus:border-bambu-green`})]}),(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`label`,{className:`block text-xs text-zinc-400 mb-1`,children:i(`spoolbuddy.writeTag.color`,`Color`)}),(0,K.jsx)(`input`,{type:`color`,value:_e,onChange:e=>pe(`rgba`,e.target.value.replace(`#`,``).toUpperCase()+`FF`),className:`w-10 h-9 bg-transparent border border-bambu-dark-tertiary rounded cursor-pointer`})]})]}),(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`label`,{className:`block text-xs text-zinc-400 mb-1`,children:i(`spoolbuddy.writeTag.brand`,`Brand`)}),(0,K.jsx)(`input`,{type:`text`,value:d.brand,onChange:e=>pe(`brand`,e.target.value),placeholder:`Polymaker`,className:`w-full px-3 py-2 bg-bambu-dark-tertiary border border-bambu-dark-tertiary rounded text-sm text-white placeholder-zinc-500 focus:outline-none focus:border-bambu-green`})]}),(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`label`,{className:`block text-xs text-zinc-400 mb-1`,children:i(`spoolbuddy.writeTag.weight`,`Weight (g)`)}),(0,K.jsx)(`input`,{type:`number`,value:d.label_weight,onChange:e=>pe(`label_weight`,parseInt(e.target.value)||0),min:0,max:1e4,className:`w-full px-3 py-2 bg-bambu-dark-tertiary border border-bambu-dark-tertiary rounded text-sm text-white focus:outline-none focus:border-bambu-green`})]}),(0,K.jsx)(`button`,{onClick:ge,disabled:b||!d.material,className:`w-full py-2.5 bg-bambu-green hover:bg-bambu-green/80 disabled:opacity-50 disabled:cursor-not-allowed text-white text-sm font-medium rounded transition-colors`,children:b?i(`spoolbuddy.writeTag.creating`,`Creating...`):i(`spoolbuddy.writeTag.createSpool`,`Create Spool`)})]}):(0,K.jsxs)(K.Fragment,{children:[(0,K.jsxs)(`div`,{className:`flex items-center justify-between px-2 py-2 bg-bambu-dark-secondary rounded-lg border border-bambu-dark-tertiary`,children:[(0,K.jsx)(`span`,{className:`text-sm text-zinc-200`,children:i(`inventory.quickAdd`,`Quick Add`)}),(0,K.jsx)(`button`,{type:`button`,onClick:()=>g(e=>!e),className:`relative inline-flex h-6 w-11 items-center rounded-full transition-colors ${h?`bg-bambu-green`:`bg-bambu-dark-tertiary`}`,children:(0,K.jsx)(`span`,{className:`inline-block h-4.5 w-4.5 rounded-full bg-white transition-transform ${h?`translate-x-6`:`translate-x-1`}`})})]}),(0,K.jsxs)(`div`,{className:`flex border border-bambu-dark-tertiary rounded-lg overflow-hidden`,children:[(0,K.jsx)(`button`,{onClick:()=>u(`filament`),className:`flex-1 py-2.5 text-sm font-medium ${l===`filament`?`bg-bambu-green/15 text-bambu-green`:`bg-bambu-dark-secondary text-zinc-400`}`,children:i(`inventory.filamentInfoTab`,`Filament`)}),!h&&(0,K.jsx)(`button`,{onClick:()=>u(`pa-profile`),className:`flex-1 py-2.5 text-sm font-medium ${l===`pa-profile`?`bg-bambu-green/15 text-bambu-green`:`bg-bambu-dark-secondary text-zinc-400`}`,children:i(`inventory.paProfileTab`,`PA Profile`)})]}),(0,K.jsx)(`div`,{className:`bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg p-3`,children:l===`filament`?(0,K.jsxs)(`div`,{className:`space-y-4`,children:[(0,K.jsx)(SZe,{formData:d,updateField:pe,cloudAuthenticated:w,loadingCloudPresets:E,presetInputValue:R,setPresetInputValue:z,selectedPresetOption:oe,filamentOptions:ae,availableBrands:de,availableMaterials:fe,quickAdd:h,quantity:_,onQuantityChange:v,errors:p}),(0,K.jsx)(wZe,{formData:d,updateField:pe,recentColors:B,onColorUsed:me,catalogColors:I}),(0,K.jsx)(EZe,{formData:d,updateField:pe,spoolCatalog:P,currencySymbol:e,availableCategories:Array.from(new Set(a.map(e=>e.category?.trim()).filter(e=>!!e))).sort((e,t)=>e.localeCompare(t)),globalLowStockThreshold:o?.low_stock_threshold??20})]}):(0,K.jsx)(OZe,{formData:d,updateField:pe,printersWithCalibrations:ee,selectedProfiles:ne,setSelectedProfiles:re,expandedPrinters:ie,setExpandedPrinters:H})})]}),S&&(0,K.jsx)(`div`,{className:`text-sm text-red-400 bg-red-900/20 border border-red-900/40 rounded-lg px-3 py-2`,children:S}),s===`full`&&(0,K.jsx)(`button`,{onClick:ge,disabled:b,className:`w-full py-3 bg-bambu-green hover:bg-bambu-green/80 disabled:opacity-50 disabled:cursor-not-allowed text-white text-sm font-medium rounded transition-colors`,children:b?i(`spoolbuddy.writeTag.creating`,`Creating...`):i(`spoolbuddy.writeTag.createSpool`,`Create Spool`)}),s===`full`&&n&&(0,K.jsxs)(`div`,{className:`flex flex-col items-center justify-center p-4 text-center bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg`,children:[(0,K.jsx)(`div`,{className:`w-12 h-12 rounded-full mb-4 border border-white/10`,style:n.rgba?nf(n.rgba):{backgroundColor:`#666`}}),(0,K.jsxs)(`p`,{className:`text-white font-medium`,children:[n.brand?`${n.brand} `:``,n.material]}),n.color_name&&(0,K.jsx)(`p`,{className:`text-zinc-400 text-sm`,children:n.color_name}),(0,K.jsxs)(`p`,{className:`text-zinc-500 text-xs mt-1`,children:[n.label_weight,`g`]}),(0,K.jsx)(`p`,{className:`text-bambu-green text-sm mt-4`,children:i(`spoolbuddy.writeTag.spoolCreated`,`Spool created! Ready to write.`)})]})]})}function U$e({writeStatus:e,writeMessage:t,selectedSpool:n,tagOnReader:r,tagUid:i,deviceOnline:a,canWrite:o,isReplace:s,canUntag:c,untagging:l,onWrite:u,onUntag:d,onCancel:f,onRetry:p,t:m}){if(e===`success`)return(0,K.jsxs)(`div`,{className:`flex flex-col items-center text-center space-y-4`,children:[(0,K.jsx)(`div`,{className:`w-16 h-16 rounded-full bg-green-500/20 flex items-center justify-center`,children:(0,K.jsx)(`svg`,{className:`w-8 h-8 text-green-400`,fill:`none`,viewBox:`0 0 24 24`,stroke:`currentColor`,children:(0,K.jsx)(`path`,{strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:2,d:`M5 13l4 4L19 7`})})}),(0,K.jsx)(`p`,{className:`text-green-400 font-medium`,children:t}),n&&(0,K.jsxs)(`p`,{className:`text-zinc-400 text-sm`,children:[n.brand?`${n.brand} `:``,n.material,n.color_name?` - ${n.color_name}`:``]})]});if(e===`error`)return(0,K.jsxs)(`div`,{className:`flex flex-col items-center text-center space-y-4`,children:[(0,K.jsx)(`div`,{className:`w-16 h-16 rounded-full bg-red-500/20 flex items-center justify-center`,children:(0,K.jsx)(`svg`,{className:`w-8 h-8 text-red-400`,fill:`none`,viewBox:`0 0 24 24`,stroke:`currentColor`,children:(0,K.jsx)(`path`,{strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:2,d:`M6 18L18 6M6 6l12 12`})})}),(0,K.jsx)(`p`,{className:`text-red-400 font-medium`,children:t}),(0,K.jsx)(`button`,{onClick:p,className:`px-4 py-2 bg-bambu-dark-tertiary hover:bg-bambu-dark-secondary text-white text-sm rounded transition-colors`,children:m(`spoolbuddy.writeTag.tryAgain`,`Try Again`)})]});if(e===`writing`)return(0,K.jsxs)(`div`,{className:`flex flex-col items-center text-center space-y-4`,children:[(0,K.jsxs)(`div`,{className:`relative w-16 h-16`,children:[(0,K.jsx)(`div`,{className:`absolute inset-0 rounded-full border-2 border-bambu-green/30 animate-ping`}),(0,K.jsx)(`div`,{className:`absolute inset-2 rounded-full border-2 border-bambu-green/50 animate-pulse`}),(0,K.jsx)(`div`,{className:`absolute inset-0 flex items-center justify-center`,children:(0,K.jsx)(Z9,{className:`w-8 h-8 text-bambu-green`})})]}),(0,K.jsx)(`p`,{className:`text-bambu-green font-medium`,children:m(`spoolbuddy.writeTag.writing`,`Writing tag...`)}),(0,K.jsx)(`p`,{className:`text-zinc-500 text-xs`,children:t}),(0,K.jsx)(`button`,{onClick:f,className:`px-4 py-2 bg-bambu-dark-tertiary hover:bg-bambu-dark-secondary text-zinc-400 text-sm rounded transition-colors`,children:m(`spoolbuddy.writeTag.cancel`,`Cancel`)})]});if(!a)return(0,K.jsxs)(`div`,{className:`flex flex-col items-center text-center space-y-3`,children:[(0,K.jsx)(Z9,{className:`w-12 h-12 text-zinc-600`}),(0,K.jsx)(`p`,{className:`text-zinc-500 text-sm`,children:m(`spoolbuddy.writeTag.deviceOffline`,`SpoolBuddy is offline`)})]});if(!n)return(0,K.jsxs)(`div`,{className:`flex flex-col items-center text-center space-y-3`,children:[(0,K.jsx)(Z9,{className:`w-12 h-12 text-zinc-600`}),(0,K.jsx)(`p`,{className:`text-zinc-400 text-sm`,children:m(`spoolbuddy.writeTag.selectSpool`,`Select a spool, then place a blank NTAG on the reader`)})]});let h=n.rgba?nf(n.rgba):{backgroundColor:`#666`};return(0,K.jsxs)(`div`,{className:`flex flex-col items-center text-center space-y-4 w-full`,children:[(0,K.jsx)(`div`,{className:`relative w-16 h-16`,children:r?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`div`,{className:`absolute inset-0 rounded-full bg-bambu-green/10`}),(0,K.jsx)(`div`,{className:`absolute inset-0 flex items-center justify-center`,children:(0,K.jsx)(Z9,{className:`w-8 h-8 text-bambu-green`})})]}):(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`div`,{className:`absolute inset-0 rounded-full border-2 border-zinc-600 animate-pulse`}),(0,K.jsx)(`div`,{className:`absolute inset-0 flex items-center justify-center`,children:(0,K.jsx)(Z9,{className:`w-8 h-8 text-zinc-500`})})]})}),r?(0,K.jsxs)(`div`,{className:`space-y-1`,children:[(0,K.jsx)(`p`,{className:`text-bambu-green text-sm font-medium`,children:m(`spoolbuddy.writeTag.tagReady`,`Tag detected — ready to write`)}),i&&(0,K.jsx)(`p`,{className:`text-zinc-500 text-xs font-mono`,children:i})]}):(0,K.jsx)(`p`,{className:`text-zinc-400 text-sm`,children:m(`spoolbuddy.writeTag.placeTag`,`Place an NTAG on the reader`)}),(0,K.jsxs)(`div`,{className:`w-full bg-bambu-dark-secondary rounded-lg p-3 space-y-2`,children:[(0,K.jsxs)(`div`,{className:`flex items-center gap-3`,children:[(0,K.jsx)(`div`,{className:`w-8 h-8 rounded-full border border-white/10 shrink-0`,style:h}),(0,K.jsxs)(`div`,{className:`text-left min-w-0`,children:[(0,K.jsxs)(`p`,{className:`text-white text-sm font-medium truncate`,children:[n.brand?`${n.brand} `:``,n.material]}),n.color_name&&(0,K.jsx)(`p`,{className:`text-zinc-400 text-xs`,children:n.color_name})]})]}),(0,K.jsxs)(`div`,{className:`text-xs text-zinc-500`,children:[n.label_weight,`g`]})]}),s&&n.tag_uid&&(0,K.jsx)(`p`,{className:`text-yellow-500/80 text-xs`,children:m(`spoolbuddy.writeTag.replaceWarning`,`Old tag will be unlinked. New tag will replace it.`)}),(0,K.jsx)(`button`,{onClick:u,disabled:!o,className:`w-full py-3 bg-bambu-green hover:bg-bambu-green/80 disabled:opacity-40 disabled:cursor-not-allowed text-white font-medium rounded-lg transition-colors text-sm`,children:s?m(`spoolbuddy.writeTag.replaceTag`,`Replace Tag`):m(`spoolbuddy.writeTag.writeTag`,`Write Tag`)}),s&&c&&(0,K.jsx)(`button`,{onClick:d,disabled:l,className:`w-full py-2.5 bg-bambu-dark-tertiary hover:bg-bambu-dark-secondary disabled:opacity-40 disabled:cursor-not-allowed text-zinc-200 rounded-lg transition-colors text-sm`,children:l?m(`spoolbuddy.writeTag.untagging`,`Removing tag...`):m(`spoolbuddy.writeTag.untagSpool`,`Untag Selected Spool`)})]})}function Z9({className:e}){return(0,K.jsxs)(`svg`,{className:e,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:1.5,children:[(0,K.jsx)(`path`,{strokeLinecap:`round`,strokeLinejoin:`round`,d:`M8.288 15.038a5.25 5.25 0 017.424 0M5.106 11.856c3.807-3.808 9.98-3.808 13.788 0M1.924 8.674c5.565-5.565 14.587-5.565 20.152 0`}),(0,K.jsx)(`path`,{strokeLinecap:`round`,strokeLinejoin:`round`,d:`M12.53 18.22l-.53.53-.53-.53a.75.75 0 011.06 0z`})]})}var W$e=`spoolbuddy-default-core-weight`;function G$e(){try{let e=localStorage.getItem(W$e);if(e){let t=parseInt(e,10);if(t>=0&&t<=500)return t}}catch{}return 250}function K$e({spool:e,liveScaleWeight:t,persistedGrossWeight:n,onClose:r,onSyncWeight:i,onAssignToAms:a,isAssigned:o,onUnassignFromAms:s,className:c}){let{t:l}=W(),[u,d]=(0,y.useState)(!1),[f,p]=(0,y.useState)(!1),[m,h]=(0,y.useState)(null),{data:g}=q({queryKey:[`spool-k-profiles`,e.id],queryFn:()=>Q.getSpoolKProfiles(e.id),enabled:!e.k_profiles||e.k_profiles.length===0,staleTime:300*1e3}),_=e.k_profiles&&e.k_profiles.length>0?e.k_profiles:g,v=tf(e.rgba),b=e.core_weight&&e.core_weight>0?e.core_weight:G$e(),x=t===null?null:Math.round(Math.max(0,t)),S=m??(n===void 0?x:n===null?null:Math.round(Math.max(0,n))),C=Math.round(Math.max(0,(e.label_weight||0)-(e.weight_used||0))),w=x!==null&&x>=10?Math.round(Math.max(0,x-b)):C,T=Math.round(e.label_weight||1e3),E=T>0?Math.min(100,Math.round(w/T*100)):null,D=E===null?`#808080`:E>50?`#22c55e`:E>20?`#eab308`:`#ef4444`,O=Math.max(0,(e.label_weight||0)-(e.weight_used||0))+b,k=x===null?null:x-O,A=k===null?null:Math.abs(k)<=50,j=S??Math.round(O),M=e.nozzle_temp_min!=null&&e.nozzle_temp_max!=null?`${e.nozzle_temp_min}-${e.nozzle_temp_max}\u00B0C`:null,N=e.slicer_filament_name||e.slicer_filament||null,P=e.note?.trim()||null,F=_&&_.length>0?Array.from(new Set(_.map(e=>e.k_value.toFixed(3)))).join(`, `):null,I=async()=>{if(t===null)return;let n=Math.round(Math.max(0,t));d(!0);try{await ud.updateSpoolWeight(e.id,n),h(n),p(!0),i?.(),setTimeout(()=>p(!1),3e3)}catch(e){console.error(`Failed to sync weight:`,e)}finally{d(!1)}};return(0,K.jsxs)(`div`,{className:`flex flex-col items-center space-y-4 max-w-md ${c??``}`,children:[(0,K.jsxs)(`div`,{className:`flex items-start gap-5`,children:[(0,K.jsxs)(`div`,{className:`relative shrink-0`,children:[(0,K.jsx)(G9,{color:v,isEmpty:!1,size:100}),E!==null&&(0,K.jsxs)(`div`,{className:`absolute -bottom-2 -right-2 px-2 py-0.5 rounded-full text-xs font-bold text-white shadow-lg`,style:{backgroundColor:D},children:[E,`%`]})]}),(0,K.jsxs)(`div`,{className:`flex-1 min-w-0 pt-1`,children:[(0,K.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,K.jsx)(`h3`,{className:`text-lg font-semibold text-zinc-100`,children:e.color_name||`Unknown color`}),(0,K.jsxs)(`span`,{className:`text-xs font-mono text-zinc-500 shrink-0`,children:[`#`,e.id]})]}),(0,K.jsxs)(`p`,{className:`text-sm text-zinc-400`,children:[e.brand,` • `,e.material,e.subtype&&` ${e.subtype}`]}),(0,K.jsxs)(`div`,{className:`mt-3`,children:[(0,K.jsxs)(`div`,{className:`flex items-baseline gap-2`,children:[(0,K.jsxs)(`span`,{className:`text-3xl font-bold font-mono text-zinc-100`,children:[w,`g`]}),(0,K.jsxs)(`span`,{className:`text-sm text-zinc-500`,children:[`/ `,T,`g`]})]}),(0,K.jsx)(`p`,{className:`text-xs text-zinc-500 mt-0.5`,children:l(`spoolbuddy.spool.remaining`,`Remaining`)}),(0,K.jsx)(`div`,{className:`mt-2 max-w-xs`,children:(0,K.jsx)(`div`,{className:`h-2 bg-zinc-700 rounded-full overflow-hidden`,children:(0,K.jsx)(`div`,{className:`h-full rounded-full transition-all duration-500`,style:{width:`${E??0}%`,backgroundColor:D}})})})]})]})]}),(0,K.jsxs)(`div`,{className:`grid grid-cols-2 gap-x-6 gap-y-2 text-sm bg-zinc-800 rounded-lg p-4 w-full`,children:[(0,K.jsxs)(`div`,{className:`flex justify-between`,children:[(0,K.jsx)(`span`,{className:`text-zinc-500`,children:l(`spoolbuddy.dashboard.grossWeight`,`Gross weight`)}),(0,K.jsxs)(`span`,{className:`font-mono text-zinc-300`,children:[j,`g`]})]}),(0,K.jsxs)(`div`,{className:`flex justify-between`,children:[(0,K.jsx)(`span`,{className:`text-zinc-500`,children:l(`spoolbuddy.spool.coreWeight`,`Core`)}),(0,K.jsxs)(`span`,{className:`font-mono text-zinc-300`,children:[b,`g`]})]}),(0,K.jsxs)(`div`,{className:`flex justify-between`,children:[(0,K.jsx)(`span`,{className:`text-zinc-500`,children:l(`spoolbuddy.dashboard.spoolSize`,`Spool size`)}),(0,K.jsxs)(`span`,{className:`font-mono text-zinc-300`,children:[T,`g`]})]}),(0,K.jsxs)(`div`,{className:`flex justify-between items-center`,children:[(0,K.jsx)(`span`,{className:`text-zinc-500`,children:l(`spoolbuddy.spool.scaleWeight`,`Scale`)}),x===null?(0,K.jsx)(`span`,{className:`text-zinc-500`,children:`—`}):(0,K.jsxs)(`span`,{className:`flex items-center gap-1 font-mono ${A?`text-green-500`:`text-yellow-500`}`,children:[x,`g`,A?(0,K.jsx)(ts,{className:`w-3.5 h-3.5`}):(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(wu,{className:`w-3.5 h-3.5`}),(0,K.jsx)(`button`,{onClick:I,className:`p-1 hover:bg-green-500/20 rounded transition-colors text-green-500`,title:l(`spoolbuddy.dashboard.syncWeight`,`Sync Weight`),children:(0,K.jsx)(kl,{className:`w-4 h-4`})})]})]})]}),(0,K.jsxs)(`div`,{className:`flex justify-between items-center`,children:[(0,K.jsx)(`span`,{className:`text-zinc-500`,children:l(`spoolbuddy.dashboard.tagId`,`Tag`)}),(0,K.jsx)(`span`,{className:`font-mono text-xs text-zinc-400 truncate max-w-[120px]`,title:e.tag_uid||``,children:e.tag_uid?e.tag_uid.slice(-8):`—`})]}),M&&(0,K.jsxs)(`div`,{className:`flex justify-between items-center`,children:[(0,K.jsx)(`span`,{className:`text-zinc-500`,children:l(`spoolbuddy.inventory.nozzleTemp`,`Nozzle`)}),(0,K.jsx)(`span`,{className:`font-mono text-zinc-300`,children:M})]}),e.cost_per_kg!=null&&e.cost_per_kg>0&&(0,K.jsxs)(`div`,{className:`flex justify-between items-center`,children:[(0,K.jsx)(`span`,{className:`text-zinc-500`,children:l(`spoolbuddy.inventory.costPerKg`,`Cost/kg`)}),(0,K.jsxs)(`span`,{className:`font-mono text-zinc-300`,children:[e.cost_per_kg.toFixed(2),`/kg`]})]}),F&&(0,K.jsxs)(`div`,{className:`flex justify-between items-center`,children:[(0,K.jsx)(`span`,{className:`text-zinc-500`,children:l(`spoolbuddy.inventory.kProfiles`,`K-Profile`)}),(0,K.jsx)(`span`,{className:`font-mono text-zinc-300 truncate max-w-[220px] text-right`,title:F,children:F})]}),N&&(0,K.jsxs)(`div`,{className:`min-w-0`,children:[(0,K.jsx)(`p`,{className:`text-xs text-zinc-500 mb-1`,children:l(`spoolbuddy.inventory.slicerFilament`,`Slicer Filament`)}),(0,K.jsx)(`p`,{className:`text-sm text-zinc-300 whitespace-pre-wrap break-words`,children:N})]}),P&&(0,K.jsxs)(`div`,{className:`col-span-2`,children:[(0,K.jsx)(`p`,{className:`text-xs text-zinc-500 mb-1`,children:l(`spoolbuddy.inventory.note`,`Note`)}),(0,K.jsx)(`p`,{className:`text-sm leading-5 text-zinc-300 whitespace-pre-wrap break-words max-h-[3.75rem] overflow-y-auto pr-1`,children:P})]})]}),(0,K.jsxs)(`div`,{className:`flex gap-2 justify-center`,children:[a&&(0,K.jsx)(`button`,{onClick:o?void 0:a,disabled:!!o,className:`px-5 py-2.5 rounded-lg text-sm font-medium bg-green-600 text-white hover:bg-green-700 transition-colors min-h-[44px] disabled:opacity-50 disabled:cursor-not-allowed`,children:l(`spoolbuddy.modal.assignToAms`,`Assign to AMS`)}),s&&(0,K.jsxs)(`button`,{onClick:s,className:`px-5 py-2.5 rounded-lg text-sm font-medium bg-red-600/20 text-red-400 hover:bg-red-600/30 transition-colors min-h-[44px]`,children:[(0,K.jsx)(Du,{className:`w-4 h-4 inline mr-1`}),l(`inventory.unassignSpool`)]}),(0,K.jsx)(`button`,{onClick:I,disabled:t===null||u,className:`px-5 py-2.5 rounded-lg text-sm font-medium transition-colors min-h-[44px] ${f?`bg-green-600/20 text-green-400`:a?`bg-zinc-700 text-zinc-300 hover:bg-zinc-600 disabled:opacity-40 disabled:cursor-not-allowed`:`bg-green-600 text-white hover:bg-green-700 disabled:opacity-40 disabled:cursor-not-allowed`}`,children:u?`...`:f?l(`spoolbuddy.dashboard.weightSynced`,`Synced!`):l(`spoolbuddy.dashboard.syncWeight`,`Sync Weight`)}),r&&(0,K.jsx)(`button`,{onClick:r,className:`px-5 py-2.5 rounded-lg text-sm font-medium bg-zinc-700 text-zinc-300 hover:bg-zinc-600 transition-colors min-h-[44px]`,children:l(`spoolbuddy.dashboard.close`,`Close`)})]})]})}function q$e(e){return tf(e.rgba)}function J$e(e){return Math.max(0,e.label_weight-e.weight_used)}function Y$e(e){return e.label_weight<=0?0:Math.max(0,Math.min(100,(e.label_weight-e.weight_used)/e.label_weight*100))}function X$e(e){let t=[e.material];return e.subtype&&t.push(e.subtype),t.join(` `)}function Z$e(e){let t=e.ams_id===254||e.ams_id===255,n=!t&&e.ams_id>=128;return Wf(e.ams_id,e.tray_id,n,t)}function Q$e({color:e,size:t=56}){return(0,K.jsxs)(`svg`,{width:t,height:t,viewBox:`0 0 56 56`,children:[(0,K.jsx)(`circle`,{cx:`28`,cy:`28`,r:`26`,fill:e}),(0,K.jsx)(`circle`,{cx:`28`,cy:`28`,r:`20`,fill:e,style:{filter:`brightness(0.85)`}}),(0,K.jsx)(`ellipse`,{cx:`20`,cy:`20`,rx:`6`,ry:`4`,fill:`white`,opacity:`0.3`}),(0,K.jsx)(`circle`,{cx:`28`,cy:`28`,r:`8`,fill:`#2d2d2d`}),(0,K.jsx)(`circle`,{cx:`28`,cy:`28`,r:`5`,fill:`#1a1a1a`})]})}function $$e(){let{sbState:e,selectedPrinterId:t}=nr(),{t:n}=W(),{showToast:r}=kd(),i=to(),[a,o]=(0,y.useState)(``),[s,c]=(0,y.useState)(`all`),[l,u]=(0,y.useState)(null),[d,f]=(0,y.useState)(!1),{data:p}=q({queryKey:[`spoolman-settings`],queryFn:Q.getSpoolmanSettings,staleTime:300*1e3}),m=p?.spoolman_enabled===`true`&&!!p?.spoolman_url,{data:h=[],isLoading:g,refetch:_}=q({queryKey:m?[`spoolman-inventory-spools`]:[`inventory-spools`],queryFn:()=>m?Q.getSpoolmanInventorySpools(!1):Q.getSpools(!1),enabled:p!==void 0,refetchInterval:3e4}),{data:v=[]}=q({queryKey:[`spool-assignments`],queryFn:()=>Q.getAssignments(),refetchInterval:3e4,enabled:!m}),{data:b=[]}=q({queryKey:[`spoolman-slot-assignments`],queryFn:()=>Q.getSpoolmanSlotAssignments(),refetchInterval:3e4,enabled:m}),x=J({mutationFn:e=>Q.unassignSpoolmanSlot(e),onSuccess:()=>{i.invalidateQueries({queryKey:[`spoolman-slot-assignments`]}),i.invalidateQueries({queryKey:[`spoolman-inventory-spools`]})},onError:()=>r(n(`inventory.unassignFailed`,`Failed to unassign spool`),`error`)}),S=(0,y.useMemo)(()=>{if(m){let e={};return b.forEach(t=>{e[t.spoolman_spool_id]={ams_id:t.ams_id,tray_id:t.tray_id}}),e}let e={};return v.forEach(t=>{e[t.spool_id]={ams_id:t.ams_id,tray_id:t.tray_id,printer_name:t.printer_name}}),e},[m,v,b]),C=(0,y.useMemo)(()=>h.filter(e=>!e.archived_at),[h]),w=(0,y.useMemo)(()=>new Set(Object.keys(S).map(Number)),[S]),T=(0,y.useMemo)(()=>C.filter(e=>w.has(e.id)).length,[C,w]),E=(0,y.useMemo)(()=>{let e=new Set;return C.forEach(t=>e.add(t.material)),Array.from(e).sort()},[C]),D=(0,y.useMemo)(()=>{let e=C;return s===`in_ams`?e=e.filter(e=>w.has(e.id)):s!==`all`&&(e=e.filter(e=>e.material===s)),e=yU(e,a.trim()),[...e].sort((e,t)=>{let n=+!w.has(e.id),r=+!w.has(t.id);return n===r?new Date(t.updated_at).getTime()-new Date(e.updated_at).getTime():n-r})},[C,s,a,w]);return(0,K.jsxs)(`div`,{className:`h-full flex flex-col`,children:[(0,K.jsxs)(`div`,{className:`px-3 pt-3 pb-2 space-y-2.5`,children:[(0,K.jsxs)(`div`,{className:`relative`,children:[(0,K.jsx)(zl,{className:`absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-white/40`}),(0,K.jsx)(`input`,{type:`text`,value:a,onChange:e=>o(e.target.value),placeholder:n(`spoolbuddy.inventory.searchPlaceholder`,`Search spools...`),className:`w-full pl-9 pr-8 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-sm text-white placeholder-white/30 focus:outline-none focus:border-bambu-green`}),a&&(0,K.jsx)(`button`,{onClick:()=>o(``),className:`absolute right-2 top-1/2 -translate-y-1/2 text-white/40 hover:text-white/60`,children:(0,K.jsx)(Hu,{className:`w-4 h-4`})})]}),(0,K.jsxs)(`div`,{className:`flex gap-1.5 overflow-x-auto no-scrollbar`,children:[(0,K.jsx)(Q9,{active:s===`all`,onClick:()=>c(`all`),label:`${n(`spoolbuddy.inventory.all`,`All`)} (${C.length})`,green:!0}),T>0&&(0,K.jsx)(Q9,{active:s===`in_ams`,onClick:()=>c(`in_ams`),label:`${n(`spoolbuddy.inventory.inAms`,`In AMS`)} (${T})`}),E.map(e=>(0,K.jsx)(Q9,{active:s===e,onClick:()=>c(s===e?`all`:e),label:e},e))]})]}),(0,K.jsx)(`div`,{className:`flex-1 overflow-y-auto px-3 pb-3`,children:g?(0,K.jsx)(`div`,{className:`flex items-center justify-center py-16`,children:(0,K.jsx)(`div`,{className:`w-8 h-8 border-2 border-bambu-green border-t-transparent rounded-full animate-spin`})}):D.length===0?(0,K.jsxs)(`div`,{className:`flex flex-col items-center justify-center py-16 text-white/30`,children:[(0,K.jsx)(fl,{className:`w-12 h-12 mb-3`}),(0,K.jsx)(`p`,{className:`text-sm`,children:a||s!==`all`?n(`spoolbuddy.inventory.noResults`,`No spools match your filters`):n(`spoolbuddy.inventory.empty`,`No spools in inventory`)})]}):(0,K.jsx)(`div`,{className:`grid grid-cols-[repeat(auto-fill,minmax(130px,1fr))] gap-2`,children:D.map(e=>(0,K.jsx)(e1e,{spool:e,assignment:S[e.id],onClick:()=>u(e.id)},e.id))})}),l!=null&&(()=>{let n=h.find(e=>e.id===l);return n?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(t1e,{spool:n,assignment:S[n.id],sbState:e,onSyncWeight:()=>{_()},onAssignToAms:()=>f(!0),onUnassignFromAms:m&&S[n.id]?()=>x.mutate(n.id):void 0,onClose:()=>{u(null),f(!1)}}),(0,K.jsx)(d$e,{isOpen:d,onClose:()=>f(!1),spool:n,printerId:t,spoolmanMode:m})]}):null})()]})}function Q9({active:e,onClick:t,label:n,green:r}){return(0,K.jsx)(`button`,{onClick:t,className:`px-4 py-1.5 rounded-full text-sm font-medium border whitespace-nowrap shrink-0 transition-colors ${e?r?`bg-bambu-green/20 text-bambu-green border-bambu-green/50`:`bg-white/10 text-white border-white/20`:`bg-transparent text-white/40 border-bambu-dark-tertiary hover:text-white/60`}`,children:n})}function e1e({spool:e,assignment:t,onClick:n}){let r=q$e(e),i=Y$e(e),a=J$e(e),o=ef(e.color_name,e.rgba);return(0,K.jsxs)(`button`,{onClick:n,className:`bg-bambu-dark-secondary rounded-xl p-3 flex flex-col items-center text-center gap-1.5 border border-transparent hover:border-bambu-green/50 transition-colors`,children:[(0,K.jsx)(Q$e,{color:r,size:56}),(0,K.jsx)(`p`,{className:`text-xs font-semibold text-white leading-tight truncate w-full`,children:X$e(e)}),(0,K.jsxs)(`div`,{className:`flex items-center gap-1 min-w-0 max-w-full`,children:[(0,K.jsx)(`span`,{className:`w-2.5 h-2.5 rounded-full shrink-0 border border-white/10`,style:nf(e.rgba)}),(0,K.jsx)(`span`,{className:`text-[11px] text-white/50 truncate`,children:o||`-`})]}),(0,K.jsxs)(`div`,{className:`w-full space-y-0.5`,children:[(0,K.jsx)(`div`,{className:`h-1.5 bg-bambu-dark-tertiary rounded-full overflow-hidden`,children:(0,K.jsx)(`div`,{className:`h-full rounded-full ${i>50?`bg-bambu-green`:i>20?`bg-yellow-500`:`bg-red-500`}`,style:{width:`${Math.min(i,100)}%`}})}),(0,K.jsxs)(`p`,{className:`text-[11px] text-white/40`,children:[Math.round(a),`g (`,Math.round(i),`%)`]})]}),t&&(0,K.jsx)(`span`,{className:`px-2 py-0.5 rounded text-[10px] font-bold bg-bambu-green/20 text-bambu-green`,children:Z$e(t)})]})}function t1e({spool:e,assignment:t,sbState:n,onSyncWeight:r,onAssignToAms:i,onUnassignFromAms:a,onClose:o}){let s=n.deviceOnline&&n.weight!==null?Math.round(n.weight):null,c=e.last_scale_weight==null?null:Math.round(e.last_scale_weight);return(0,K.jsx)(`div`,{className:`fixed inset-0 z-50 bg-black/70 flex items-center justify-center p-4`,onClick:o,children:(0,K.jsx)(`div`,{className:`w-full max-w-md bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-2xl p-4 overflow-y-auto max-h-[90vh]`,onClick:e=>e.stopPropagation(),children:(0,K.jsxs)(`div`,{className:`space-y-3`,children:[t&&(0,K.jsxs)(`div`,{className:`flex items-center justify-center gap-2`,children:[(0,K.jsx)(`span`,{className:`px-2.5 py-1 rounded-md text-xs font-bold bg-bambu-green/20 text-bambu-green`,children:Z$e(t)}),t.printer_name&&(0,K.jsx)(`span`,{className:`text-xs text-zinc-400`,children:t.printer_name})]}),(0,K.jsx)(`div`,{className:`flex justify-center`,children:(0,K.jsx)(K$e,{spool:e,liveScaleWeight:s,persistedGrossWeight:c,onSyncWeight:r,onAssignToAms:i,isAssigned:!!t,onUnassignFromAms:a,onClose:o,className:`max-w-md`})})]})})})}var n1e=class extends y.Component{state={error:null,errorInfo:null};static getDerivedStateFromError(e){return{error:e}}componentDidCatch(e,t){this.setState({errorInfo:t}),console.error(`React crash:`,e,t)}render(){return this.state.error?(0,K.jsxs)(`div`,{style:{padding:24,color:`#ef4444`,backgroundColor:`#18181b`,minHeight:`100vh`,fontFamily:`monospace`},children:[(0,K.jsx)(`h1`,{style:{fontSize:20,marginBottom:12},children:`UI Crash`}),(0,K.jsx)(`pre`,{style:{whiteSpace:`pre-wrap`,fontSize:14},children:this.state.error.message}),(0,K.jsx)(`pre`,{style:{whiteSpace:`pre-wrap`,fontSize:12,color:`#a1a1aa`,marginTop:12},children:this.state.error.stack}),(0,K.jsx)(`button`,{onClick:()=>{this.setState({error:null,errorInfo:null})},style:{marginTop:16,padding:`8px 16px`,backgroundColor:`#3b82f6`,color:`#fff`,border:`none`,borderRadius:8,cursor:`pointer`},children:`Retry`})]}):this.props.children}},r1e=new Qa({defaultOptions:{queries:{staleTime:1e3*60,retry:1}}});function i1e(){return f9(),null}function a1e({children:e}){return AQe(),(0,K.jsx)(K.Fragment,{children:e})}function o1e({children:e}){let{authEnabled:t,loading:n,user:r}=hd(),i=Xn();return n?(0,K.jsx)(`div`,{className:`min-h-screen flex items-center justify-center`,children:`Loading...`}):t&&!r?(0,K.jsx)(Or,{to:`/login`,replace:!0,state:{from:i}}):(0,K.jsx)(K.Fragment,{children:e})}function $9({permission:e,children:t}){let{authEnabled:n,loading:r,user:i,hasPermission:a}=hd(),o=Xn();return r?(0,K.jsx)(`div`,{className:`min-h-screen flex items-center justify-center`,children:`Loading...`}):n?i?a(e)?(0,K.jsx)(K.Fragment,{children:t}):(0,K.jsx)(Or,{to:`/`,replace:!0}):(0,K.jsx)(Or,{to:`/login`,replace:!0,state:{from:o}}):(0,K.jsx)(K.Fragment,{children:t})}function s1e({children:e}){let{authEnabled:t,loading:n}=hd();return n?(0,K.jsx)(`div`,{className:`min-h-screen flex items-center justify-center`,children:`Loading...`}):t?(0,K.jsx)(Or,{to:`/login`,replace:!0}):(0,K.jsx)(K.Fragment,{children:e})}function c1e(){return(0,K.jsx)(n1e,{children:(0,K.jsx)(Id,{children:(0,K.jsx)(no,{client:r1e,children:(0,K.jsx)(md,{children:(0,K.jsx)(_d,{children:(0,K.jsx)(jQe,{children:(0,K.jsxs)(aAe,{children:[(0,K.jsx)(i1e,{}),(0,K.jsx)(bi,{children:(0,K.jsxs)(Mr,{children:[(0,K.jsx)(Ar,{path:`/setup`,element:(0,K.jsx)(s1e,{children:(0,K.jsx)(EQe,{})})}),(0,K.jsx)(Ar,{path:`/login`,element:(0,K.jsx)(TQe,{})}),(0,K.jsx)(Ar,{path:`/camera/:printerId`,element:(0,K.jsx)(ZXe,{})}),(0,K.jsx)(Ar,{path:`/overlay/:printerId`,element:(0,K.jsx)(nZe,{})}),(0,K.jsxs)(Ar,{element:(0,K.jsx)(o1e,{children:(0,K.jsx)(a1e,{children:(0,K.jsx)(UQe,{})})}),children:[(0,K.jsx)(Ar,{path:`spoolbuddy`,element:(0,K.jsx)(v$e,{})}),(0,K.jsx)(Ar,{path:`spoolbuddy/ams`,element:(0,K.jsx)(S$e,{})}),(0,K.jsx)(Ar,{path:`spoolbuddy/write-tag`,element:(0,K.jsx)(z$e,{})}),(0,K.jsx)(Ar,{path:`spoolbuddy/inventory`,element:(0,K.jsx)($$e,{})}),(0,K.jsx)(Ar,{path:`spoolbuddy/settings`,element:(0,K.jsx)(F$e,{})}),(0,K.jsx)(Ar,{path:`spoolbuddy/calibration`,element:(0,K.jsx)(L$e,{})})]}),(0,K.jsxs)(Ar,{element:(0,K.jsx)(o1e,{children:(0,K.jsx)(a1e,{children:(0,K.jsx)(Lp,{})})}),children:[(0,K.jsx)(Ar,{index:!0,element:(0,K.jsx)(eAe,{})}),(0,K.jsx)(Ar,{path:`archives`,element:(0,K.jsx)(Dze,{})}),(0,K.jsx)(Ar,{path:`queue`,element:(0,K.jsx)(jVe,{})}),(0,K.jsx)(Ar,{path:`pipelines/runs`,element:(0,K.jsx)(Or,{to:`/queue?tab=pipelines`,replace:!0})}),(0,K.jsx)(Ar,{path:`stats`,element:(0,K.jsx)(XVe,{})}),(0,K.jsx)(Ar,{path:`profiles`,element:(0,K.jsx)(JUe,{})}),(0,K.jsx)(Ar,{path:`maintenance`,element:(0,K.jsx)($Ue,{})}),(0,K.jsx)(Ar,{path:`projects`,element:(0,K.jsx)(nWe,{})}),(0,K.jsx)(Ar,{path:`projects/:id`,element:(0,K.jsx)(cWe,{})}),(0,K.jsx)(Ar,{path:`inventory`,element:(0,K.jsx)(nQe,{})}),(0,K.jsx)(Ar,{path:`files`,element:(0,K.jsx)(WXe,{})}),(0,K.jsx)(Ar,{path:`files/trash`,element:(0,K.jsx)(KXe,{})}),(0,K.jsx)(Ar,{path:`makerworld`,element:(0,K.jsx)($9,{permission:`makerworld:view`,children:(0,K.jsx)(mQe,{})})}),(0,K.jsx)(Ar,{path:`settings`,element:(0,K.jsx)($9,{permission:`settings:read`,children:(0,K.jsx)(TUe,{})})}),(0,K.jsx)(Ar,{path:`groups/new`,element:(0,K.jsx)($9,{permission:`groups:create`,children:(0,K.jsx)(m9,{})})}),(0,K.jsx)(Ar,{path:`groups/:id/edit`,element:(0,K.jsx)($9,{permission:`groups:update`,children:(0,K.jsx)(m9,{})})}),(0,K.jsx)(Ar,{path:`users`,element:(0,K.jsx)(Or,{to:`/settings?tab=users`,replace:!0})}),(0,K.jsx)(Ar,{path:`groups`,element:(0,K.jsx)(Or,{to:`/settings?tab=users`,replace:!0})}),(0,K.jsx)(Ar,{path:`system`,element:(0,K.jsx)(bQe,{})}),(0,K.jsx)(Ar,{path:`notifications`,element:(0,K.jsx)(DQe,{})}),(0,K.jsx)(Ar,{path:`gcode-viewer`,element:(0,K.jsx)(OQe,{})}),(0,K.jsx)(Ar,{path:`external/:id`,element:(0,K.jsx)(rZe,{})}),(0,K.jsx)(Ar,{path:`camera-tokens`,element:(0,K.jsx)(Or,{to:`/settings?tab=apikeys#card-camera-tokens`,replace:!0})})]})]})})]})})})})})})})}(0,b.createRoot)(document.getElementById(`root`)).render((0,K.jsx)(y.StrictMode,{children:(0,K.jsx)(c1e,{})})); \ No newline at end of file diff --git a/static/index.html b/static/index.html index 97083e35e..ae3c2b770 100644 --- a/static/index.html +++ b/static/index.html @@ -26,7 +26,7 @@ - +