From defec334c478df7e9d4ee677956b80be628803b1 Mon Sep 17 00:00:00 2001 From: maziggy Date: Wed, 10 Jun 2026 10:59:27 +0200 Subject: [PATCH] feat(a2l): add Bambu Lab A2L support (#1684) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Internal code N9 (from BambuStudio resources/profiles/BBL/machine/Bambu Lab A2L.json), serial prefix 26A19 (5-char, same shape as H2C's late 31B8B). Capabilities from Bambu's official A2L specs page: linear rail, single FDM extruder + integrated cutter/plotter, no Ethernet (2.4 GHz Wi-Fi only), low-rate chamber camera on port 6000. The BambuStudio profile's use_double_extruder_default_texture: true flag describes two TOOL HEADS (FDM + cutter), not dual filament extrusion — A2L must NOT be classified as dual-nozzle or AMS routing will target the deputy slot and firmware rejects with 07FF_8012. Registry updates: printer_models.py, firmware_check.py, virtual_printer/manager.py, virtual_printer/mqtt_server.py, PrintersPage.tsx, SpoolBuddyAmsPage.tsx. 12 new test cases in TestA2LModel pin every dimension. --- CHANGELOG.md | 2 + backend/app/services/firmware_check.py | 7 +++ .../app/services/virtual_printer/manager.py | 4 ++ .../services/virtual_printer/mqtt_server.py | 1 + backend/app/utils/printer_models.py | 5 ++ backend/tests/unit/test_printer_models.py | 63 +++++++++++++++++++ frontend/src/pages/PrintersPage.tsx | 57 ++++++++++------- .../pages/spoolbuddy/SpoolBuddyAmsPage.tsx | 3 +- .../{index-DdAEkh5e.js => index-lbRfAnFB.js} | 6 +- static/index.html | 2 +- 10 files changed, 121 insertions(+), 29 deletions(-) rename static/assets/{index-DdAEkh5e.js => index-lbRfAnFB.js} (97%) diff --git a/CHANGELOG.md b/CHANGELOG.md index a54b18d8f..115a460c9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,8 @@ All notable changes to Bambuddy will be documented in this file. ## [0.2.5b1] - Unreleased ### Added +- **Bambu Lab A2L support (#1684)** — Internal model code `N9`, serial prefix `26A19` (5 chars, same shape as H2C's late `31B8B`). Capabilities resolved from BambuStudio's `resources/profiles/BBL/machine/Bambu Lab A2L.json` cross-checked against Bambu's official A2L specs page: linear rail, single FDM extruder + integrated cutter/plotter head (the BambuStudio `use_double_extruder_default_texture: true` flag covers the dual TOOL HEADS, not dual filament extrusion — A2L must NOT route AMS to the deputy slot or firmware rejects with 07FF_8012). Specs page also confirms NO Ethernet (Wi-Fi 2.4 GHz 802.11 b/g/n only), `Low-Rate-Kamera` on the chamber-image protocol (port 6000, NOT RTSP:322), no heated chamber. **Registry updates**: `PRINTER_MODEL_MAP` + `PRINTER_MODEL_ID_MAP` + `LINEAR_RAIL_MODELS` in `utils/printer_models.py`; `MODEL_TO_API_KEY` + `API_KEY_TO_DEV_MODEL` + `API_KEY_TO_WIKI_PATH` in `firmware_check.py` (wiki path follows the established `/en/a2l/manual/a2l-firmware-release-history` pattern; the existing 404 handling in `_fetch_all_versions_from_wiki` makes this safe to ship before Bambu publishes the page); `VIRTUAL_PRINTER_MODELS` + `MODEL_SERIAL_PREFIXES` in `virtual_printer/manager.py` (prefix `26A19A` with the same revision-letter padding as X2D's `20P90A`); `MODEL_PRODUCT_NAMES` in `virtual_printer/mqtt_server.py`; `mapModelCode` + Add-Printer / Edit-Printer model dropdowns in `PrintersPage.tsx` (new "A2 Series" optgroup); `mapModelCode` in `SpoolBuddyAmsPage.tsx`. **Camera and dual-nozzle code paths need no edits**: `supports_rtsp()` correctly falls through to chamber-image for A2L because `N9` is neither in the internal-code RTSP set nor does the display name match the X1/X2/H2/P2 prefix tuple; `is_dual_nozzle_model()` correctly returns False because A2L is not in `DUAL_NOZZLE_MODELS`. The cutter/plotter capability surfaces in MQTT push fields Bambuddy doesn't yet model; ignored for v1, will surface as a follow-up only if a real-world A2L bundle reveals a confusing UI state. **Tests**: 12 new cases in `test_printer_models.py::TestA2LModel` pinning every dimension — rod type, model-id round-trip, both ethernet directions, both camera-port directions, the explicit non-dual-nozzle guard (regression guard for the BambuStudio profile flag misread), set membership in `LINEAR_RAIL_MODELS` and exclusion from `CARBON_ROD_MODELS` / `STEEL_ROD_MODELS`. + - **One-shot `device.*` identification probe in MQTT push parser (#1684 enabler)** — Adding support for a new Bambu printer model needs the internal model code the firmware sends in MQTT `device.dev_model_name` (e.g. A1 is `N2S`, H2C is `O1C`, X2D is `N6`). The field arrives on every push but Bambuddy never logged it, so even a debug-enabled support bundle from a new-model user (A2L on #1684 was the case that surfaced this) gave us no way to identify the model — `get_version` was also missing because the printer disconnected right after the request topic subscription, which is a separate firmware quirk. **Fix:** at the top of the existing `device.*` parsing block in `bambu_mqtt.py`, emit one INFO log per client session dumping `dev_model_name` / `dev_product_name` / `dev_id` / `project_name` if any are present; otherwise fall back to `device.keys()` so a future Bambu rename (e.g. `model_name` without the `dev_` prefix) still surfaces. INFO level so the line lands in every support bundle, not just debug-enabled ones; one-shot via a `_device_id_logged` flag matching the existing `_nozzle_fields_logged` pattern at line 2095 — no spam at every push_status. 3 unit tests in `TestDeviceIdentificationProbe` pin the one-shot behaviour, the known-id-field path, and the keys-fallback path. Full `test_bambu_mqtt.py` suite 281 / 281 green; ruff clean. Once this ships, a new-model issue self-resolves from the first bundle — no second round of "please enable debug and reupload" required. - **Archives page banner: reactive install-step-4 nudge for the slicer-side setting** — Companion to the new `external_storage` diagnostic check. The diagnostic catches the printer-side variant of "Store sent files on external storage" via `home_flag` bit 11. The slicer-side variant on older BambuStudio / OrcaSlicer never reaches the printer, so the diagnostic passes even when the option is off in the slicer. The deterministic symptom is the archiver creating a row with `extra_data.no_3mf_available=True` (`main.py:2770`) — that's the signal this banner watches. New backend endpoint `GET /archives/no-3mf-warning` returns `{has_fallback: bool}` — true iff any archive in the last 30 days has the flag set AND isn't soft-deleted. The 30-day window prevents old never-fixed installs from showing the banner forever; the soft-delete filter respects the user clearing the evidence. Frontend banner sits at the top of the Archives page (amber, dismissible) — "Some recent prints couldn't be archived with thumbnails…" + link to install step 4 in the wiki. Dismissal is one-shot via `localStorage` key `archiveNo3MFWarningDismissed` (matches the existing `Layout.tsx` update-banner pattern but persistent across sessions, since "you've been told" should outlive a browser restart). React-Query is `enabled: !dismissed` so the endpoint isn't polled after dismissal. 5 backend integration tests (`TestNo3MFWarning`) cover: recent fallback returns true, no archives returns false, archives without the flag returns false, >30-day-old fallbacks ignored, soft-deleted fallbacks ignored. i18n: 4 new keys (`title`, `body`, `docsLink`, `dismissLabel`) under `archives.no3mfBanner` translated to all 11 locales — no English fallbacks. diff --git a/backend/app/services/firmware_check.py b/backend/app/services/firmware_check.py index c01979768..bd0652204 100644 --- a/backend/app/services/firmware_check.py +++ b/backend/app/services/firmware_check.py @@ -62,6 +62,7 @@ MODEL_TO_API_KEY = { "A1 Mini": "a1-mini", "A1-Mini": "a1-mini", "A1mini": "a1-mini", + "A2L": "a2l", "H2D": "h2d", "H2C": "h2c", "H2S": "h2s", @@ -88,6 +89,7 @@ MODEL_TO_API_KEY = { "N1": "a1-mini", "N6": "x2d", "N7": "p2s", + "N9": "a2l", } # Reverse mapping: API key to model codes @@ -103,6 +105,7 @@ API_KEY_TO_DEV_MODEL = { "x1e": "C13", "x2d": "N6", "h2d-pro": "O1E", + "a2l": "N9", } # Wiki firmware release history pages (primary version source) @@ -118,6 +121,10 @@ API_KEY_TO_WIKI_PATH = { "p2s": "/en/p2s/manual/p2s-firmware-release-history", "x2d": "/en/x2d/manual/x2d-firmware-release-history", "h2d-pro": "/en/h2d-pro/manual/firmware-release-history", + # A2L wiki path follows the established pattern but isn't yet published — + # _fetch_all_versions_from_wiki silently returns [] on 404 so this is safe + # to ship before Bambu publishes the page. + "a2l": "/en/a2l/manual/a2l-firmware-release-history", } diff --git a/backend/app/services/virtual_printer/manager.py b/backend/app/services/virtual_printer/manager.py index f527bcb35..f7f7c5904 100644 --- a/backend/app/services/virtual_printer/manager.py +++ b/backend/app/services/virtual_printer/manager.py @@ -44,6 +44,8 @@ VIRTUAL_PRINTER_MODELS = { "C13": "X1E", # X1E # X2 Series "N6": "X2D", # X2D + # A2 Series (single-FDM + integrated cutter/plotter) + "N9": "A2L", # A2L # P Series "C11": "P1P", # P1P "C12": "P1S", # P1S @@ -76,6 +78,8 @@ MODEL_SERIAL_PREFIXES = { "C13": "03W00A", # X1E # X2 Series "N6": "20P90A", # X2D (first 4 chars "20P9" match real serials) + # A2 Series + "N9": "26A19A", # A2L (first 5 chars "26A19" match real serials) # P Series "C11": "01S00A", # P1P "C12": "01P00A", # P1S diff --git a/backend/app/services/virtual_printer/mqtt_server.py b/backend/app/services/virtual_printer/mqtt_server.py index 02f7621e6..48cbfd6ef 100644 --- a/backend/app/services/virtual_printer/mqtt_server.py +++ b/backend/app/services/virtual_printer/mqtt_server.py @@ -45,6 +45,7 @@ MODEL_PRODUCT_NAMES = { "BL-P002": "X1", "C13": "X1E", "N6": "X2D", + "N9": "A2L", "C11": "P1P", "C12": "P1S", "N7": "P2S", diff --git a/backend/app/utils/printer_models.py b/backend/app/utils/printer_models.py index 37fcf16d8..2add2b3e1 100644 --- a/backend/app/utils/printer_models.py +++ b/backend/app/utils/printer_models.py @@ -23,6 +23,7 @@ PRINTER_MODEL_MAP = { "Bambu Lab H2C": "H2C", "Bambu Lab H2S": "H2S", "Bambu Lab X2D": "X2D", + "Bambu Lab A2L": "A2L", } # Map from printer_model_id (internal codes in slice_info.config) to short names @@ -39,6 +40,8 @@ PRINTER_MODEL_ID_MAP = { "P2S": "P2S", # X2 series "N6": "X2D", + # A2 series (A2L is single-FDM + integrated cutter/plotter — single nozzle) + "N9": "A2L", # A1 series "A11": "A1", "A12": "A1 Mini", @@ -91,6 +94,7 @@ LINEAR_RAIL_MODELS = frozenset( # Display names (uppercase, no spaces) "A1", "A1MINI", + "A2L", "H2D", "H2DPRO", "H2C", @@ -98,6 +102,7 @@ LINEAR_RAIL_MODELS = frozenset( # Internal codes "N1", # A1 Mini "N2S", # A1 + "N9", # A2L "A04", # A1 Mini (alternate) "A11", # A1 "A12", # A1 Mini diff --git a/backend/tests/unit/test_printer_models.py b/backend/tests/unit/test_printer_models.py index c29662180..7e02d3d03 100644 --- a/backend/tests/unit/test_printer_models.py +++ b/backend/tests/unit/test_printer_models.py @@ -5,6 +5,7 @@ import pytest from backend.app.services.camera import get_camera_port, supports_rtsp from backend.app.utils.printer_models import ( CARBON_ROD_MODELS, + LINEAR_RAIL_MODELS, STEEL_ROD_MODELS, get_rod_type, has_ethernet, @@ -108,6 +109,68 @@ class TestX2DModel: assert "N6" in STEEL_ROD_MODELS +class TestA2LModel: + """A2L printer support (#1684). + + The A2L is a hybrid 3D printer + cutter/plotter announced June 2026. It + uses linear rails like the A1 family, has NO Ethernet (Wi-Fi 2.4 GHz only), + a low-rate chamber-image camera on port 6000 (no RTSP), and a single FDM + extruder (the second "tool head" in BambuStudio's profile is the cutter, + not a second extruder — must NOT be classified as dual-nozzle). Internal + SSDP/MQTT model code is "N9"; serial numbers begin with "26A19". + """ + + def test_a2l_is_linear_rail_display_name(self): + assert get_rod_type("A2L") == "linear_rail" + + def test_a2l_is_linear_rail_internal_code(self): + assert get_rod_type("N9") == "linear_rail" + + def test_a2l_model_id_map(self): + assert normalize_printer_model_id("N9") == "A2L" + + def test_a2l_model_map(self): + assert normalize_printer_model("Bambu Lab A2L") == "A2L" + + def test_a2l_has_no_ethernet_display_name(self): + """A2L specs (bambulab.com/de-de/a2l/specs) list Ethernet 'Nicht verfügbar'.""" + assert has_ethernet("A2L") is False + + def test_a2l_has_no_ethernet_internal_code(self): + assert has_ethernet("N9") is False + + def test_a2l_does_not_support_rtsp_display_name(self): + """A2L uses the low-rate chamber-image protocol on port 6000, not RTSP.""" + assert supports_rtsp("A2L") is False + + def test_a2l_does_not_support_rtsp_internal_code(self): + assert supports_rtsp("N9") is False + + def test_a2l_camera_port_is_chamber_image(self): + assert get_camera_port("A2L") == 6000 + assert get_camera_port("N9") == 6000 + + def test_a2l_is_not_dual_nozzle(self): + """A2L has a single FDM extruder + a cutter/plotter head. The + BambuStudio profile flag ``use_double_extruder_default_texture`` flags + the dual TOOL HEADS, not dual filament extrusion — A2L must not land + in the dual-nozzle group or AMS routing will target the deputy slot + and the firmware will reject the print with 07FF_8012. + """ + assert is_dual_nozzle_model("A2L") is False + assert is_dual_nozzle_model("N9") is False + + def test_a2l_in_linear_rail_set(self): + assert "A2L" in LINEAR_RAIL_MODELS + assert "N9" in LINEAR_RAIL_MODELS + + def test_a2l_not_in_carbon_or_steel_rod_sets(self): + assert "A2L" not in CARBON_ROD_MODELS + assert "N9" not in CARBON_ROD_MODELS + assert "A2L" not in STEEL_ROD_MODELS + assert "N9" not in STEEL_ROD_MODELS + + class TestA1SeriesModelIds: """Regression guard for the A1-family internal-code → display-name map. diff --git a/frontend/src/pages/PrintersPage.tsx b/frontend/src/pages/PrintersPage.tsx index b8c3c573f..602586c2e 100644 --- a/frontend/src/pages/PrintersPage.tsx +++ b/frontend/src/pages/PrintersPage.tsx @@ -1194,6 +1194,8 @@ function mapModelCode(ssdpModel: string | null): string { 'BL-P003': 'X1E', // X2 Series 'N6': 'X2D', + // A2 Series + 'N9': 'A2L', // P Series 'C11': 'P1S', 'C12': 'P1P', @@ -1211,6 +1213,7 @@ function mapModelCode(ssdpModel: string | null): string { 'P2S': 'P2S', 'A1': 'A1', 'A1 Mini': 'A1 Mini', + 'A2L': 'A2L', 'H2D': 'H2D', 'H2D Pro': 'H2D Pro', 'H2C': 'H2C', @@ -5963,28 +5966,31 @@ export function AddPrinterModal({ onChange={(e) => setForm({ ...form, model: e.target.value })} > + + + + + + + - - + + + + - - + + - - - - - - - - + + @@ -6489,28 +6495,31 @@ function EditPrinterModal({ onChange={(e) => setForm({ ...form, model: e.target.value })} > + + + + + + + - - + + + + - - + + - - - - - - - - + + diff --git a/frontend/src/pages/spoolbuddy/SpoolBuddyAmsPage.tsx b/frontend/src/pages/spoolbuddy/SpoolBuddyAmsPage.tsx index 10f2adb8e..b0fb34d18 100644 --- a/frontend/src/pages/spoolbuddy/SpoolBuddyAmsPage.tsx +++ b/frontend/src/pages/spoolbuddy/SpoolBuddyAmsPage.tsx @@ -27,10 +27,11 @@ function mapModelCode(ssdpModel: string | null): string { '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', 'H2D': 'H2D', 'H2D Pro': 'H2D Pro', 'H2C': 'H2C', 'H2S': 'H2S', + 'A1': 'A1', 'A1 Mini': 'A1 Mini', 'A2L': 'A2L', 'H2D': 'H2D', 'H2D Pro': 'H2D Pro', 'H2C': 'H2C', 'H2S': 'H2S', }; return modelMap[ssdpModel] || ssdpModel; } diff --git a/static/assets/index-DdAEkh5e.js b/static/assets/index-lbRfAnFB.js similarity index 97% rename from static/assets/index-DdAEkh5e.js rename to static/assets/index-lbRfAnFB.js index a9b355583..8f493841c 100644 --- a/static/assets/index-DdAEkh5e.js +++ b/static/assets/index-lbRfAnFB.js @@ -8533,7 +8533,7 @@ ${l("inventory.assignReconfigureNote")}`,r.jsx(ka,{title:l("inventory.assignMism 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 K9e({slots:t,filamentInfo:e}){const{t:a}=wt(),n=t.filter(l=>l.id>=2),i=6,s=16,o=Array.from({length:i},(l,c)=>n.find(d=>d.id===s+c)??{id:-(c+1),nozzle_type:"",nozzle_diameter:"",wear:null,stat:null,max_temp:0,serial_number:"",filament_color:"",filament_id:"",filament_type:""});return r.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:[r.jsx("p",{className:"text-[9px] text-bambu-gray mb-1",children:a("printers.nozzleRack")}),r.jsx("div",{className:"flex gap-[3px] justify-center",children:o.map((l,c)=>{const d=!l.nozzle_diameter&&!l.nozzle_type,u=d?null:KI(l.filament_color),m=u?CJ(l.filament_color):!1;return r.jsx(Ose,{slot:l,index:c,filamentName:l.filament_id?e?.[l.filament_id]?.name:void 0,children:r.jsx("div",{className:`w-7 h-7 rounded flex items-center justify-center cursor-default transition-colors border-b-2 ${d?"bg-bambu-dark-tertiary/20 border-bambu-dark-tertiary/20":"bg-bambu-dark-tertiary/40 border-bambu-dark-tertiary/40"}`,style:u?{backgroundColor:u}:void 0,children:r.jsx("span",{className:`text-[10px] font-semibold ${d?"text-bambu-gray/30":m?"text-black/80":"text-white"}`,style:u&&!m?{textShadow:"0 1px 3px rgba(0,0,0,0.9)"}:void 0,children:d?"—":l.nozzle_diameter||"?"})})},l.id>=0?l.id:`empty-${c}`)})})]})}function vY({className:t}){return r.jsx("svg",{className:t,viewBox:"0 0 36 54",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:r.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 Y9e({className:t}){return r.jsxs("svg",{className:t,viewBox:"0 0 35 53",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[r.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"}),r.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 Q9e({className:t}){return r.jsxs("svg",{className:t,viewBox:"0 0 36 54",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[r.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"}),r.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 X9e({className:t}){return r.jsxs("svg",{className:t,viewBox:"0 0 12 20",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[r.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"}),r.jsx("circle",{cx:"6",cy:"15",r:"2.5",stroke:"#C3C2C1",strokeWidth:"1",fill:"none"})]})}function Z9e({className:t}){return r.jsxs("svg",{className:t,viewBox:"0 0 12 20",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[r.jsx("rect",{x:"4.5",y:"8",width:"3",height:"4.5",fill:"#d4a017",rx:"0.5"}),r.jsx("circle",{cx:"6",cy:"15",r:"2",fill:"#d4a017"}),r.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 J9e({className:t}){return r.jsxs("svg",{className:t,viewBox:"0 0 12 20",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[r.jsx("rect",{x:"4.5",y:"3",width:"3",height:"9.5",fill:"#c62828",rx:"0.5"}),r.jsx("circle",{cx:"6",cy:"15",r:"2",fill:"#c62828"}),r.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 e7e({className:t}){return r.jsxs("svg",{className:t,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[r.jsx("rect",{x:"9.2",y:"3.4",width:"5.6",height:"8.1"}),r.jsx("rect",{x:"6",y:"11.5",width:"12.1",height:"3.7"}),r.jsx("path",{d:"M 7.3 15.2 L 12.1 19.6 L 16.7 15.2"})]})}function EF({className:t,color:e,isHeating:a}){const i={"text-orange-400":"#fb923c","text-blue-400":"#60a5fa","text-green-400":"#4ade80"}[e]||"#888",s=a?{filter:`drop-shadow(0 0 4px ${i}) drop-shadow(0 0 8px ${i})`}:{};return a?r.jsxs("svg",{className:t,style:s,viewBox:"0 0 12 20",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[r.jsx("rect",{x:"4.5",y:"3",width:"3",height:"9.5",fill:i,rx:"0.5"}),r.jsx("circle",{cx:"6",cy:"15",r:"2",fill:i}),r.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:i,strokeWidth:"1",fill:"none"})]}):r.jsxs("svg",{className:t,viewBox:"0 0 12 20",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[r.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:i,strokeWidth:"1",fill:"none"}),r.jsx("circle",{cx:"6",cy:"15",r:"2.5",stroke:i,strokeWidth:"1",fill:"none"})]})}function wY({humidity:t,goodThreshold:e=40,fairThreshold:a=60,onClick:n,compact:i}){const s=typeof t=="string"?parseInt(t,10):t,o=typeof e=="number"?e:40,l=typeof a=="number"?a:60;let c,d;isNaN(s)?(c="#C3C2C1",d="Unknown"):s<=o?(c="#22a352",d="Good"):s<=l?(c="#d4a017",d="Fair"):(c="#c62828",d="Bad");let u;return isNaN(s)||s<=o?u=vY:s<=l?u=Y9e:u=Q9e,r.jsxs("button",{type:"button",onClick:n,className:`flex items-center gap-1 ${n?"cursor-pointer hover:opacity-80 transition-opacity":""}`,title:`Humidity: ${s}% - ${d}${n?" (click for history)":""}`,children:[r.jsx(u,{className:i?"w-2.5 h-3":"w-3 h-4"}),r.jsxs("span",{className:`font-medium tabular-nums ${i?"text-[10px]":"text-xs"}`,style:{color:c},children:[s,"%"]})]})}function SY({temp:t,goodThreshold:e=28,fairThreshold:a=35,onClick:n,compact:i}){const s=typeof e=="number"?e:28,o=typeof a=="number"?a:35;let l,c,d;return t<=s?(l="#22a352",c="Good",d=X9e):t<=o?(l="#d4a017",c="Fair",d=Z9e):(l="#c62828",c="Bad",d=J9e),r.jsxs("button",{type:"button",onClick:n,className:`flex items-center gap-1 ${n?"cursor-pointer hover:opacity-80 transition-opacity":""}`,title:`Temperature: ${t}°C - ${c}${n?" (click for history)":""}`,children:[r.jsx(d,{className:i?"w-2.5 h-3":"w-3 h-4"}),r.jsxs("span",{className:`tabular-nums text-right ${i?"text-[10px] w-8":"w-12"}`,style:{color:l},children:[t,"°C"]})]})}function qo(t,e){const a=typeof t=="string"?parseInt(t,10):t,n=isNaN(a)?0:a,i=e===1,s=n>=128?n-128:n,o=String.fromCharCode(65+s);return i?`HT-${o}`:`AMS-${o}`}function DF(t){return t?.tray_type?null:t?.state===9||t?.state===10?"physical":"reset"}function t7e({url:t,printName:e}){const{t:a}=wt(),[n,i]=y.useState(!1),[s,o]=y.useState(!1),[l,c]=y.useState(!1),d=y.useMemo(()=>{if(!t)return null;const u=t.includes("?")?"&":"?";return zn(`${t}${u}v=${encodeURIComponent(e||Date.now().toString())}`)},[t,e]);return y.useEffect(()=>{i(!1),o(!1)},[d]),r.jsxs(r.Fragment,{children:[r.jsx("div",{className:`w-20 h-20 flex-shrink-0 rounded-lg overflow-hidden bg-bambu-dark-tertiary flex items-center justify-center ${d&&n?"cursor-pointer":""}`,onClick:()=>d&&n&&c(!0),children:d&&!s?r.jsxs(r.Fragment,{children:[r.jsx("img",{src:d,alt:a("printers.printPreview"),className:`w-full h-full object-cover ${n?"block":"hidden"}`,onLoad:()=>i(!0),onError:()=>o(!0)}),!n&&r.jsx(Ei,{className:"w-8 h-8 text-bambu-gray"})]}):r.jsx(Ei,{className:"w-8 h-8 text-bambu-gray"})}),l&&d&&r.jsx("div",{className:"fixed inset-0 bg-black/80 flex items-center justify-center z-50 p-8",onClick:()=>c(!1),children:r.jsxs("div",{className:"relative max-w-2xl max-h-full",children:[r.jsx("img",{src:d,alt:a("printers.printPreview"),className:"max-w-full max-h-[80vh] rounded-lg shadow-2xl"}),e&&r.jsx("p",{className:"text-white text-center mt-4 text-lg",children:e})]})})]})}function a7e({printers:t}){const{t:e}=wt(),a=na(),[n,i]=y.useState(0);y.useEffect(()=>{let c=!1;const d=a.getQueryCache().subscribe(()=>{c||(c=!0,requestAnimationFrame(()=>{i(u=>u+1),c=!1}))});return()=>d()},[a]);const{counts:s,nextFinish:o}=y.useMemo(()=>{let c=0,d=0,u=0,m=0,p=0,f=0,g=0,v=null,b=null,x=0;return t?.forEach(S=>{const k=a.getQueryData(["printerStatus",S.id]);if(k===void 0)f++;else if(!k.connected)p++;else{const C=k.hms_errors?Bm(k.hms_errors).length:0;switch(C>0&&g++,k.state){case"RUNNING":c++,k.remaining_time!=null&&k.remaining_time>0&&(b===null||k.remaining_time0||u++;break;default:m++;break}}}),{counts:{printing:c,paused:d,finished:u,idle:m,offline:p,loading:f,error:g,total:t?.length||0},nextFinish:v&&b?{name:v,remainingMin:b,progress:x}:null}},[t,a,n]);if(!t?.length)return null;const l=[{count:s.printing,dot:"bg-bambu-green animate-pulse",label:e("printers.status.printing").toLowerCase()},{count:s.paused,dot:"bg-status-warning",label:e("printers.status.paused","paused").toLowerCase()},{count:s.finished,dot:"bg-blue-400",label:e("printers.status.finished","finished").toLowerCase()},{count:s.idle,dot:s.idle>0?"bg-bambu-green":"bg-gray-500",label:e("printers.status.available").toLowerCase()},{count:s.error,dot:"bg-status-error",label:e("printers.status.problem").toLowerCase()},{count:s.offline,dot:"bg-gray-400",label:e("printers.status.offline").toLowerCase()}];return r.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-4 gap-y-2 text-bambu-gray",children:[l.map(({count:c,dot:d,label:u})=>c>0&&r.jsxs("div",{className:"flex items-center gap-1.5",children:[r.jsx("div",{className:`w-2 h-2 rounded-full ${d}`}),r.jsxs("span",{className:"text-bambu-gray",children:[r.jsx("span",{className:"text-white font-medium",children:c})," ",u]})]},u)),o&&r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"w-px h-4 bg-bambu-dark-tertiary"}),r.jsxs("div",{className:"flex flex-col gap-1 sm:flex-row sm:items-center sm:gap-2",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsxs("span",{className:"text-bambu-green font-medium",children:[e("printers.nextAvailable"),":"]}),r.jsx("span",{className:"text-white font-medium",children:o.name})]}),r.jsxs("div",{className:"flex items-center gap-2 w-full sm:w-auto",children:[r.jsx("div",{className:"w-full sm:w-16 bg-bambu-dark-tertiary rounded-full h-1.5",children:r.jsx("div",{className:"bg-bambu-green h-1.5 rounded-full transition-all",style:{width:`${o.progress}%`}})}),r.jsxs("span",{className:"text-white font-medium",children:[Math.round(o.progress),"%"]}),r.jsxs("span",{className:"text-bambu-gray",children:["(",ds(o.remainingMin*60),")"]})]})]})]})]})}function FF({value:t,options:e,onChange:a,fullWidth:n=!1}){const[i,s]=y.useState(!1),o=e.find(l=>l.value===t)??e[0];return r.jsxs("div",{className:`relative ${n?"w-full min-w-0":""}`,children:[r.jsxs("button",{type:"button",onClick:()=>s(l=>!l),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 ${n?"w-full":"min-w-28"}`,children:[r.jsx("span",{className:"truncate",children:o?.label}),r.jsx(za,{className:`w-4 h-4 text-bambu-gray transition-transform ${i?"rotate-180":""}`})]}),i&&r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>s(!1)}),r.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:e.map(l=>r.jsx("button",{type:"button",onClick:()=>{a(l.value),s(!1)},className:`w-full px-3 py-2 text-left text-sm transition-colors hover:bg-bambu-dark-tertiary ${l.value===t?"text-bambu-green":"text-white"}`,children:l.label},l.value))})]})]})}function LF({label:t,icon:e,children:a}){const[n,i]=y.useState(!1);return r.jsxs("div",{className:"relative",children:[r.jsx("button",{type:"button",onClick:()=>i(s=>!s),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":t,title:t,children:e}),n&&r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>i(!1)}),r.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:a})]})]})}const r7e=["error","printing","paused","finished","idle","offline"],kY={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 _Y(t){if(!t?.connected)return"offline";if((t.hms_errors?Bm(t.hms_errors):[]).length>0)return"error";switch(t.state){case"RUNNING":return"printing";case"PAUSE":return"paused";case"FINISH":return"finished";case"FAILED":return"finished";default:return"idle"}}function RF(t,e){if(e)return e;switch(t){case"RUNNING":return"Printing";case"PAUSE":return"Paused";case"FINISH":return"Finished";case"FAILED":return"Failed";case"IDLE":return"Idle";default:return t?t.charAt(0)+t.slice(1).toLowerCase():"Idle"}}function bw(t){return t?{O1D:"H2D",O1E:"H2D Pro",O2D:"H2D Pro",O1C:"H2C",O1C2:"H2C",O1S:"H2S","BL-P001":"X1C","BL-P002":"X1","BL-P003":"X1E",N6:"X2D",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",H2D:"H2D","H2D Pro":"H2D Pro",H2C:"H2C",H2S:"H2S"}[t]||t:""}function PY({ams:t,printerId:e,label:a,amsLabels:n,canEdit:i,onSaved:s,children:o}){const{t:l}=wt(),[c,d]=y.useState(!1),[u,m]=y.useState("top"),[p,f]=y.useState(""),[g,v]=y.useState(!1),[b,x]=y.useState(null),[S,k]=y.useState(!1),C=y.useRef(null),N=y.useRef(null),T=y.useRef(null);y.useEffect(()=>{c&&(f(n?.[t.id]??""),x(null),requestAnimationFrame(()=>{if(C.current&&N.current){const z=C.current.getBoundingClientRect(),I=z.top-56,B=window.innerHeight-z.bottom;m(II?"bottom":"top")}}))},[c,n,t.id]);const j=()=>{T.current&&clearTimeout(T.current),T.current=setTimeout(()=>d(!0),80)},D=()=>{T.current&&clearTimeout(T.current),S||(T.current=setTimeout(()=>d(!1),200))};y.useEffect(()=>()=>{T.current&&clearTimeout(T.current)},[]);const P=async()=>{if(i){v(!0),x(null);try{const z=p.trim();z?await ne.saveAmsLabel(e,t.id,z,t.serial_number):await ne.deleteAmsLabel(e,t.id,t.serial_number),s(),d(!1)}catch(z){x(z instanceof Error?z.message:String(z))}finally{v(!1)}}},E=async()=>{if(i){v(!0),x(null);try{await ne.deleteAmsLabel(e,t.id,t.serial_number),s(),d(!1)}catch(z){x(z instanceof Error?z.message:String(z))}finally{v(!1)}}};return r.jsxs("div",{ref:C,className:"relative inline-block",onMouseEnter:j,onMouseLeave:D,children:[o,c&&r.jsx("div",{ref:N,className:` + `})]})]})}function K9e({slots:t,filamentInfo:e}){const{t:a}=wt(),n=t.filter(l=>l.id>=2),i=6,s=16,o=Array.from({length:i},(l,c)=>n.find(d=>d.id===s+c)??{id:-(c+1),nozzle_type:"",nozzle_diameter:"",wear:null,stat:null,max_temp:0,serial_number:"",filament_color:"",filament_id:"",filament_type:""});return r.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:[r.jsx("p",{className:"text-[9px] text-bambu-gray mb-1",children:a("printers.nozzleRack")}),r.jsx("div",{className:"flex gap-[3px] justify-center",children:o.map((l,c)=>{const d=!l.nozzle_diameter&&!l.nozzle_type,u=d?null:KI(l.filament_color),m=u?CJ(l.filament_color):!1;return r.jsx(Ose,{slot:l,index:c,filamentName:l.filament_id?e?.[l.filament_id]?.name:void 0,children:r.jsx("div",{className:`w-7 h-7 rounded flex items-center justify-center cursor-default transition-colors border-b-2 ${d?"bg-bambu-dark-tertiary/20 border-bambu-dark-tertiary/20":"bg-bambu-dark-tertiary/40 border-bambu-dark-tertiary/40"}`,style:u?{backgroundColor:u}:void 0,children:r.jsx("span",{className:`text-[10px] font-semibold ${d?"text-bambu-gray/30":m?"text-black/80":"text-white"}`,style:u&&!m?{textShadow:"0 1px 3px rgba(0,0,0,0.9)"}:void 0,children:d?"—":l.nozzle_diameter||"?"})})},l.id>=0?l.id:`empty-${c}`)})})]})}function vY({className:t}){return r.jsx("svg",{className:t,viewBox:"0 0 36 54",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:r.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 Y9e({className:t}){return r.jsxs("svg",{className:t,viewBox:"0 0 35 53",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[r.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"}),r.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 Q9e({className:t}){return r.jsxs("svg",{className:t,viewBox:"0 0 36 54",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[r.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"}),r.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 X9e({className:t}){return r.jsxs("svg",{className:t,viewBox:"0 0 12 20",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[r.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"}),r.jsx("circle",{cx:"6",cy:"15",r:"2.5",stroke:"#C3C2C1",strokeWidth:"1",fill:"none"})]})}function Z9e({className:t}){return r.jsxs("svg",{className:t,viewBox:"0 0 12 20",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[r.jsx("rect",{x:"4.5",y:"8",width:"3",height:"4.5",fill:"#d4a017",rx:"0.5"}),r.jsx("circle",{cx:"6",cy:"15",r:"2",fill:"#d4a017"}),r.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 J9e({className:t}){return r.jsxs("svg",{className:t,viewBox:"0 0 12 20",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[r.jsx("rect",{x:"4.5",y:"3",width:"3",height:"9.5",fill:"#c62828",rx:"0.5"}),r.jsx("circle",{cx:"6",cy:"15",r:"2",fill:"#c62828"}),r.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 e7e({className:t}){return r.jsxs("svg",{className:t,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[r.jsx("rect",{x:"9.2",y:"3.4",width:"5.6",height:"8.1"}),r.jsx("rect",{x:"6",y:"11.5",width:"12.1",height:"3.7"}),r.jsx("path",{d:"M 7.3 15.2 L 12.1 19.6 L 16.7 15.2"})]})}function EF({className:t,color:e,isHeating:a}){const i={"text-orange-400":"#fb923c","text-blue-400":"#60a5fa","text-green-400":"#4ade80"}[e]||"#888",s=a?{filter:`drop-shadow(0 0 4px ${i}) drop-shadow(0 0 8px ${i})`}:{};return a?r.jsxs("svg",{className:t,style:s,viewBox:"0 0 12 20",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[r.jsx("rect",{x:"4.5",y:"3",width:"3",height:"9.5",fill:i,rx:"0.5"}),r.jsx("circle",{cx:"6",cy:"15",r:"2",fill:i}),r.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:i,strokeWidth:"1",fill:"none"})]}):r.jsxs("svg",{className:t,viewBox:"0 0 12 20",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[r.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:i,strokeWidth:"1",fill:"none"}),r.jsx("circle",{cx:"6",cy:"15",r:"2.5",stroke:i,strokeWidth:"1",fill:"none"})]})}function wY({humidity:t,goodThreshold:e=40,fairThreshold:a=60,onClick:n,compact:i}){const s=typeof t=="string"?parseInt(t,10):t,o=typeof e=="number"?e:40,l=typeof a=="number"?a:60;let c,d;isNaN(s)?(c="#C3C2C1",d="Unknown"):s<=o?(c="#22a352",d="Good"):s<=l?(c="#d4a017",d="Fair"):(c="#c62828",d="Bad");let u;return isNaN(s)||s<=o?u=vY:s<=l?u=Y9e:u=Q9e,r.jsxs("button",{type:"button",onClick:n,className:`flex items-center gap-1 ${n?"cursor-pointer hover:opacity-80 transition-opacity":""}`,title:`Humidity: ${s}% - ${d}${n?" (click for history)":""}`,children:[r.jsx(u,{className:i?"w-2.5 h-3":"w-3 h-4"}),r.jsxs("span",{className:`font-medium tabular-nums ${i?"text-[10px]":"text-xs"}`,style:{color:c},children:[s,"%"]})]})}function SY({temp:t,goodThreshold:e=28,fairThreshold:a=35,onClick:n,compact:i}){const s=typeof e=="number"?e:28,o=typeof a=="number"?a:35;let l,c,d;return t<=s?(l="#22a352",c="Good",d=X9e):t<=o?(l="#d4a017",c="Fair",d=Z9e):(l="#c62828",c="Bad",d=J9e),r.jsxs("button",{type:"button",onClick:n,className:`flex items-center gap-1 ${n?"cursor-pointer hover:opacity-80 transition-opacity":""}`,title:`Temperature: ${t}°C - ${c}${n?" (click for history)":""}`,children:[r.jsx(d,{className:i?"w-2.5 h-3":"w-3 h-4"}),r.jsxs("span",{className:`tabular-nums text-right ${i?"text-[10px] w-8":"w-12"}`,style:{color:l},children:[t,"°C"]})]})}function qo(t,e){const a=typeof t=="string"?parseInt(t,10):t,n=isNaN(a)?0:a,i=e===1,s=n>=128?n-128:n,o=String.fromCharCode(65+s);return i?`HT-${o}`:`AMS-${o}`}function DF(t){return t?.tray_type?null:t?.state===9||t?.state===10?"physical":"reset"}function t7e({url:t,printName:e}){const{t:a}=wt(),[n,i]=y.useState(!1),[s,o]=y.useState(!1),[l,c]=y.useState(!1),d=y.useMemo(()=>{if(!t)return null;const u=t.includes("?")?"&":"?";return zn(`${t}${u}v=${encodeURIComponent(e||Date.now().toString())}`)},[t,e]);return y.useEffect(()=>{i(!1),o(!1)},[d]),r.jsxs(r.Fragment,{children:[r.jsx("div",{className:`w-20 h-20 flex-shrink-0 rounded-lg overflow-hidden bg-bambu-dark-tertiary flex items-center justify-center ${d&&n?"cursor-pointer":""}`,onClick:()=>d&&n&&c(!0),children:d&&!s?r.jsxs(r.Fragment,{children:[r.jsx("img",{src:d,alt:a("printers.printPreview"),className:`w-full h-full object-cover ${n?"block":"hidden"}`,onLoad:()=>i(!0),onError:()=>o(!0)}),!n&&r.jsx(Ei,{className:"w-8 h-8 text-bambu-gray"})]}):r.jsx(Ei,{className:"w-8 h-8 text-bambu-gray"})}),l&&d&&r.jsx("div",{className:"fixed inset-0 bg-black/80 flex items-center justify-center z-50 p-8",onClick:()=>c(!1),children:r.jsxs("div",{className:"relative max-w-2xl max-h-full",children:[r.jsx("img",{src:d,alt:a("printers.printPreview"),className:"max-w-full max-h-[80vh] rounded-lg shadow-2xl"}),e&&r.jsx("p",{className:"text-white text-center mt-4 text-lg",children:e})]})})]})}function a7e({printers:t}){const{t:e}=wt(),a=na(),[n,i]=y.useState(0);y.useEffect(()=>{let c=!1;const d=a.getQueryCache().subscribe(()=>{c||(c=!0,requestAnimationFrame(()=>{i(u=>u+1),c=!1}))});return()=>d()},[a]);const{counts:s,nextFinish:o}=y.useMemo(()=>{let c=0,d=0,u=0,m=0,p=0,f=0,g=0,v=null,b=null,x=0;return t?.forEach(S=>{const k=a.getQueryData(["printerStatus",S.id]);if(k===void 0)f++;else if(!k.connected)p++;else{const C=k.hms_errors?Bm(k.hms_errors).length:0;switch(C>0&&g++,k.state){case"RUNNING":c++,k.remaining_time!=null&&k.remaining_time>0&&(b===null||k.remaining_time0||u++;break;default:m++;break}}}),{counts:{printing:c,paused:d,finished:u,idle:m,offline:p,loading:f,error:g,total:t?.length||0},nextFinish:v&&b?{name:v,remainingMin:b,progress:x}:null}},[t,a,n]);if(!t?.length)return null;const l=[{count:s.printing,dot:"bg-bambu-green animate-pulse",label:e("printers.status.printing").toLowerCase()},{count:s.paused,dot:"bg-status-warning",label:e("printers.status.paused","paused").toLowerCase()},{count:s.finished,dot:"bg-blue-400",label:e("printers.status.finished","finished").toLowerCase()},{count:s.idle,dot:s.idle>0?"bg-bambu-green":"bg-gray-500",label:e("printers.status.available").toLowerCase()},{count:s.error,dot:"bg-status-error",label:e("printers.status.problem").toLowerCase()},{count:s.offline,dot:"bg-gray-400",label:e("printers.status.offline").toLowerCase()}];return r.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-4 gap-y-2 text-bambu-gray",children:[l.map(({count:c,dot:d,label:u})=>c>0&&r.jsxs("div",{className:"flex items-center gap-1.5",children:[r.jsx("div",{className:`w-2 h-2 rounded-full ${d}`}),r.jsxs("span",{className:"text-bambu-gray",children:[r.jsx("span",{className:"text-white font-medium",children:c})," ",u]})]},u)),o&&r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"w-px h-4 bg-bambu-dark-tertiary"}),r.jsxs("div",{className:"flex flex-col gap-1 sm:flex-row sm:items-center sm:gap-2",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsxs("span",{className:"text-bambu-green font-medium",children:[e("printers.nextAvailable"),":"]}),r.jsx("span",{className:"text-white font-medium",children:o.name})]}),r.jsxs("div",{className:"flex items-center gap-2 w-full sm:w-auto",children:[r.jsx("div",{className:"w-full sm:w-16 bg-bambu-dark-tertiary rounded-full h-1.5",children:r.jsx("div",{className:"bg-bambu-green h-1.5 rounded-full transition-all",style:{width:`${o.progress}%`}})}),r.jsxs("span",{className:"text-white font-medium",children:[Math.round(o.progress),"%"]}),r.jsxs("span",{className:"text-bambu-gray",children:["(",ds(o.remainingMin*60),")"]})]})]})]})]})}function FF({value:t,options:e,onChange:a,fullWidth:n=!1}){const[i,s]=y.useState(!1),o=e.find(l=>l.value===t)??e[0];return r.jsxs("div",{className:`relative ${n?"w-full min-w-0":""}`,children:[r.jsxs("button",{type:"button",onClick:()=>s(l=>!l),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 ${n?"w-full":"min-w-28"}`,children:[r.jsx("span",{className:"truncate",children:o?.label}),r.jsx(za,{className:`w-4 h-4 text-bambu-gray transition-transform ${i?"rotate-180":""}`})]}),i&&r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>s(!1)}),r.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:e.map(l=>r.jsx("button",{type:"button",onClick:()=>{a(l.value),s(!1)},className:`w-full px-3 py-2 text-left text-sm transition-colors hover:bg-bambu-dark-tertiary ${l.value===t?"text-bambu-green":"text-white"}`,children:l.label},l.value))})]})]})}function LF({label:t,icon:e,children:a}){const[n,i]=y.useState(!1);return r.jsxs("div",{className:"relative",children:[r.jsx("button",{type:"button",onClick:()=>i(s=>!s),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":t,title:t,children:e}),n&&r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>i(!1)}),r.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:a})]})]})}const r7e=["error","printing","paused","finished","idle","offline"],kY={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 _Y(t){if(!t?.connected)return"offline";if((t.hms_errors?Bm(t.hms_errors):[]).length>0)return"error";switch(t.state){case"RUNNING":return"printing";case"PAUSE":return"paused";case"FINISH":return"finished";case"FAILED":return"finished";default:return"idle"}}function RF(t,e){if(e)return e;switch(t){case"RUNNING":return"Printing";case"PAUSE":return"Paused";case"FINISH":return"Finished";case"FAILED":return"Failed";case"IDLE":return"Idle";default:return t?t.charAt(0)+t.slice(1).toLowerCase():"Idle"}}function bw(t){return t?{O1D:"H2D",O1E:"H2D Pro",O2D:"H2D Pro",O1C:"H2C",O1C2:"H2C",O1S:"H2S","BL-P001":"X1C","BL-P002":"X1","BL-P003":"X1E",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"}[t]||t:""}function PY({ams:t,printerId:e,label:a,amsLabels:n,canEdit:i,onSaved:s,children:o}){const{t:l}=wt(),[c,d]=y.useState(!1),[u,m]=y.useState("top"),[p,f]=y.useState(""),[g,v]=y.useState(!1),[b,x]=y.useState(null),[S,k]=y.useState(!1),C=y.useRef(null),N=y.useRef(null),T=y.useRef(null);y.useEffect(()=>{c&&(f(n?.[t.id]??""),x(null),requestAnimationFrame(()=>{if(C.current&&N.current){const z=C.current.getBoundingClientRect(),I=z.top-56,B=window.innerHeight-z.bottom;m(II?"bottom":"top")}}))},[c,n,t.id]);const j=()=>{T.current&&clearTimeout(T.current),T.current=setTimeout(()=>d(!0),80)},D=()=>{T.current&&clearTimeout(T.current),S||(T.current=setTimeout(()=>d(!1),200))};y.useEffect(()=>()=>{T.current&&clearTimeout(T.current)},[]);const P=async()=>{if(i){v(!0),x(null);try{const z=p.trim();z?await ne.saveAmsLabel(e,t.id,z,t.serial_number):await ne.deleteAmsLabel(e,t.id,t.serial_number),s(),d(!1)}catch(z){x(z instanceof Error?z.message:String(z))}finally{v(!1)}}},E=async()=>{if(i){v(!0),x(null);try{await ne.deleteAmsLabel(e,t.id,t.serial_number),s(),d(!1)}catch(z){x(z instanceof Error?z.message:String(z))}finally{v(!1)}}};return r.jsxs("div",{ref:C,className:"relative inline-block",onMouseEnter:j,onMouseLeave:D,children:[o,c&&r.jsx("div",{ref:N,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 @@ -8545,7 +8545,7 @@ ${l("inventory.assignReconfigureNote")}`,r.jsx(ka,{title:l("inventory.assignMism flex items-center justify-center gap-1 px-3 py-1.5 rounded-lg text-xs font-medium transition-colors ${Yt&&B("printers:control")?Bt?"bg-bambu-green/20 text-bambu-green hover:bg-bambu-green/30":"bg-yellow-500/20 text-yellow-400 hover:bg-yellow-500/30":"bg-bambu-dark text-bambu-gray/50 cursor-not-allowed"} - `,title:B("printers:control")?P(Bt?"printers.resume":"printers.pause"):P("printers.permission.noControl"),children:[Bt?r.jsx(gs,{className:"w-3 h-3"}):r.jsx(US,{className:"w-3 h-3"}),P(Bt?"printers.resume":"printers.pause")]})]})]})]})})(),(Mo?.length>0||ke.vt_tray.length>0)&&n==="expanded"&&(()=>{const dt=Mo.filter(ut=>ut.tray.length>1),Bt=Mo.filter(ut=>ut.tray.length===1),Yt=t.nozzle_count===2||ke?.temperatures?.nozzle_2!==void 0;return r.jsxs("div",{className:"mt-3",children:[r.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[r.jsx("span",{className:"text-[10px] uppercase tracking-wider text-bambu-gray font-medium",children:P("printers.filaments")}),r.jsx("div",{className:"flex-1 h-px bg-bambu-dark-tertiary/30"})]}),r.jsxs("div",{className:"space-y-3",children:[dt.length>0&&r.jsx("div",{className:"grid grid-cols-2 gap-3",children:dt.map(ut=>{const Da=Ol[String(ut.id)],qr=ut.id>=128?ut.id-128:ut.id,Xa=Da!==void 0?Da:qr,bn=Xa===1,En=Xa===0;return r.jsxs("div",{className:"p-2.5 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary/30",children:[r.jsxs("div",{className:"flex items-center justify-between mb-2",children:[r.jsxs("div",{className:"flex items-center gap-1.5",children:[r.jsx(PY,{ams:ut,printerId:t.id,label:qo(ut.id,ut.tray.length),amsLabels:$a,canEdit:B("printers:update"),onSaved:Oa,children:r.jsx("span",{className:"text-[10px] text-white font-medium cursor-default select-none",children:$a?.[ut.id]||qo(ut.id,ut.tray.length)})}),Yt&&(bn||En)&&r.jsx(yY,{side:bn?"L":"R"})]}),(ut.humidity!=null||ut.temp!=null)&&r.jsxs("div",{className:"flex items-center gap-1.5 max-[550px]:flex-col max-[550px]:items-start",children:[ut.humidity!=null&&r.jsx(wY,{humidity:ut.humidity,goodThreshold:s?.humidityGood,fairThreshold:s?.humidityFair,onClick:()=>ea({amsId:ut.id,amsLabel:qo(ut.id,ut.tray.length),mode:"humidity"}),compact:!0}),ut.temp!=null&&r.jsx(SY,{temp:ut.temp,goodThreshold:s?.tempGood,fairThreshold:s?.tempFair,onClick:()=>ea({amsId:ut.id,amsLabel:qo(ut.id,ut.tray.length),mode:"temperature"}),compact:!0}),ke.supports_drying&&(ut.module_type==="n3f"||ut.module_type==="n3s")&&B("printers:control")&&r.jsx("button",{disabled:!!(ut.dry_sf_reason?.length&&ut.dry_time===0),onClick:sa=>{if(ut.dry_time>0)Do.mutate(ut.id);else if(Fe===ut.id)Ke(null);else{const Dn=(ut.tray.find($c=>$c.tray_type)?.tray_type||"PLA").split(" ")[0].toUpperCase(),Qn=C[Dn]||C.PLA,ki=ut.module_type;Qe(Dn),Ee(Qn[ki]||Qn.n3f),Xe(ki==="n3s"?Qn.n3s_hours:Qn.n3f_hours),Vt(!1),Me(ut.module_type),Ke(ut.id);const Gc=sa.currentTarget.getBoundingClientRect();It($8({triggerRect:Gc,popoverWidth:bY,estimatedHeight:xY}))}},className:`flex items-center gap-0.5 px-1 py-0.5 rounded text-[9px] transition-colors ${ut.dry_time>0?"bg-amber-500/20 text-amber-400":ut.dry_sf_reason?.length?"bg-bambu-dark-tertiary/30 text-bambu-gray/50 cursor-not-allowed":"bg-bambu-dark-tertiary/50 text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary"}`,title:ut.dry_time>0?P("printers.drying.stop"):ut.dry_sf_reason?.length?P("printers.drying.powerRequired"):P("printers.drying.start"),children:r.jsx(ym,{className:"w-3 h-3"})})]})]}),ut.dry_time>0&&r.jsxs("div",{className:"flex items-center gap-2 px-2 py-1 mb-1 bg-amber-500/10 border border-amber-500/20 rounded text-[9px]",children:[r.jsx(ym,{className:"w-3 h-3 text-amber-400 shrink-0"}),r.jsx("span",{className:"text-amber-400 font-medium",children:P("printers.drying.active")}),r.jsx("span",{className:"text-amber-300/70",children:P("printers.drying.timeRemaining",{time:ut.dry_time>=60?`${Math.floor(ut.dry_time/60)}h ${ut.dry_time%60}m`:`${ut.dry_time}m`})}),r.jsx("button",{onClick:()=>Do.mutate(ut.id),disabled:Do.isPending,className:"ml-auto text-amber-400 hover:text-amber-300 transition-colors disabled:opacity-50",title:P("printers.drying.stop"),children:r.jsx(Ht,{className:"w-3 h-3"})})]}),r.jsx("div",{className:"grid grid-cols-4 gap-1.5",children:[0,1,2,3].map(sa=>{const Ta=ut.tray[sa]||ut.tray.find(ha=>ha.id===sa),Dn=Ta?.tray_type&&Ta.remain>=0,Qn=!Ta?.tray_type,ki=DF(Ta),Gc=ut.id*4+sa,$c=ir===Gc,Ou=Ta?.tray_info_idx?Jt?.[Ta.tray_info_idx]:null,Qr=fa?.[Gc],Xn=(Ta?.tray_uuid||Ta?.tag_uid||Sm(t.serial_number,ut.id,sa))?.toUpperCase(),Fn=Xn?l?.[Xn]:void 0,Ss=GC(Fn),Fo=o&&!g?f?.find(ha=>ha.printer_id===t.id&&ha.ams_id===ut.id&&ha.tray_id===sa):void 0,rn=Fo?p?.find(ha=>ha.id===Fo.spoolman_spool_id):void 0,Lo=rn&&(rn.label_weight??0)>0?Math.round(Math.max(0,(rn.label_weight??0)-rn.weight_used)/(rn.label_weight??1)*100):null,mo=u?.(t.id,ut.id,sa),_i=(()=>{const ha=mo?.spool;return ha&&ha.label_weight>0&&ha.weight_used!=null?Math.round(Math.max(0,ha.label_weight-ha.weight_used)/ha.label_weight*100):null})(),Md=_i===0&&Dn&&Ta.remain>0?null:_i,fi=Ss??Lo??Md??(Dn?Ta.remain:null),wr=Ss!==null||Lo!==null?"spoolman":Md!==null?"inventory":Dn?"ams":void 0,zr=Ta?.tray_type?{vendor:Qs(Ta)?"Bambu Lab":"Generic",profile:Qr?.preset_name||(rn?[rn.brand,rn.slicer_filament_name?.split("@")[0].trim()||rn.material].filter(Boolean).join(" ").trim():null)||mo?.spool?.slicer_filament_name||Ou?.name||Ta.tray_sub_brands||Ta.tray_type,colorName:_c(Ta.tray_color||""),colorHex:Ta.tray_color||null,kFactor:MF(Ta.k),fillLevel:fi,trayUuid:Ta.tray_uuid||null,tagUid:Ta.tag_uid||null,fillSource:wr}:null,Zn=Vl?.amsId===ut.id&&Vl?.slotId===sa,kp=r.jsxs("div",{className:`bg-bambu-dark-tertiary rounded p-1 text-center ${Qn?"opacity-50":""} ${$c?"ring-2 ring-bambu-green ring-offset-1 ring-offset-bambu-dark":""}`,children:[r.jsx(jF,{trayColor:Ta?.tray_color,trayType:Ta?.tray_type,isEmpty:Qn,emptyKind:ki,slotNumber:sa+1}),r.jsx("div",{className:"text-[9px] text-white font-bold truncate",children:Ta?.tray_type||P(ki==="reset"?"ams.slotUnconfigured":"ams.slotEmpty")}),r.jsx("div",{className:"mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden",children:fi!==null&&fi>=0&&!Qn&&Ta&&r.jsx("div",{className:"h-full rounded-full transition-all",style:{width:`${fi}%`,backgroundColor:by(fi)}})})]});return r.jsxs("div",{className:"relative group",children:[Zn&&r.jsx("div",{className:"absolute inset-0 bg-bambu-dark-tertiary/80 rounded flex items-center justify-center z-20",children:r.jsx(tr,{className:"w-4 h-4 text-bambu-green animate-spin"})}),ke?.state!=="RUNNING"&&r.jsx("button",{onClick:ha=>{ha.stopPropagation(),qs(hi?.amsId===ut.id&&hi?.slotId===sa?null:{amsId:ut.id,slotId:sa})},className:"absolute -top-1 -right-1 w-4 h-4 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-full flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity z-10 hover:bg-bambu-dark-tertiary",title:P("printers.slotOptions"),children:r.jsx(Cm,{className:"w-2.5 h-2.5 text-bambu-gray"})}),ke?.state!=="RUNNING"&&hi?.amsId===ut.id&&hi?.slotId===sa&&r.jsxs("div",{className:"absolute top-full left-0 mt-1 z-50 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl py-1 min-w-[120px]",children:[r.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-xs flex items-center gap-2 ${B("printers:ams_rfid")?"text-white hover:bg-bambu-dark-tertiary":"text-bambu-gray/50 cursor-not-allowed"}`,onClick:ha=>{ha.stopPropagation(),B("printers:ams_rfid")&&(Ru.mutate({amsId:ut.id,slotId:sa}),qs(null))},disabled:Zn||!B("printers:ams_rfid"),title:B("printers:ams_rfid")?void 0:P("printers.permission.noAmsRfid"),children:[r.jsx(tr,{className:`w-3 h-3 ${Zn?"animate-spin":""}`}),P("printers.rfid.reread")]}),r.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-xs flex items-center gap-2 ${B("printers:control")?"text-white hover:bg-bambu-dark-tertiary":"text-bambu-gray/50 cursor-not-allowed"}`,onClick:ha=>{ha.stopPropagation(),B("printers:control")&&(Td.mutate({trayId:ut.id*4+sa}),qs(null))},disabled:!B("printers:control"),title:B("printers:control")?void 0:P("printers.permission.noControl"),children:[r.jsx(lw,{className:"w-3 h-3"}),P("printers.ams.load")]}),r.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-xs flex items-center gap-2 ${B("printers:control")?"text-white hover:bg-bambu-dark-tertiary":"text-bambu-gray/50 cursor-not-allowed"}`,onClick:ha=>{ha.stopPropagation(),B("printers:control")&&(Ad.mutate(),qs(null))},disabled:!B("printers:control"),title:B("printers:control")?void 0:P("printers.permission.noControl"),children:[r.jsx(Sg,{className:"w-3 h-3"}),P("printers.ams.unload")]})]}),zr?r.jsx(_F,{data:zr,spoolman:{enabled:o,linkedSpoolId:Fo?.spoolman_spool_id??(Xn?l?.[Xn]?.id:void 0),spoolmanUrl:c,syncMode:d,onLinkSpool:o&&!Fo&&!mo?()=>{const ha=(zr.trayUuid||zr.tagUid||Sm(t.serial_number,ut.id,sa)).toUpperCase();Pe({tagUid:zr.tagUid||ha,trayUuid:zr.trayUuid||"",printerId:t.id,amsId:ut.id,trayId:sa})}:void 0,onUnlinkSpool:Fn?.id?()=>pi.mutate(Fn.id):void 0},inventory:(()=>{if(o){if(g)return;const Wc=Fo,nn=rn;return{assignedSpool:nn?{id:nn.id,material:nn.material,brand:nn.brand??null,color_name:nn.color_name??null,remainingWeightGrams:nn.label_weight?Math.max(0,Math.round(nn.label_weight-nn.weight_used)):void 0}:null,onAssignSpool:()=>it({printerId:t.id,amsId:ut.id,trayId:sa,trayInfo:{type:Ta?.tray_type||zr.profile,material:Ta?.tray_type??void 0,profile:zr.profile,color:zr.colorHex||"",location:`${qo(ut.id,ut.tray.length)} Slot ${sa+1}`}}),onUnassignSpool:nn&&!Qs(Ta)?()=>v?.(nn.id):void 0,isAssigned:!!Wc||Qs(Ta)}}const ha=u?.(t.id,ut.id,sa);return{assignedSpool:ha?.spool?{id:ha.spool.id,material:ha.spool.material,brand:ha.spool.brand,color_name:ha.spool.color_name,remainingWeightGrams:Math.max(0,Math.round(ha.spool.label_weight-ha.spool.weight_used))}:null,onAssignSpool:()=>it({printerId:t.id,amsId:ut.id,trayId:sa,trayInfo:{type:Ta?.tray_type||zr.profile,material:Ta?.tray_type??void 0,profile:zr.profile,color:zr.colorHex||"",location:`${qo(ut.id,ut.tray.length)} Slot ${sa+1}`}}),onUnassignSpool:ha&&!Qs(Ta)?()=>m?.(t.id,ut.id,sa):void 0,isAssigned:!!ha||Qs(Ta)}})(),configureSlot:{enabled:B("printers:control"),onConfigure:()=>Se({amsId:ut.id,trayId:sa,trayCount:ut.tray.length,trayType:Ta?.tray_type||void 0,trayColor:Ta?.tray_color||void 0,traySubBrands:Ta?.tray_sub_brands||void 0,trayInfoIdx:Ta?.tray_info_idx||void 0,extruderId:Da,caliIdx:Ta?.cali_idx,savedPresetId:Qr?.preset_id})},children:kp}):r.jsx(PF,{kind:ki??void 0,configureSlot:{enabled:B("printers:control"),onConfigure:()=>Se({amsId:ut.id,trayId:sa,trayCount:ut.tray.length,extruderId:Da})},onAssignSpool:()=>it({printerId:t.id,amsId:ut.id,trayId:sa,trayInfo:{type:"",material:void 0,profile:"",color:"",location:`${qo(ut.id,ut.tray.length)} Slot ${sa+1}`}}),children:kp})]},sa)})})]},ut.id)})}),(Bt.length>0||ke.vt_tray.length>0)&&r.jsxs("div",{className:"grid grid-cols-4 gap-3",children:[Bt.map(ut=>{const Da=Ol[String(ut.id)],qr=ut.id>=128?ut.id-128:ut.id,Xa=Da!==void 0?Da:qr,bn=Xa===1,En=Xa===0,sa=ut.tray[0],Ta=sa?.tray_type&&sa.remain>=0,Dn=!sa?.tray_type,Qn=DF(sa),ki=ib(ut.id,sa?.id??0,!1),Gc=ir===ki,$c=sa?.tray_info_idx?Jt?.[sa.tray_info_idx]:null,Ou=fa?.[ki],Qr=sa?.id??0,Xn=(sa?.tray_uuid||sa?.tag_uid||Sm(t.serial_number,ut.id,Qr))?.toUpperCase(),Fn=Xn?l?.[Xn]:void 0,Ss=GC(Fn),Fo=u?.(t.id,ut.id,Qr),rn=(()=>{const ha=Fo?.spool;return ha&&ha.label_weight>0&&ha.weight_used!=null?Math.round(Math.max(0,ha.label_weight-ha.weight_used)/ha.label_weight*100):null})(),Lo=rn===0&&Ta&&sa.remain>0?null:rn,mo=o&&!g?f?.find(ha=>ha.printer_id===t.id&&ha.ams_id===ut.id&&ha.tray_id===Qr):void 0,_i=mo?p?.find(ha=>ha.id===mo.spoolman_spool_id):void 0,Md=_i&&(_i.label_weight??0)>0?Math.round(Math.max(0,(_i.label_weight??0)-_i.weight_used)/(_i.label_weight??1)*100):null,fi=Ss??Md??Lo??(Ta?sa.remain:null),wr=Ss!==null||Md!==null?"spoolman":Lo!==null?"inventory":Ta?"ams":void 0,zr=sa?.tray_type?{vendor:Qs(sa)?"Bambu Lab":"Generic",profile:Ou?.preset_name||(_i?[_i.brand,_i.slicer_filament_name?.split("@")[0].trim()||_i.material].filter(Boolean).join(" ").trim():null)||Fo?.spool?.slicer_filament_name||$c?.name||sa.tray_sub_brands||sa.tray_type,colorName:_c(sa.tray_color||""),colorHex:sa.tray_color||null,kFactor:MF(sa.k),fillLevel:fi,trayUuid:sa.tray_uuid||null,tagUid:sa.tag_uid||null,fillSource:wr}:null,Zn=Vl?.amsId===ut.id&&Vl?.slotId===Qr,kp=r.jsxs("div",{className:`bg-bambu-dark-tertiary rounded p-1 text-center ${Dn?"opacity-50":""} ${Gc?"ring-2 ring-bambu-green ring-offset-1 ring-offset-bambu-dark":""}`,children:[r.jsx(jF,{trayColor:sa?.tray_color,trayType:sa?.tray_type,isEmpty:Dn,emptyKind:Qn,slotNumber:1}),r.jsx("div",{className:"text-[9px] text-white font-bold truncate",children:sa?.tray_type||P(Qn==="reset"?"ams.slotUnconfigured":"ams.slotEmpty")}),r.jsx("div",{className:"mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden",children:fi!==null&&fi>=0&&!Dn&&r.jsx("div",{className:"h-full rounded-full transition-all",style:{width:`${fi}%`,backgroundColor:by(fi)}})})]});return r.jsxs("div",{className:"p-2.5 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary/30",children:[r.jsxs("div",{className:"flex items-center gap-1 mb-2",children:[r.jsx(PY,{ams:ut,printerId:t.id,label:qo(ut.id,ut.tray.length),amsLabels:$a,canEdit:B("printers:update"),onSaved:Oa,children:r.jsx("span",{className:"text-[10px] text-white font-medium cursor-default select-none",children:$a?.[ut.id]||qo(ut.id,ut.tray.length)})}),Yt&&(bn||En)&&r.jsx(yY,{side:bn?"L":"R"}),ke.supports_drying&&(ut.module_type==="n3f"||ut.module_type==="n3s")&&B("printers:control")&&r.jsx("div",{className:"relative ml-auto",children:r.jsx("button",{onClick:ha=>{if(ut.dry_time>0)Do.mutate(ut.id);else if(Fe===ut.id)Ke(null);else{const nn=(ut.tray.find(jk=>jk.tray_type)?.tray_type||"PLA").split(" ")[0].toUpperCase(),Pf=C[nn]||C.PLA,Ed=ut.module_type;Qe(nn),Ee(Pf[Ed]||Pf.n3f),Xe(Ed==="n3s"?Pf.n3s_hours:Pf.n3f_hours),Vt(!1),Me(ut.module_type),Ke(ut.id);const Ak=ha.currentTarget.getBoundingClientRect();It($8({triggerRect:Ak,popoverWidth:bY,estimatedHeight:xY}))}},className:`flex items-center gap-0.5 px-1 py-0.5 rounded text-[9px] transition-colors ${ut.dry_time>0?"bg-amber-500/20 text-amber-400":"bg-bambu-dark-tertiary/50 text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary"}`,title:ut.dry_time>0?P("printers.drying.stop"):P("printers.drying.start"),children:r.jsx(ym,{className:"w-3 h-3"})})})]}),ut.dry_time>0&&r.jsxs("div",{className:"flex items-center gap-1.5 px-2 py-1 mb-1 bg-amber-500/10 border border-amber-500/20 rounded text-[9px] whitespace-nowrap overflow-hidden",children:[r.jsx(ym,{className:"w-3 h-3 text-amber-400 shrink-0"}),r.jsx("span",{className:"text-amber-300/70 text-[8px] truncate",children:ut.dry_time>=60?`${Math.floor(ut.dry_time/60)}h ${ut.dry_time%60}m`:`${ut.dry_time}m`}),r.jsx("button",{onClick:()=>Do.mutate(ut.id),disabled:Do.isPending,className:"ml-auto text-amber-400 hover:text-amber-300 transition-colors disabled:opacity-50 shrink-0",title:P("printers.drying.stop"),children:r.jsx(Ht,{className:"w-3 h-3"})})]}),r.jsxs("div",{className:"flex gap-1.5 max-[550px]:flex-col max-[550px]:items-start",children:[r.jsxs("div",{className:"relative group flex-1 max-[550px]:w-full",children:[Zn&&r.jsx("div",{className:"absolute inset-0 bg-bambu-dark-tertiary/80 rounded flex items-center justify-center z-20",children:r.jsx(tr,{className:"w-4 h-4 text-bambu-green animate-spin"})}),ke?.state!=="RUNNING"&&r.jsx("button",{onClick:ha=>{ha.stopPropagation(),qs(hi?.amsId===ut.id&&hi?.slotId===Qr?null:{amsId:ut.id,slotId:Qr})},className:"absolute -top-1 -right-1 w-4 h-4 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-full flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity z-10 hover:bg-bambu-dark-tertiary",title:P("printers.slotOptions"),children:r.jsx(Cm,{className:"w-2.5 h-2.5 text-bambu-gray"})}),ke?.state!=="RUNNING"&&hi?.amsId===ut.id&&hi?.slotId===Qr&&r.jsxs("div",{className:"absolute top-full left-0 mt-1 z-50 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl py-1 min-w-[120px]",children:[r.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-xs flex items-center gap-2 ${B("printers:ams_rfid")?"text-white hover:bg-bambu-dark-tertiary":"text-bambu-gray/50 cursor-not-allowed"}`,onClick:ha=>{ha.stopPropagation(),B("printers:ams_rfid")&&(Ru.mutate({amsId:ut.id,slotId:Qr}),qs(null))},disabled:Zn||!B("printers:ams_rfid"),title:B("printers:ams_rfid")?void 0:P("printers.permission.noAmsRfid"),children:[r.jsx(tr,{className:`w-3 h-3 ${Zn?"animate-spin":""}`}),P("printers.rfid.reread")]}),r.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-xs flex items-center gap-2 ${B("printers:control")?"text-white hover:bg-bambu-dark-tertiary":"text-bambu-gray/50 cursor-not-allowed"}`,onClick:ha=>{ha.stopPropagation(),B("printers:control")&&(Td.mutate({trayId:ut.id*4+Qr}),qs(null))},disabled:!B("printers:control"),title:B("printers:control")?void 0:P("printers.permission.noControl"),children:[r.jsx(lw,{className:"w-3 h-3"}),P("printers.ams.load")]}),r.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-xs flex items-center gap-2 ${B("printers:control")?"text-white hover:bg-bambu-dark-tertiary":"text-bambu-gray/50 cursor-not-allowed"}`,onClick:ha=>{ha.stopPropagation(),B("printers:control")&&(Ad.mutate(),qs(null))},disabled:!B("printers:control"),title:B("printers:control")?void 0:P("printers.permission.noControl"),children:[r.jsx(Sg,{className:"w-3 h-3"}),P("printers.ams.unload")]})]}),zr?r.jsx(_F,{data:zr,spoolman:{enabled:o,linkedSpoolId:mo?.spoolman_spool_id??(Xn?l?.[Xn]?.id:void 0),spoolmanUrl:c,syncMode:d,onLinkSpool:o&&!mo&&!Fo?()=>{const ha=(zr.trayUuid||zr.tagUid||Sm(t.serial_number,ut.id,Qr)).toUpperCase();Pe({tagUid:zr.tagUid||ha,trayUuid:zr.trayUuid||"",printerId:t.id,amsId:ut.id,trayId:Qr})}:void 0,onUnlinkSpool:Fn?.id?()=>pi.mutate(Fn.id):void 0},inventory:(()=>{if(o){if(g)return;const Wc=mo,nn=_i;return{assignedSpool:nn?{id:nn.id,material:nn.material,brand:nn.brand??null,color_name:nn.color_name??null,remainingWeightGrams:nn.label_weight?Math.max(0,Math.round(nn.label_weight-nn.weight_used)):void 0}:null,onAssignSpool:()=>it({printerId:t.id,amsId:ut.id,trayId:Qr,trayInfo:{type:sa?.tray_type||zr.profile,material:sa?.tray_type??void 0,profile:zr.profile,color:zr.colorHex||"",location:qo(ut.id,ut.tray.length)}}),onUnassignSpool:nn&&!Qs(sa)?()=>v?.(nn.id):void 0,isAssigned:!!Wc||Qs(sa)}}const ha=u?.(t.id,ut.id,Qr);return{assignedSpool:ha?.spool?{id:ha.spool.id,material:ha.spool.material,brand:ha.spool.brand,color_name:ha.spool.color_name,remainingWeightGrams:Math.max(0,Math.round(ha.spool.label_weight-ha.spool.weight_used))}:null,onAssignSpool:()=>it({printerId:t.id,amsId:ut.id,trayId:Qr,trayInfo:{type:sa?.tray_type||zr.profile,material:sa?.tray_type??void 0,profile:zr.profile,color:zr.colorHex||"",location:qo(ut.id,ut.tray.length)}}),onUnassignSpool:ha&&!Qs(sa)?()=>m?.(t.id,ut.id,Qr):void 0,isAssigned:!!ha||Qs(sa)}})(),configureSlot:{enabled:B("printers:control"),onConfigure:()=>Se({amsId:ut.id,trayId:Qr,trayCount:ut.tray.length,trayType:sa?.tray_type||void 0,trayColor:sa?.tray_color||void 0,traySubBrands:sa?.tray_sub_brands||void 0,trayInfoIdx:sa?.tray_info_idx||void 0,extruderId:Da,caliIdx:sa?.cali_idx,savedPresetId:Ou?.preset_id})},children:kp}):r.jsx(PF,{kind:Qn??void 0,configureSlot:{enabled:B("printers:control"),onConfigure:()=>Se({amsId:ut.id,trayId:Qr,trayCount:ut.tray.length,extruderId:Da})},onAssignSpool:()=>it({printerId:t.id,amsId:ut.id,trayId:Qr,trayInfo:{type:"",material:void 0,profile:"",color:"",location:qo(ut.id,ut.tray.length)}}),children:kp})]}),(ut.humidity!=null||ut.temp!=null)&&r.jsxs("div",{className:"flex flex-col justify-center gap-1 shrink-0 max-[550px]:w-full",children:[ut.temp!=null&&r.jsx(SY,{temp:ut.temp,goodThreshold:s?.tempGood,fairThreshold:s?.tempFair,onClick:()=>ea({amsId:ut.id,amsLabel:qo(ut.id,ut.tray.length),mode:"temperature"}),compact:!0}),ut.humidity!=null&&r.jsx(wY,{humidity:ut.humidity,goodThreshold:s?.humidityGood,fairThreshold:s?.humidityFair,onClick:()=>ea({amsId:ut.id,amsLabel:qo(ut.id,ut.tray.length),mode:"humidity"}),compact:!0})]})]})]},ut.id)}),ke.vt_tray.length>0&&r.jsxs("div",{className:`p-2.5 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary/30 ${ke.vt_tray.length===1?"max-w-[50%]":""}`,children:[r.jsx("div",{className:"flex items-center gap-1 mb-2",children:r.jsx("span",{className:"text-[10px] text-white font-medium",children:P("printers.external")})}),r.jsx("div",{className:`grid ${ke.vt_tray.length>1?"grid-cols-2":"grid-cols-1"} gap-1.5`,children:[...ke.vt_tray].sort((ut,Da)=>(ut.id??254)-(Da.id??254)).map(ut=>{const Da=ut.id??254,qr=Yt&&ir===254?Da===254&&ke.active_extruder===1||Da===255&&ke.active_extruder===0:ir===Da,Xa=Da-254,bn=Yt?P(Da===254?"printers.extL":"printers.extR"):"",En=ut.tray_info_idx?Jt?.[ut.tray_info_idx]:null,sa=fa?.[1020+Xa],Ta=(ut.tray_uuid||ut.tag_uid||Sm(t.serial_number,255,Xa))?.toUpperCase(),Dn=Ta?l?.[Ta]:void 0,Qn=GC(Dn),ki=u?.(t.id,255,Xa),Gc=(()=>{const wr=ki?.spool;return wr&&wr.label_weight>0&&wr.weight_used!=null?Math.round(Math.max(0,wr.label_weight-wr.weight_used)/wr.label_weight*100):null})(),$c=ut.tray_type&&ut.remain>=0,Ou=Gc===0&&$c&&ut.remain>0?null:Gc,Qr=o&&!g?f?.find(wr=>wr.printer_id===t.id&&wr.ams_id===255&&wr.tray_id===Xa):void 0,Xn=Qr?p?.find(wr=>wr.id===Qr.spoolman_spool_id):void 0,Fn=Xn&&(Xn.label_weight??0)>0?Math.round(Math.max(0,(Xn.label_weight??0)-Xn.weight_used)/(Xn.label_weight??1)*100):null,Ss=Qn??Fn??Ou??($c?ut.remain:null),Fo=Qn!==null||Fn!==null?"spoolman":Ou!==null?"inventory":$c?"ams":void 0,rn={vendor:Qs(ut)?"Bambu Lab":"Generic",profile:sa?.preset_name||(Xn?[Xn.brand,Xn.slicer_filament_name?.split("@")[0].trim()||Xn.material].filter(Boolean).join(" ").trim():null)||ki?.spool?.slicer_filament_name||En?.name||ut.tray_sub_brands||ut.tray_type||"Unknown",colorName:_c(ut.tray_color||""),colorHex:ut.tray_color||null,kFactor:MF(ut.k),fillLevel:Ss,trayUuid:ut.tray_uuid||null,tagUid:ut.tag_uid||null,fillSource:Fo},Lo=!ut.tray_type,mo=DF(ut),_i=r.jsxs("div",{className:`bg-bambu-dark-tertiary rounded p-1 text-center ${Lo?"opacity-50":""} ${qr?"ring-2 ring-bambu-green ring-offset-1 ring-offset-bambu-dark":""}`,children:[r.jsx(jF,{trayColor:ut.tray_color,trayType:ut.tray_type,isEmpty:Lo,emptyKind:mo,slotNumber:Xa+1}),r.jsx("div",{className:`text-[9px] font-bold truncate ${Lo?"text-white/40":"text-white"}`,children:ut.tray_type||P("ams.slotEmpty")}),r.jsx("div",{className:"mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden",children:Ss!==null&&Ss>=0&&!Lo&&r.jsx("div",{className:"h-full rounded-full transition-all",style:{width:`${Ss}%`,backgroundColor:by(Ss)}})}),bn&&r.jsx("div",{className:"text-[7px] text-white/40 mt-0.5 truncate",children:bn})]}),Md=2550+Xa,fi=hi?.amsId===255&&hi?.slotId===Md;return r.jsxs("div",{className:"relative group",children:[ke?.state!=="RUNNING"&&r.jsx("button",{onClick:wr=>{wr.stopPropagation(),qs(fi?null:{amsId:255,slotId:Md})},className:"absolute -top-1 -right-1 w-4 h-4 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-full flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity z-10 hover:bg-bambu-dark-tertiary",title:P("printers.slotOptions"),children:r.jsx(Cm,{className:"w-2.5 h-2.5 text-bambu-gray"})}),ke?.state!=="RUNNING"&&fi&&r.jsxs("div",{className:"absolute top-full left-0 mt-1 z-50 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl py-1 min-w-[120px]",children:[r.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-xs flex items-center gap-2 ${B("printers:control")?"text-white hover:bg-bambu-dark-tertiary":"text-bambu-gray/50 cursor-not-allowed"}`,onClick:wr=>{wr.stopPropagation(),B("printers:control")&&(Td.mutate({trayId:Da}),qs(null))},disabled:!B("printers:control"),title:B("printers:control")?void 0:P("printers.permission.noControl"),children:[r.jsx(lw,{className:"w-3 h-3"}),P("printers.ams.load")]}),r.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-xs flex items-center gap-2 ${B("printers:control")?"text-white hover:bg-bambu-dark-tertiary":"text-bambu-gray/50 cursor-not-allowed"}`,onClick:wr=>{wr.stopPropagation(),B("printers:control")&&(Ad.mutate(),qs(null))},disabled:!B("printers:control"),title:B("printers:control")?void 0:P("printers.permission.noControl"),children:[r.jsx(Sg,{className:"w-3 h-3"}),P("printers.ams.unload")]})]}),Lo?r.jsx(PF,{kind:mo??void 0,configureSlot:{enabled:B("printers:control"),onConfigure:()=>Se({amsId:255,trayId:Xa,trayCount:1,extruderId:Yt?Da===254?1:0:void 0})},onAssignSpool:()=>it({printerId:t.id,amsId:255,trayId:Xa,trayInfo:{type:"",material:void 0,profile:"",color:"",location:`External Slot ${Xa+1}`}}),children:_i}):r.jsx(_F,{data:rn,spoolman:{enabled:o,linkedSpoolId:Qr?.spoolman_spool_id??(Ta?l?.[Ta]?.id:void 0),spoolmanUrl:c,syncMode:d,onLinkSpool:o&&!Qr&&!ki?()=>{const wr=(rn.trayUuid||rn.tagUid||Sm(t.serial_number,255,Xa)).toUpperCase();Pe({tagUid:rn.tagUid||wr,trayUuid:rn.trayUuid||"",printerId:t.id,amsId:255,trayId:Xa})}:void 0,onUnlinkSpool:Dn?.id?()=>pi.mutate(Dn.id):void 0},inventory:(()=>{if(o){if(g)return;const zr=Qr,Zn=Xn;return{assignedSpool:Zn?{id:Zn.id,material:Zn.material,brand:Zn.brand??null,color_name:Zn.color_name??null,remainingWeightGrams:Zn.label_weight?Math.max(0,Math.round(Zn.label_weight-Zn.weight_used)):void 0}:null,onAssignSpool:()=>it({printerId:t.id,amsId:255,trayId:Xa,trayInfo:{type:ut.tray_type||rn.profile,material:ut.tray_type??void 0,profile:rn.profile,color:rn.colorHex||"",location:bn||P("printers.external")}}),onUnassignSpool:Zn&&!Qs(ut)?()=>v?.(Zn.id):void 0,isAssigned:!!zr||Qs(ut)}}const wr=u?.(t.id,255,Xa);return{assignedSpool:wr?.spool?{id:wr.spool.id,material:wr.spool.material,brand:wr.spool.brand,color_name:wr.spool.color_name,remainingWeightGrams:Math.max(0,Math.round(wr.spool.label_weight-wr.spool.weight_used))}:null,onAssignSpool:()=>it({printerId:t.id,amsId:255,trayId:Xa,trayInfo:{type:ut.tray_type||rn.profile,material:ut.tray_type??void 0,profile:rn.profile,color:rn.colorHex||"",location:bn||P("printers.external")}}),onUnassignSpool:wr&&!Qs(ut)?()=>m?.(t.id,255,Xa):void 0,isAssigned:!!wr||Qs(ut)}})(),configureSlot:{enabled:B("printers:control"),onConfigure:()=>Se({amsId:255,trayId:Xa,trayCount:1,trayType:ut.tray_type||void 0,trayColor:ut.tray_color||void 0,traySubBrands:ut.tray_sub_brands||void 0,trayInfoIdx:ut.tray_info_idx||void 0,extruderId:Yt?Da===254?1:0:void 0,caliIdx:ut.cali_idx,savedPresetId:sa?.preset_id})},children:_i})]},Da)})})]})]})]})]})})()]}),$t&&n==="expanded"&&r.jsxs("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[r.jsx(jc,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"}),r.jsx("span",{className:"text-sm text-white truncate",children:$t.name}),$r&&r.jsxs("span",{className:`text-xs px-1.5 py-0.5 rounded flex-shrink-0 ${$r.state==="ON"?"bg-bambu-green/20 text-bambu-green":$r.state==="OFF"?"bg-red-500/20 text-red-400":"bg-bambu-gray/20 text-bambu-gray"}`,children:[$r.state||"?",$r.state==="ON"&&$r.energy?.power!=null&&r.jsxs("span",{className:"text-yellow-400 ml-1.5",children:["· ",Math.round($r.energy.power),"W"]})]})]}),r.jsx("div",{className:"flex-1"}),r.jsxs("div",{className:"flex items-center gap-1",children:[r.jsxs("button",{onClick:()=>Q(!0),disabled:Bl.isPending||$r?.state==="ON"||!B("smart_plugs:control"),className:`px-2 py-1 text-xs rounded transition-colors flex items-center gap-1 ${B("smart_plugs:control")?$r?.state==="ON"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary":"bg-bambu-dark text-bambu-gray/50 cursor-not-allowed"}`,title:B("smart_plugs:control")?void 0:P("printers.permission.noSmartPlugControl"),children:[r.jsx(Tu,{className:"w-3 h-3"}),"On"]}),r.jsxs("button",{onClick:()=>F(!0),disabled:Bl.isPending||$r?.state==="OFF"||!B("smart_plugs:control"),className:`px-2 py-1 text-xs rounded transition-colors flex items-center gap-1 ${B("smart_plugs:control")?$r?.state==="OFF"?"bg-red-500/30 text-red-400":"bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary":"bg-bambu-dark text-bambu-gray/50 cursor-not-allowed"}`,title:B("smart_plugs:control")?void 0:P("printers.permission.noSmartPlugControl"),children:[r.jsx(HS,{className:"w-3 h-3"}),"Off"]})]}),r.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[r.jsx("span",{className:`text-xs hidden sm:inline ${$t.auto_off_executed?"text-bambu-green":"text-bambu-gray"}`,children:$t.auto_off_executed?"Auto-off done":"Auto-off"}),r.jsx("button",{onClick:()=>Hc.mutate(!$t.auto_off),disabled:Hc.isPending||$t.auto_off_executed||!B("smart_plugs:control"),title:B("smart_plugs:control")?$t.auto_off_executed?P("printers.autoOffExecuted"):P("printers.autoOffAfterPrint"):P("printers.permission.noSmartPlugControl"),className:`relative w-9 h-5 rounded-full transition-colors flex-shrink-0 ${B("smart_plugs:control")?$t.auto_off_executed?"bg-bambu-green/50 cursor-not-allowed":$t.auto_off?"bg-bambu-green":"bg-bambu-dark-tertiary":"bg-bambu-dark-tertiary/50 cursor-not-allowed"}`,children:r.jsx("span",{className:`absolute top-[2px] left-[2px] w-4 h-4 bg-white rounded-full transition-transform ${$t.auto_off||$t.auto_off_executed?"translate-x-4":"translate-x-0"}`})})]})]}),Eo&&Eo.length>0&&r.jsxs("div",{className:"flex items-center gap-2 mt-2 pt-2 border-t border-bambu-dark-tertiary/50",children:[r.jsx(zS,{className:"w-3.5 h-3.5 text-blue-400 flex-shrink-0"}),r.jsx("span",{className:"text-xs text-bambu-gray",children:"HA:"}),r.jsx("div",{className:"flex flex-wrap gap-1",children:Eo.map(dt=>{const Bt=dt.ha_entity_id?.startsWith("script.");return r.jsxs("button",{onClick:()=>{Bt?Fu.mutate({id:dt.id,action:"on"}):$(dt)},disabled:Fu.isPending,title:`${Bt?"Run":"Toggle"} ${dt.ha_entity_id}`,className:"px-2 py-0.5 text-xs bg-blue-500/20 text-blue-400 hover:bg-blue-500/30 rounded transition-colors flex items-center gap-1",children:[r.jsx(gs,{className:"w-2.5 h-2.5"}),dt.name]},dt.id)})})]})]}),n==="expanded"&&r.jsxs("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary flex items-center justify-end gap-2 flex-wrap",children:[r.jsx(Le,{variant:"secondary",size:"sm",onClick:()=>kb.mutate(!ke?.chamber_light),disabled:!ke?.connected||kb.isPending||!B("printers:control"),title:B("printers:control")?ke?.chamber_light?P("printers.chamberLightOff"):P("printers.chamberLightOn"):P("printers.permission.noControl"),className:ke?.chamber_light?"!border-yellow-500 !text-yellow-400 hover:!bg-yellow-500/20":"",children:r.jsx(PO,{on:ke?.chamber_light??!1,className:`w-4 h-4 ${ke?.chamber_light?"text-yellow-400":""}`})}),r.jsx(Le,{variant:"secondary",size:"sm",onClick:()=>{if(x==="embedded"&&S)S(t.id,t.name);else{const dt=localStorage.getItem("cameraWindowState"),Bt=dt?JSON.parse(dt):{width:640,height:400},Yt=[`width=${Bt.width}`,`height=${Bt.height}`,Bt.left!==void 0?`left=${Bt.left}`:"",Bt.top!==void 0?`top=${Bt.top}`:"","menubar=no,toolbar=no,location=no,status=no"].filter(Boolean).join(",");window.open(`/camera/${t.id}`,`camera-${t.id}`,Yt)}},disabled:!ke?.connected||!B("camera:view"),title:B("camera:view")?P(x==="embedded"?"printers.openCameraOverlay":"printers.openCameraWindow"):P("printers.permission.noCamera"),children:r.jsx(bN,{className:"w-4 h-4"})}),r.jsxs("div",{className:`inline-flex rounded-md ${t.plate_detection_enabled?"ring-1 ring-green-500":""}`,children:[r.jsx(Le,{variant:"secondary",size:"sm",onClick:kf,disabled:!ke?.connected||Lu.isPending||!B("printers:update"),title:B("printers:update")?t.plate_detection_enabled?P("printers.plateDetection.enabledClick"):P("printers.plateDetection.disabledClick"):P("printers.plateDetection.noPermission"),className:`!rounded-r-none !border-r-0 ${t.plate_detection_enabled?"!border-green-500 !text-green-400 hover:!bg-green-500/20":""}`,children:Lu.isPending?r.jsx(lt,{className:"w-4 h-4 animate-spin"}):r.jsx(fN,{className:"w-4 h-4"})}),r.jsx(Le,{variant:"secondary",size:"sm",onClick:Pb,disabled:!ke?.connected||Je||!B("printers:update"),title:B("printers:update")?P("printers.plateDetection.manageCalibration"):P("printers.plateDetection.noPermission"),className:`!rounded-l-none !px-1.5 ${t.plate_detection_enabled?"!border-green-500 !text-green-400 hover:!bg-green-500/20":""}`,children:Je?r.jsx(lt,{className:"w-3 h-3 animate-spin"}):r.jsx(za,{className:"w-3 h-3"})})]}),r.jsxs(Le,{variant:"secondary",size:"sm",onClick:()=>me(!0),disabled:!vr||!B("printers:files"),title:B("printers:files")?P("printers.browseFiles"):P("printers.permission.noFiles"),children:[r.jsx(hb,{className:"w-4 h-4"}),P("printers.files")]}),vr&&ke?.state!=="RUNNING"&&ke?.state!=="PAUSE"&&r.jsxs(Le,{size:"sm",onClick:()=>Ce(!0),disabled:!B("printers:control"),title:B("printers:control")?P("common.print"):P("printers.permission.noControl"),className:"!bg-bambu-green hover:!bg-bambu-green/80 !text-white",children:[r.jsx(xr,{className:"w-4 h-4"}),P("common.print")]})]})]}),ie&&r.jsx(QDe,{printerId:t.id,printerName:t.name,onClose:()=>me(!1)}),qe&&r.jsx(Ese,{folderId:null,onClose:()=>Ce(!1),onUploadComplete:()=>{},autoUpload:!0,accept:".gcode,.3mf",validateFile:dt=>{const Bt=dt.name.toLowerCase();if(!Bt.endsWith(".gcode")&&!Bt.includes(".gcode."))return P("printers.dropNotPrintable","Only .gcode and .gcode.3mf files can be printed")},onFileUploaded:dt=>{const Bt=dt.metadata?.sliced_for_model,Yt=bw(t.model);if(Bt&&Yt&&Bt.toLowerCase()!==Yt.toLowerCase())return ne.deleteLibraryFile(dt.id).catch(()=>{}),P("printers.incompatibleFile","This file was sliced for {{slicedFor}}, but this printer is a {{printerModel}}",{slicedFor:Bt,printerModel:Yt});tt({id:dt.id,filename:dt.filename})}}),Oe&&r.jsx(Cc,{mode:"reprint",libraryFileId:Oe.id,archiveName:Oe.filename,initialSelectedPrinterIds:[t.id],onClose:()=>tt(null),onSuccess:()=>tt(null),cleanupLibraryAfterDispatch:!0}),he&&r.jsx(r2e,{printerId:t.id,printerName:t.name,onClose:()=>xe(!1)}),Ue&&r.jsx(QI,{printerId:t.id,printerName:t.name,onClose:()=>ze(!1)}),Ie&&r.jsx(G9e,{printer:t,status:ke,totalPrintHours:a?.total_print_hours,onClose:nt}),We&&r.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",onClick:()=>$l(),children:r.jsxs("div",{className:"bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl max-w-lg w-full",onClick:dt=>dt.stopPropagation(),children:[r.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[We.needs_calibration?r.jsx(fN,{className:"w-5 h-5 text-blue-500"}):We.is_empty?r.jsx(fr,{className:"w-5 h-5 text-green-500"}):r.jsx(Fr,{className:"w-5 h-5 text-yellow-500"}),r.jsx("h2",{className:"text-lg font-semibold text-white",children:"Build Plate Check"}),We.reference_count!==void 0&&We.max_references&&r.jsxs("span",{className:"text-xs text-bambu-gray bg-bambu-dark-tertiary px-2 py-1 rounded",children:[We.reference_count,"/",We.max_references," refs"]})]}),r.jsx("button",{onClick:()=>$l(),className:"p-1 text-bambu-gray hover:text-white rounded transition-colors",children:r.jsx(Ht,{className:"w-5 h-5"})})]}),r.jsxs("div",{className:"p-4 space-y-4",children:[We.needs_calibration?r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"p-3 rounded-lg bg-blue-500/20 border border-blue-500/50",children:[r.jsx("p",{className:"font-medium text-blue-400",children:P("printers.plateDetection.calibrationRequired")}),r.jsx("p",{className:"text-sm text-bambu-gray mt-1",dangerouslySetInnerHTML:{__html:P("printers.plateDetection.calibrationInstructions")}})]}),r.jsxs("div",{className:"text-sm text-bambu-gray space-y-2",children:[r.jsx("p",{children:P("printers.plateDetection.calibrationDescription")}),r.jsx("p",{dangerouslySetInnerHTML:{__html:P("printers.plateDetection.calibrationTip")}})]})]}):r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:`p-3 rounded-lg ${We.is_empty?"bg-green-500/20 border border-green-500/50":"bg-yellow-500/20 border border-yellow-500/50"}`,children:[r.jsx("p",{className:`font-medium ${We.is_empty?"text-green-400":"text-yellow-400"}`,children:We.is_empty?P("printers.plateDetection.plateEmpty"):P("printers.plateDetection.objectsDetected")}),r.jsxs("p",{className:"text-sm text-bambu-gray mt-1",children:[P("printers.plateDetection.confidence"),": ",Math.round(We.confidence*100),"% | ",P("printers.plateDetection.difference"),": ",We.difference_percent.toFixed(1),"%"]})]}),We.debug_image_url&&r.jsxs("div",{children:[r.jsx("p",{className:"text-sm text-bambu-gray mb-2",children:P("printers.plateDetection.analysisPreview")}),r.jsx("img",{src:We.debug_image_url,alt:P("printers.plateDetection.analysisPreview"),className:"w-full rounded-lg border border-bambu-dark-tertiary"}),r.jsx("p",{className:"text-xs text-bambu-gray mt-2",children:P("printers.plateDetection.analysisLegend")})]}),r.jsx("p",{className:"text-xs text-bambu-gray",children:We.message})]}),dl&&dl.references.length>0&&r.jsxs("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary",children:[r.jsx("p",{className:"text-sm font-medium text-white mb-2",children:P("printers.plateDetection.savedReferences",{count:dl.references.length,max:dl.max_references})}),r.jsx("div",{className:"grid grid-cols-5 gap-2",children:dl.references.map(dt=>r.jsxs("div",{className:"relative group",children:[r.jsx("img",{src:ne.getPlateReferenceThumbnailUrl(t.id,dt.index),alt:dt.label||`Reference ${dt.index+1}`,className:"w-full aspect-video object-cover rounded border border-bambu-dark-tertiary"}),r.jsx("button",{onClick:()=>Cb(dt.index),className:"absolute top-1 right-1 p-0.5 bg-red-500/80 rounded opacity-0 group-hover:opacity-100 transition-opacity",title:P("printers.plateDetection.deleteReference"),children:r.jsx(Ht,{className:"w-3 h-3 text-white"})}),Vc?.index===dt.index?r.jsx("input",{type:"text",value:Vc.label,onChange:Bt=>jd({...Vc,label:Bt.target.value}),onBlur:()=>wp(dt.index,Vc.label),onKeyDown:Bt=>{Bt.key==="Enter"&&wp(dt.index,Vc.label),Bt.key==="Escape"&&jd(null)},className:"w-full mt-1 px-1 py-0.5 text-xs bg-bambu-dark-tertiary border border-bambu-green rounded text-white",autoFocus:!0,placeholder:P("printers.plateDetection.labelPlaceholder")}):r.jsx("p",{className:"text-xs text-bambu-gray mt-1 truncate cursor-pointer hover:text-white",onClick:()=>jd({index:dt.index,label:dt.label}),title:dt.label?P("printers.plateDetection.clickToEdit",{label:dt.label}):P("printers.plateDetection.clickToAddLabel"),children:dt.label||r.jsx("span",{className:"italic opacity-50",children:P("printers.noLabel")})}),r.jsx("p",{className:"text-[10px] text-bambu-gray/60",children:dt.timestamp?Ga(dt.timestamp)?.toLocaleDateString()??"":""})]},dt.index))})]}),!We.needs_calibration&&r.jsxs("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"flex items-center justify-between mb-2",children:[r.jsx("p",{className:"text-sm font-medium text-white",children:P("printers.roi.title")}),_t?r.jsxs("div",{className:"flex gap-1",children:[r.jsx(Le,{variant:"ghost",size:"sm",onClick:()=>St(null),disabled:qt,children:P("common.cancel")}),r.jsx(Le,{size:"sm",onClick:Cv,disabled:qt,children:qt?r.jsx(lt,{className:"w-3 h-3 animate-spin"}):P("common.save")})]}):r.jsxs(Le,{variant:"ghost",size:"sm",onClick:()=>St(We.roi||{x:.15,y:.35,w:.7,h:.55}),children:[r.jsx(ci,{className:"w-3 h-3 mr-1"}),P("common.edit")]})]}),_t?r.jsxs("div",{className:"space-y-3 bg-bambu-dark-tertiary/50 p-3 rounded-lg",children:[r.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[r.jsxs("div",{children:[r.jsx("label",{className:"text-xs text-bambu-gray",children:P("printers.roi.xStart")}),r.jsx("input",{type:"range",min:"0",max:"0.9",step:"0.01",value:_t.x,onChange:dt=>St({..._t,x:parseFloat(dt.target.value)}),className:"w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"}),r.jsxs("span",{className:"text-xs text-bambu-gray",children:[Math.round(_t.x*100),"%"]})]}),r.jsxs("div",{children:[r.jsx("label",{className:"text-xs text-bambu-gray",children:P("printers.roi.yStart")}),r.jsx("input",{type:"range",min:"0",max:"0.9",step:"0.01",value:_t.y,onChange:dt=>St({..._t,y:parseFloat(dt.target.value)}),className:"w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"}),r.jsxs("span",{className:"text-xs text-bambu-gray",children:[Math.round(_t.y*100),"%"]})]}),r.jsxs("div",{children:[r.jsx("label",{className:"text-xs text-bambu-gray",children:P("printers.width")}),r.jsx("input",{type:"range",min:"0.1",max:"1",step:"0.01",value:_t.w,onChange:dt=>St({..._t,w:parseFloat(dt.target.value)}),className:"w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"}),r.jsxs("span",{className:"text-xs text-bambu-gray",children:[Math.round(_t.w*100),"%"]})]}),r.jsxs("div",{children:[r.jsx("label",{className:"text-xs text-bambu-gray",children:P("printers.height")}),r.jsx("input",{type:"range",min:"0.1",max:"1",step:"0.01",value:_t.h,onChange:dt=>St({..._t,h:parseFloat(dt.target.value)}),className:"w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"}),r.jsxs("span",{className:"text-xs text-bambu-gray",children:[Math.round(_t.h*100),"%"]})]})]}),r.jsx("p",{className:"text-xs text-bambu-gray",children:P("printers.roi.instruction")})]}):r.jsxs("p",{className:"text-xs text-bambu-gray",children:["Current: X=",Math.round((We.roi?.x||.15)*100),"%, Y=",Math.round((We.roi?.y||.35)*100),"%, W=",Math.round((We.roi?.w||.7)*100),"%, H=",Math.round((We.roi?.h||.55)*100),"%"]})]})]}),r.jsx("div",{className:"flex justify-end gap-2 p-4 border-t border-bambu-dark-tertiary",children:We.needs_calibration?r.jsxs(r.Fragment,{children:[r.jsx(Le,{variant:"ghost",onClick:()=>$l(),children:P("common.cancel")}),r.jsx(Le,{onClick:()=>_f(),disabled:kt,children:kt?r.jsxs(r.Fragment,{children:[r.jsx(lt,{className:"w-4 h-4 mr-2 animate-spin"}),"Calibrating..."]}):"Calibrate Empty Plate"})]}):r.jsxs(r.Fragment,{children:[r.jsx(Le,{variant:"ghost",onClick:()=>_f(),disabled:kt,children:kt?"Adding...":`Add Reference (${dl?.references.length||0}/${dl?.max_references||5})`}),r.jsx(Le,{onClick:()=>$l(),children:"Close"})]})})]})}),V&&$t&&r.jsx(ka,{title:P("printers.confirm.powerOnTitle"),message:P("printers.confirm.powerOnMessage",{name:t.name}),confirmText:P("printers.confirm.powerOnButton"),variant:"default",onConfirm:()=>{Bl.mutate("on"),Q(!1)},onCancel:()=>Q(!1)}),A&&$t&&r.jsx(ka,{title:P("printers.confirm.powerOffTitle"),message:ke?.state==="RUNNING"?P("printers.confirm.powerOffWarning",{name:t.name}):P("printers.confirm.powerOffMessage",{name:t.name}),confirmText:P("printers.confirm.powerOffButton"),variant:"danger",onConfirm:()=>{Bl.mutate("off"),F(!1)},onCancel:()=>F(!1)}),U&&r.jsx(ka,{title:P("printers.confirm.haToggleTitle",{name:U.name}),message:ke?.state==="RUNNING"?P("printers.confirm.haToggleWarning",{name:t.name,entity:U.ha_entity_id||U.name}):P("printers.confirm.haToggleMessage",{entity:U.ha_entity_id||U.name}),confirmText:P("printers.confirm.haToggleButton"),variant:ke?.state==="RUNNING"?"danger":"default",onConfirm:()=>{Fu.mutate({id:U.id,action:"toggle"}),$(null)},onCancel:()=>$(null)}),O&&r.jsx(ka,{title:P("printers.confirm.stopTitle"),message:P("printers.confirm.stopMessage",{name:t.name}),confirmText:P("printers.confirm.stopButton"),variant:"danger",onConfirm:()=>{Ul.mutate(),q(!1)},onCancel:()=>q(!1)}),Z&&r.jsx(ka,{title:P("printers.confirm.pauseTitle"),message:P("printers.confirm.pauseMessage",{name:t.name}),confirmText:P("printers.confirm.pauseButton"),variant:"default",onConfirm:()=>{Hl.mutate(),ee(!1)},onCancel:()=>ee(!1)}),ve&&r.jsx(ka,{title:P("printers.confirm.resumeTitle"),message:P("printers.confirm.resumeMessage",{name:t.name}),confirmText:P("printers.confirm.resumeButton"),variant:"default",onConfirm:()=>{Hs.mutate(),De(!1)},onCancel:()=>De(!1)}),ge&&r.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/70 p-4",children:r.jsxs("div",{className:"bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl w-full max-w-sm p-5",children:[r.jsxs("div",{className:"flex items-start gap-3 mb-4",children:[r.jsx(xa,{className:"w-5 h-5 text-yellow-400 flex-shrink-0 mt-0.5"}),r.jsxs("div",{children:[r.jsx("h3",{className:"text-sm font-semibold text-white mb-1",children:P("printers.bedJog.notHomedTitle")}),r.jsx("p",{className:"text-xs text-bambu-gray leading-relaxed",children:P("printers.bedJog.notHomedMessage")})]})]}),r.jsxs("div",{className:"flex flex-col gap-2",children:[r.jsx("button",{onClick:()=>{Pv.mutate("all"),be(null)},className:"w-full px-3 py-2 rounded-lg text-xs font-medium bg-bambu-green/20 text-bambu-green hover:bg-bambu-green/30 transition-colors",children:P("printers.bedJog.homeZ")}),r.jsx("button",{onClick:()=>{const dt=ge.distance;try{sessionStorage.setItem(`bambuddy.bedJog.warned.${t.id}`,"1")}catch{}yp.mutate({distance:dt,force:!0}),be(null)},className:"w-full px-3 py-2 rounded-lg text-xs font-medium bg-yellow-500/20 text-yellow-400 hover:bg-yellow-500/30 transition-colors",children:P("printers.bedJog.moveAnyway")}),r.jsx("button",{onClick:()=>be(null),className:"w-full px-3 py-2 rounded-lg text-xs font-medium bg-bambu-dark text-bambu-gray hover:bg-bambu-dark-tertiary transition-colors",children:P("common.cancel")})]})]})}),r.jsx(CO,{printerId:t.id,isOpen:je,onClose:()=>Te(!1)}),H&&r.jsx(Z0e,{printerName:t.name,errors:ke?.hms_errors||[],onClose:()=>le(!1),printerId:t.id,hasPermission:B}),Ct&&r.jsx(m9e,{isOpen:!!Ct,onClose:()=>ea(null),printerId:t.id,printerName:t.name,amsId:Ct.amsId,amsLabel:Ct.amsLabel,initialMode:Ct.mode,thresholds:s}),aa&&r.jsx(xse,{isOpen:!!aa,onClose:()=>Pe(null),tagUid:aa.tagUid,trayUuid:aa.trayUuid,printerId:aa.printerId,amsId:aa.amsId,trayId:aa.trayId}),Ye&&r.jsx(yse,{isOpen:!!Ye,onClose:()=>it(null),printerId:Ye.printerId,amsId:Ye.amsId,trayId:Ye.trayId,trayInfo:Ye.trayInfo,spoolmanEnabled:!!o}),Ae&&r.jsx(Mse,{isOpen:!!Ae,onClose:()=>Se(null),printerId:t.id,slotInfo:Ae,printerModel:bw(t.model)||void 0,onSuccess:()=>{E.invalidateQueries({queryKey:["slotPresets",t.id]}),E.invalidateQueries({queryKey:["printerStatus",t.id]})}}),oe&&r.jsx(s7e,{printer:t,onClose:()=>Y(!1)}),ct&&xt&&r.jsx(i7e,{printer:t,firmwareInfo:xt,onClose:()=>Ne(!1)}),hi&&r.jsx("div",{className:"fixed inset-0 z-40",onClick:()=>qs(null)}),Fe!==null&&ht&&(()=>{const dt=Ve==="n3s"?85:65,Bt=35,Yt=dt+10;return r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"fixed inset-0 z-[100]",onClick:()=>Ke(null)}),r.jsxs("div",{className:"fixed z-[101] flex flex-col w-[240px] bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl overflow-hidden",style:{top:ht.top,left:ht.left,maxHeight:`calc(100dvh - ${ht.top}px - 8px)`},onClick:ut=>ut.stopPropagation(),children:[r.jsxs("div",{className:"shrink-0 flex items-center gap-2 px-3 py-2.5 border-b border-bambu-dark-tertiary",children:[r.jsx(ym,{className:"w-3.5 h-3.5 text-amber-400"}),r.jsx("span",{className:"text-xs text-white font-medium",children:P("printers.drying.start")})]}),r.jsxs("div",{className:"px-3 py-2.5 space-y-2.5 overflow-y-auto min-h-0",children:[r.jsxs("div",{children:[r.jsx("label",{className:"text-[10px] text-bambu-gray mb-1 block",children:P("printers.filaments")}),r.jsx("select",{value:Be,onChange:ut=>{const Da=ut.target.value;Qe(Da);const qr=C[Da];qr&&(Ee(qr[Ve==="n3s"?"n3s":"n3f"]),Xe(Ve==="n3s"?qr.n3s_hours:qr.n3f_hours))},className:"w-full px-2 py-1.5 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-xs focus:outline-none focus:border-amber-500/50",children:Object.keys(C).map(ut=>r.jsx("option",{value:ut,children:ut},ut))})]}),r.jsxs("div",{children:[r.jsxs("div",{className:"flex items-center justify-between mb-1",children:[r.jsx("label",{className:"text-[10px] text-bambu-gray",children:P("printers.drying.temperature")}),r.jsxs("div",{className:"flex items-center gap-1",children:[r.jsx("input",{type:"number",min:45,max:dt,value:Ge,onChange:ut=>Ee(Math.min(dt,Math.max(45,Number(ut.target.value)||45))),className:"w-12 px-1 py-0.5 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-[11px] text-center focus:outline-none focus:border-amber-500/50 [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"}),r.jsx("span",{className:"text-[10px] text-bambu-gray",children:"°C"})]})]}),r.jsx("input",{type:"range",min:Bt,max:Yt,value:Ge,onChange:ut=>Ee(Math.min(dt,Math.max(45,Number(ut.target.value)))),className:"w-full h-1 accent-amber-500 cursor-pointer"}),r.jsxs("div",{className:"flex justify-between text-[9px] text-bambu-gray/50 mt-0.5",children:[r.jsx("span",{children:"45°C"}),r.jsxs("span",{children:[dt,"°C"]})]})]}),r.jsxs("div",{children:[r.jsxs("div",{className:"flex items-center justify-between mb-1",children:[r.jsx("label",{className:"text-[10px] text-bambu-gray",children:P("printers.drying.duration")}),r.jsxs("div",{className:"flex items-center gap-1",children:[r.jsx("input",{type:"number",min:1,max:24,value:rt,onChange:ut=>Xe(Math.min(24,Math.max(1,Number(ut.target.value)||1))),className:"w-10 px-1 py-0.5 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-[11px] text-center focus:outline-none focus:border-amber-500/50 [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"}),r.jsx("span",{className:"text-[10px] text-bambu-gray",children:P("printers.drying.hours")})]})]}),r.jsx("input",{type:"range",min:1,max:24,value:rt,onChange:ut=>Xe(Number(ut.target.value)),className:"w-full h-1 accent-amber-500 cursor-pointer"}),r.jsxs("div",{className:"flex justify-between text-[9px] text-bambu-gray/50 mt-0.5",children:[r.jsx("span",{children:"1h"}),r.jsx("span",{children:"24h"})]})]}),r.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[r.jsx("input",{type:"checkbox",checked:Nt,onChange:ut=>Vt(ut.target.checked),className:"w-3.5 h-3.5 accent-amber-500 rounded cursor-pointer"}),r.jsx("span",{className:"text-[11px] text-bambu-gray",children:P("printers.drying.rotateTray")})]})]}),r.jsx("div",{className:"shrink-0 px-3 pt-2.5 pb-3",children:r.jsx("button",{onClick:()=>{Fe!==null&&ll.mutate({amsId:Fe,temp:Ge,duration:rt,filament:Be,rotateTray:Nt})},disabled:ll.isPending,className:"w-full py-1.5 bg-amber-500 hover:bg-amber-400 text-white text-xs font-medium rounded-lg transition-colors disabled:opacity-50",children:ll.isPending?P("printers.drying.startingDrying"):P("printers.drying.start")})})]})]})})()]})}function n7e({onClose:t,onAdd:e,existingSerials:a}){const{t:n}=wt(),[i,s]=y.useState({name:"",serial_number:"",ip_address:"",access_code:"",model:"",location:"",auto_archive:!0}),[o,l]=y.useState(!1),[c,d]=y.useState([]),[u,m]=y.useState(""),[p,f]=y.useState(!1),[g,v]=y.useState(!1),[b,x]=y.useState([]),[S,k]=y.useState(""),[C,N]=y.useState(""),[T,j]=y.useState(!1),[D,P]=y.useState({scanned:0,total:0}),[E,z]=y.useState(!1),[I,B]=y.useState(!1),[R,K]=y.useState(null);y.useEffect(()=>{zd.getInfo().then(oe=>{v(oe.is_docker),oe.subnets.length>0&&(x(oe.subnets),k(oe.subnets[0]))}).catch(()=>{});try{const oe=localStorage.getItem("bambuddy.discovery.customSubnet");oe&&N(oe)}catch{}},[]);const J=c.filter(oe=>!a.includes(oe.serial)),X=async oe=>{oe.preventDefault(),B(!0);try{const Y=await ne.diagnoseConnection({ip_address:i.ip_address.trim(),serial_number:i.serial_number.trim()||void 0,access_code:i.access_code||void 0});if(Y.checks.some(ie=>ie.status==="fail")){K(Y);return}}catch{}finally{B(!1)}e(i)},ce=async()=>{m(""),d([]),l(!0),f(!1),P({scanned:0,total:0});const oe=T?C.trim():S,Y=g||T;if(Y&&T)try{localStorage.setItem("bambuddy.discovery.customSubnet",oe)}catch{}try{if(Y){await zd.startSubnetScan(oe);const ie=setInterval(async()=>{try{const me=await zd.getScanStatus();P({scanned:me.scanned,total:me.total});const he=await zd.getDiscoveredPrinters();d(he),me.running||(clearInterval(ie),l(!1),f(!0))}catch(me){console.error("Failed to get scan status:",me)}},500)}else{await zd.startDiscovery(10);const ie=setInterval(async()=>{try{const me=await zd.getDiscoveredPrinters();d(me)}catch(me){console.error("Failed to get discovered printers:",me)}},1e3);setTimeout(async()=>{clearInterval(ie);try{await zd.stopDiscovery()}catch{}l(!1),f(!0);try{const me=await zd.getDiscoveredPrinters();d(me)}catch(me){console.error("Failed to get final discovered printers:",me)}},1e4)}}catch(ie){console.error("Failed to start discovery:",ie),m(ie instanceof Error?ie.message:n("printers.discovery.failedToStart")),l(!1),f(!0)}},de=oe=>{const Y=oe.serial.startsWith("unknown-")?"":oe.serial;s({...i,name:oe.name||"",serial_number:Y,ip_address:oe.ip_address,model:bw(oe.model)}),d([])};return y.useEffect(()=>()=>{zd.stopDiscovery().catch(()=>{}),zd.stopSubnetScan().catch(()=>{})},[]),y.useEffect(()=>{const oe=Y=>{Y.key==="Escape"&&t()};return window.addEventListener("keydown",oe),()=>window.removeEventListener("keydown",oe)},[t]),r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-start sm:items-center justify-center z-50 p-4 overflow-y-auto",onClick:t,children:r.jsx(Tt,{className:"w-full max-w-md my-auto max-h-[calc(100vh-2rem)] overflow-y-auto",onClick:oe=>oe.stopPropagation(),children:r.jsxs(jt,{children:[r.jsx("h2",{className:"text-xl font-semibold mb-4",children:n("printers.addPrinter")}),r.jsxs("div",{className:"mb-4 pb-4 border-b border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"mb-3",children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("printers.discovery.subnetToScan")}),b.length>0?r.jsxs("select",{className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none text-sm",value:T?"__custom__":S,onChange:oe=>{oe.target.value==="__custom__"?j(!0):(j(!1),k(oe.target.value))},disabled:o,children:[b.map(oe=>r.jsx("option",{value:oe,children:oe},oe)),r.jsx("option",{value:"__custom__",children:n("printers.discovery.customSubnetOption")})]}):r.jsx("input",{type:"text",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none text-sm",value:S,onChange:oe=>k(oe.target.value),placeholder:"192.168.1.0/24",disabled:o}),T&&r.jsx("input",{type:"text","aria-label":n("printers.discovery.customSubnetLabel"),className:"mt-2 w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none text-sm",value:C,onChange:oe=>N(oe.target.value),placeholder:"10.1.1.0/24",disabled:o}),r.jsx("p",{className:"mt-1 text-xs text-bambu-gray",children:n(g?"printers.discovery.dockerNote":"printers.discovery.customSubnetNote")})]}),r.jsx(Le,{type:"button",variant:"secondary",onClick:ce,disabled:o,className:"w-full",children:o?r.jsxs(r.Fragment,{children:[r.jsx(lt,{className:"w-4 h-4 animate-spin"}),(g||T)&&D.total>0?n("printers.discovery.scanProgress",{scanned:D.scanned,total:D.total}):n("printers.discovery.scanning")]}):r.jsxs(r.Fragment,{children:[r.jsx(br,{className:"w-4 h-4"}),n(g||T?"printers.discovery.scanSubnet":"printers.discovery.discoverNetwork")]})}),u&&r.jsx("div",{className:"mt-2 text-sm text-red-400",children:u}),J.length>0&&r.jsx("div",{className:"mt-3 space-y-2 max-h-40 overflow-y-auto",children:J.map(oe=>r.jsxs("div",{className:"flex items-center justify-between p-2 bg-bambu-dark rounded-lg hover:bg-bambu-dark-secondary cursor-pointer transition-colors",onClick:()=>de(oe),children:[r.jsxs("div",{className:"min-w-0 flex-1",children:[r.jsx("p",{className:"font-medium text-white text-sm truncate",children:oe.name||oe.serial}),r.jsxs("p",{className:"text-xs text-bambu-gray truncate",children:[bw(oe.model)||n("printers.discovery.unknown")," • ",oe.ip_address,oe.serial.startsWith("unknown-")&&r.jsxs("span",{className:"text-yellow-500",children:[" • ",n("printers.discovery.serialRequired")]})]})]}),r.jsx(za,{className:"w-4 h-4 text-bambu-gray -rotate-90 flex-shrink-0 ml-2"})]},oe.serial))}),o&&r.jsx("p",{className:"mt-2 text-sm text-bambu-gray text-center",children:n(g||T?"printers.discovery.scanningSubnet":"printers.discovery.scanningNetwork")}),p&&!o&&c.length===0&&r.jsx("p",{className:"mt-2 text-sm text-bambu-gray text-center",children:n(g||T?"printers.discovery.noPrintersFoundSubnet":"printers.discovery.noPrintersFoundNetwork")}),p&&!o&&c.length>0&&J.length===0&&r.jsx("p",{className:"mt-2 text-sm text-bambu-gray text-center",children:n("printers.discovery.allConfigured")})]}),r.jsxs("form",{onSubmit:X,className:"space-y-4",children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("printers.name")}),r.jsx("input",{type:"text",required:!0,className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:i.name,onChange:oe=>s({...i,name:oe.target.value}),placeholder:n("printers.modal.myPrinter")})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("printers.ipAddress")}),r.jsx("input",{type:"text",required:!0,pattern:"(\\d{1,3}(\\.\\d{1,3}){3}|[a-zA-Z0-9]([a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])?(\\.[a-zA-Z0-9]([a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])?)*)",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:i.ip_address,onChange:oe=>s({...i,ip_address:oe.target.value}),placeholder:"192.168.1.100 or printer.local"})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("printers.serialNumber")}),r.jsx("input",{type:"text",required:!0,className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:i.serial_number,onChange:oe=>s({...i,serial_number:oe.target.value}),placeholder:"01P00A000000000"})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("printers.accessCode")}),r.jsx("input",{type:"password",required:!0,className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:i.access_code,onChange:oe=>s({...i,access_code:oe.target.value}),placeholder:n("printers.modal.fromPrinterSettings")})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("printers.modal.modelOptional")}),r.jsxs("select",{className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:i.model||"",onChange:oe=>s({...i,model:oe.target.value}),children:[r.jsx("option",{value:"",children:n("printers.modal.selectModel")}),r.jsxs("optgroup",{label:"H2 Series",children:[r.jsx("option",{value:"H2C",children:"H2C"}),r.jsx("option",{value:"H2D",children:"H2D"}),r.jsx("option",{value:"H2D Pro",children:"H2D Pro"}),r.jsx("option",{value:"H2S",children:"H2S"})]}),r.jsx("optgroup",{label:"X2 Series",children:r.jsx("option",{value:"X2D",children:"X2D"})}),r.jsxs("optgroup",{label:"X1 Series",children:[r.jsx("option",{value:"X1E",children:"X1E"}),r.jsx("option",{value:"X1C",children:"X1 Carbon"}),r.jsx("option",{value:"X1",children:"X1"})]}),r.jsxs("optgroup",{label:"P Series",children:[r.jsx("option",{value:"P2S",children:"P2S"}),r.jsx("option",{value:"P1S",children:"P1S"}),r.jsx("option",{value:"P1P",children:"P1P"})]}),r.jsxs("optgroup",{label:"A1 Series",children:[r.jsx("option",{value:"A1",children:"A1"}),r.jsx("option",{value:"A1 Mini",children:"A1 Mini"})]})]})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("printers.modal.locationGroup")}),r.jsx("input",{type:"text",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:i.location||"",onChange:oe=>s({...i,location:oe.target.value}),placeholder:n("printers.modal.locationPlaceholder")}),r.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:n("printers.locationHelp")})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("input",{type:"checkbox",id:"auto_archive",checked:i.auto_archive,onChange:oe=>s({...i,auto_archive:oe.target.checked}),className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),r.jsx("label",{htmlFor:"auto_archive",className:"text-sm text-bambu-gray",children:n("printers.modal.autoArchiveLabel")})]}),r.jsxs("button",{type:"button",onClick:()=>z(!0),disabled:!i.ip_address.trim(),className:"w-full flex items-center justify-center gap-2 px-3 py-2 text-sm text-bambu-gray hover:text-white disabled:opacity-40 disabled:cursor-not-allowed border border-bambu-dark-tertiary rounded-lg transition-colors",children:[r.jsx(Ll,{className:"w-4 h-4"}),n("diagnostic.runButton")]}),R?r.jsxs("div",{className:"rounded-lg bg-amber-500/10 border border-amber-500/30 p-3 space-y-3",children:[r.jsxs("div",{className:"flex items-start gap-2",children:[r.jsx(xa,{className:"w-4 h-4 mt-0.5 flex-shrink-0 text-amber-400"}),r.jsx("p",{className:"text-sm text-amber-300",children:n("printers.addPreflight.warning")})]}),r.jsx(U1,{result:R}),r.jsxs("div",{className:"flex gap-3",children:[r.jsx(Le,{type:"button",variant:"secondary",onClick:()=>K(null),className:"flex-1",children:n("printers.addPreflight.back")}),r.jsx(Le,{type:"button",onClick:()=>e(i),className:"flex-1",children:n("printers.addPreflight.saveAnyway")})]})]}):r.jsxs("div",{className:"flex gap-3 pt-2",children:[r.jsx(Le,{type:"button",variant:"secondary",onClick:t,className:"flex-1",children:n("common.cancel")}),r.jsx(Le,{type:"submit",disabled:I,className:"flex-1",children:n(I?"printers.addPreflight.checking":"printers.addPrinter")})]})]})]})})}),E&&r.jsx(QI,{connection:{ip_address:i.ip_address.trim(),serial_number:i.serial_number.trim()||void 0,access_code:i.access_code||void 0},printerName:i.name||null,onClose:()=>z(!1)})]})}function i7e({printer:t,firmwareInfo:e,onClose:a}){const{t:n}=wt(),i=na(),{showToast:s}=oa(),{hasPermission:o}=lr(),l=o("firmware:update"),[c,d]=y.useState(null),[u,m]=y.useState(!1),[p,f]=y.useState(null),[g,v]=y.useState(e.update_available?e.latest_version:null),{data:b,isLoading:x}=$e({queryKey:["firmwarePrepare",t.id,g],queryFn:()=>AC.prepareUpload(t.id,g??void 0),staleTime:3e4,enabled:!!g&&l&&!u}),S=at({mutationFn:()=>AC.startUpload(t.id,g??void 0),onSuccess:()=>{m(!0);const C=setInterval(async()=>{try{const N=await AC.getUploadStatus(t.id);d(N),(N.status==="complete"||N.status==="error")&&(clearInterval(C),f(null),m(!1),N.status==="complete"&&(s(n("printers.firmwareModal.uploadedToast"),"success"),i.invalidateQueries({queryKey:["firmwareUpdate",t.id]})))}catch{}},2e3);f(C)},onError:C=>{s(n("printers.firmwareModal.uploadFailed",{error:C.message}),"error"),m(!1)}});y.useEffect(()=>()=>{p&&clearInterval(p)},[p]);const k=()=>{d(null),S.mutate()};return r.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",children:r.jsx(Tt,{className:"w-full max-w-md mx-4",children:r.jsxs(jt,{children:[r.jsxs("div",{className:"flex items-start gap-3 mb-4",children:[r.jsx("div",{className:`p-2 rounded-full ${e.update_available?"bg-orange-500/20":"bg-status-ok/20"}`,children:e.update_available?r.jsx(Ur,{className:"w-5 h-5 text-orange-400"}):r.jsx(fr,{className:"w-5 h-5 text-status-ok"})}),r.jsxs("div",{className:"flex-1",children:[r.jsx("h3",{className:"text-lg font-semibold text-white",children:e.update_available?n("printers.firmwareModal.title"):n("printers.firmwareModal.titleUpToDate")}),r.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:t.name})]})]}),(()=>{const C=g?e.available_versions?.find(D=>D.version===g):null,N=g??e.latest_version,T=C?.release_notes??e.release_notes,j=!!N&&N!==e.current_version;return r.jsxs("div",{className:"bg-bambu-dark rounded-lg p-3 mb-4",children:[r.jsxs("div",{className:"flex justify-between items-center text-sm",children:[r.jsx("span",{className:"text-bambu-gray",children:n("printers.firmwareModal.currentVersion")}),r.jsx("span",{className:`font-mono ${j?"text-white":"text-status-ok"}`,children:e.current_version||n("common.unknown")})]}),j&&r.jsxs("div",{className:"flex justify-between items-center text-sm mt-1",children:[r.jsx("span",{className:"text-bambu-gray",children:n("printers.firmwareModal.latestVersion")}),r.jsx("span",{className:"text-orange-400 font-mono",children:N})]}),T&&r.jsxs("details",{className:"mt-3 text-sm",open:!j,children:[r.jsx("summary",{className:`cursor-pointer hover:underline ${j?"text-orange-400":"text-status-ok"}`,children:n("printers.firmwareModal.releaseNotes")}),r.jsx("div",{className:"mt-2 text-bambu-gray text-xs max-h-40 overflow-y-auto whitespace-pre-wrap",children:T})]},N??"none")]})})(),e.available_versions&&e.available_versions.length>0&&!u&&c?.status!=="complete"&&r.jsxs("div",{className:"mb-4",children:[r.jsx("div",{className:"text-xs text-bambu-gray mb-2",children:n("printers.firmwareModal.availableVersions")}),r.jsx("div",{className:"max-h-56 overflow-y-auto border border-bambu-dark-tertiary rounded-lg divide-y divide-bambu-dark-tertiary",children:e.available_versions.map(C=>{const N=e.current_version===C.version,T=g===C.version,j=e.current_version?Y0e(C.version,e.current_version):0,D=N?n("printers.firmwareModal.currentBadge"):j>0?n("printers.firmwareModal.newerBadge"):n("printers.firmwareModal.olderBadge"),P=N?"text-bambu-gray":j>0?"text-orange-400":"text-blue-400";return r.jsxs("button",{type:"button",disabled:!C.file_available||!l||N,onClick:()=>v(C.version),className:`w-full text-left px-3 py-2 text-sm flex items-center justify-between gap-2 transition-colors ${T?"bg-orange-500/10":"hover:bg-bambu-dark"} ${!C.file_available||!l||N?"opacity-60 cursor-not-allowed":"cursor-pointer"}`,children:[r.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[r.jsx("span",{className:"font-mono text-white",children:C.version}),r.jsx("span",{className:`text-xs ${P}`,children:D})]}),r.jsx("span",{className:`text-xs px-2 py-0.5 rounded-full ${N?"bg-blue-500/15 text-blue-400 border border-blue-500/30":C.file_available?"bg-bambu-green/15 text-bambu-green border border-bambu-green/30":"bg-bambu-gray/10 text-bambu-gray border border-bambu-gray/30"}`,children:N?n("printers.firmwareModal.installed"):C.file_available?n("printers.firmwareModal.usable"):n("printers.firmwareModal.unavailable")})]},C.version)})})]}),g?x?r.jsxs("div",{className:"flex items-center gap-2 text-bambu-gray text-sm mb-4",children:[r.jsx(lt,{className:"w-4 h-4 animate-spin"}),n("printers.firmwareModal.checkingPrereqs")]}):b&&!u&&!c?r.jsx("div",{className:"mb-4",children:b.can_proceed?r.jsxs("div",{className:"flex items-center gap-2 text-bambu-green text-sm",children:[r.jsx(Ei,{className:"w-4 h-4"}),n("printers.firmwareModal.sdCardReady")]}):r.jsx("div",{className:"space-y-1",children:b.errors.map((C,N)=>r.jsxs("div",{className:"flex items-center gap-2 text-red-400 text-sm",children:[r.jsx(Sn,{className:"w-4 h-4 flex-shrink-0"}),C]},N))})}):null:null,(u||c)&&c&&r.jsxs("div",{className:"mb-4",children:[r.jsxs("div",{className:"flex items-center justify-between text-sm mb-1",children:[r.jsx("span",{className:"text-bambu-gray capitalize",children:c.status}),r.jsxs("span",{className:"text-white",children:[c.progress,"%"]})]}),r.jsx("div",{className:"w-full bg-bambu-dark-tertiary rounded-full h-2",children:r.jsx("div",{className:`h-2 rounded-full transition-all ${c.status==="error"?"bg-status-error":c.status==="complete"?"bg-status-ok":"bg-orange-500"} ${c.status==="uploading"?"animate-pulse":""}`,style:{width:`${c.progress}%`}})}),r.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:c.message}),c.error&&r.jsx("p",{className:"text-xs text-red-400 mt-1",children:c.error})]}),c?.status==="complete"&&r.jsxs("div",{className:"bg-bambu-green/10 border border-bambu-green/30 rounded-lg p-3 mb-4",children:[r.jsx("p",{className:"text-sm text-bambu-green font-medium mb-2",children:n("printers.firmwareModal.uploadedSuccess")}),r.jsx("p",{className:"text-xs text-bambu-gray",children:n("printers.firmwareModal.applyInstructions")}),r.jsxs("ol",{className:"text-xs text-bambu-gray mt-1 list-decimal list-inside space-y-1",children:[r.jsx("li",{dangerouslySetInnerHTML:{__html:n("printers.firmwareModal.step1")}}),r.jsx("li",{dangerouslySetInnerHTML:{__html:n("printers.firmwareModal.step2")}}),r.jsx("li",{dangerouslySetInnerHTML:{__html:n("printers.firmwareModal.step3")}}),r.jsx("li",{children:n("printers.firmwareModal.step4")})]})]}),r.jsxs("div",{className:"flex gap-2 justify-end",children:[r.jsx(Le,{variant:"secondary",onClick:a,children:c?.status==="complete"?n("printers.firmwareModal.done"):n("common.cancel")}),b?.can_proceed&&!u&&c?.status!=="complete"&&l&&r.jsx(Le,{onClick:k,disabled:S.isPending,children:S.isPending?r.jsxs(r.Fragment,{children:[r.jsx(lt,{className:"w-4 h-4 animate-spin mr-2"}),n("printers.firmwareModal.starting")]}):r.jsxs(r.Fragment,{children:[r.jsx(Ur,{className:"w-4 h-4 mr-2"}),n("printers.firmwareModal.uploadFirmware")]})})]})]})})})}function s7e({printer:t,onClose:e}){const{t:a}=wt(),n=na(),{showToast:i}=oa(),[s,o]=y.useState({name:t.name,ip_address:t.ip_address,access_code:"",model:t.model||"",location:t.location||"",auto_archive:t.auto_archive}),[l,c]=y.useState(!1),[d,u]=y.useState(null),m=at({mutationFn:g=>ne.updatePrinter(t.id,g),onSuccess:()=>{n.invalidateQueries({queryKey:["printers"]}),n.invalidateQueries({queryKey:["printerStatus",t.id]}),e()},onError:g=>i(g.message||a("printers.toast.failedToUpdate"),"error")});y.useEffect(()=>{const g=v=>{v.key==="Escape"&&e()};return window.addEventListener("keydown",g),()=>window.removeEventListener("keydown",g)},[e]);const p=()=>{const g={name:s.name,ip_address:s.ip_address,model:s.model||void 0,location:s.location||void 0,auto_archive:s.auto_archive};s.access_code&&(g.access_code=s.access_code),m.mutate(g)},f=async g=>{g.preventDefault(),c(!0);try{const v=await ne.diagnoseConnection({ip_address:s.ip_address.trim(),serial_number:t.serial_number,access_code:s.access_code||void 0});if(v.checks.some(b=>b.status==="fail")){u(v);return}}catch{}finally{c(!1)}p()};return r.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-start sm:items-center justify-center z-50 p-4 overflow-y-auto",onClick:e,children:r.jsx(Tt,{className:"w-full max-w-md my-auto max-h-[calc(100vh-2rem)] overflow-y-auto",onClick:g=>g.stopPropagation(),children:r.jsxs(jt,{children:[r.jsx("h2",{className:"text-xl font-semibold mb-4",children:a("printers.editPrinter")}),r.jsxs("form",{onSubmit:f,className:"space-y-4",children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("printers.name")}),r.jsx("input",{type:"text",required:!0,className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:s.name,onChange:g=>o({...s,name:g.target.value}),placeholder:a("printers.modal.myPrinter")})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("printers.ipAddress")}),r.jsx("input",{type:"text",required:!0,pattern:"(\\d{1,3}(\\.\\d{1,3}){3}|[a-zA-Z0-9]([a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])?(\\.[a-zA-Z0-9]([a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])?)*)",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:s.ip_address,onChange:g=>o({...s,ip_address:g.target.value}),placeholder:"192.168.1.100 or printer.local"})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("printers.serialNumber")}),r.jsx("input",{type:"text",disabled:!0,className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-bambu-gray cursor-not-allowed",value:t.serial_number}),r.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:a("printers.serialCannotBeChanged")})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("printers.accessCode")}),r.jsx("input",{type:"password",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:s.access_code,onChange:g=>o({...s,access_code:g.target.value}),placeholder:a("printers.accessCodePlaceholder")})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("printers.model")}),r.jsxs("select",{className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:s.model,onChange:g=>o({...s,model:g.target.value}),children:[r.jsx("option",{value:"",children:a("printers.modal.selectModel")}),r.jsxs("optgroup",{label:"H2 Series",children:[r.jsx("option",{value:"H2C",children:"H2C"}),r.jsx("option",{value:"H2D",children:"H2D"}),r.jsx("option",{value:"H2D Pro",children:"H2D Pro"}),r.jsx("option",{value:"H2S",children:"H2S"})]}),r.jsx("optgroup",{label:"X2 Series",children:r.jsx("option",{value:"X2D",children:"X2D"})}),r.jsxs("optgroup",{label:"X1 Series",children:[r.jsx("option",{value:"X1E",children:"X1E"}),r.jsx("option",{value:"X1C",children:"X1 Carbon"}),r.jsx("option",{value:"X1",children:"X1"})]}),r.jsxs("optgroup",{label:"P Series",children:[r.jsx("option",{value:"P2S",children:"P2S"}),r.jsx("option",{value:"P1S",children:"P1S"}),r.jsx("option",{value:"P1P",children:"P1P"})]}),r.jsxs("optgroup",{label:"A1 Series",children:[r.jsx("option",{value:"A1",children:"A1"}),r.jsx("option",{value:"A1 Mini",children:"A1 Mini"})]})]})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Location / Group"}),r.jsx("input",{type:"text",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:s.location,onChange:g=>o({...s,location:g.target.value}),placeholder:a("printers.modal.locationPlaceholder")}),r.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:a("printers.locationHelp")})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("input",{type:"checkbox",id:"edit_auto_archive",checked:s.auto_archive,onChange:g=>o({...s,auto_archive:g.target.checked}),className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),r.jsx("label",{htmlFor:"edit_auto_archive",className:"text-sm text-bambu-gray",children:a("printers.modal.autoArchiveLabel")})]}),d?r.jsxs("div",{className:"rounded-lg bg-amber-500/10 border border-amber-500/30 p-3 space-y-3",children:[r.jsxs("div",{className:"flex items-start gap-2",children:[r.jsx(xa,{className:"w-4 h-4 mt-0.5 flex-shrink-0 text-amber-400"}),r.jsx("p",{className:"text-sm text-amber-300",children:a("printers.addPreflight.warning")})]}),r.jsx(U1,{result:d}),r.jsxs("div",{className:"flex gap-3",children:[r.jsx(Le,{type:"button",variant:"secondary",onClick:()=>u(null),className:"flex-1",children:a("printers.addPreflight.back")}),r.jsx(Le,{type:"button",onClick:p,className:"flex-1",disabled:m.isPending,children:a("printers.addPreflight.saveAnyway")})]})]}):r.jsxs("div",{className:"flex gap-3 pt-4",children:[r.jsx(Le,{type:"button",variant:"secondary",onClick:e,className:"flex-1",children:a("common.cancel")}),r.jsx(Le,{type:"submit",className:"flex-1",disabled:m.isPending||l,children:l?a("printers.addPreflight.checking"):m.isPending?a("common.saving"):a("printers.modal.saveChanges")})]})]})]})})})}function o7e(t){const{data:e}=$e({queryKey:["printerStatus",t],queryFn:()=>ne.getPrinterStatus(t),refetchInterval:3e4});return!e?.connected}function l7e({printer:t,plug:e,onPowerOn:a,isPowering:n}){const i=o7e(t.id),{data:s}=$e({queryKey:["smartPlugStatus",e.id],queryFn:()=>ne.getSmartPlugStatus(e.id),refetchInterval:1e4});return i?r.jsxs("div",{className:"flex items-center justify-between px-3 py-2 hover:bg-gray-100 dark:hover:bg-bambu-dark-tertiary",children:[r.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[r.jsx("span",{className:"text-sm text-gray-900 dark:text-white truncate",children:t.name}),s&&r.jsx("span",{className:`text-xs px-1.5 py-0.5 rounded ${s.state==="ON"?"bg-bambu-green/20 text-bambu-green":"bg-red-500/20 text-red-400"}`,children:s.state||"?"})]}),r.jsxs("button",{onClick:()=>a(e.id),disabled:n||s?.state==="ON",className:`px-2 py-1 text-xs rounded transition-colors flex items-center gap-1 ${s?.state==="ON"?"bg-bambu-green/20 text-bambu-green cursor-default":"bg-bambu-green/20 text-bambu-green hover:bg-bambu-green hover:text-white"}`,children:[r.jsx(Tu,{className:"w-3 h-3"}),n?"...":"On"]})]}):null}function c7e(){const{t}=wt(),[e,a]=y.useState(!1),[n,i]=y.useState(()=>localStorage.getItem("hideDisconnectedPrinters")==="true"),[s,o]=y.useState(!1),[l,c]=y.useState(null),[d,u]=y.useState(()=>localStorage.getItem("printerSortBy")||"name"),[m,p]=y.useState(()=>localStorage.getItem("printerSortAsc")!=="false"),[f,g]=y.useState(()=>{const ot=localStorage.getItem("printerCardSize");return ot?parseInt(ot,10):2}),v=f===1?"compact":"expanded",[b,x]=y.useState(""),[S,k]=y.useState("all"),[C,N]=y.useState("all"),[T,j]=y.useState(0),[D,P]=y.useState(()=>{try{const ot=localStorage.getItem("printerCollapsedSections");return ot?JSON.parse(ot):{}}catch{return{}}}),E=na(),{showToast:z}=oa(),{hasPermission:I}=lr(),[B,R]=y.useState(()=>{const ot=localStorage.getItem("openEmbeddedCameras");if(ot)try{const vt=JSON.parse(ot);return new Map(vt.map(Ct=>[Ct.id,Ct]))}catch{return new Map}return new Map});y.useEffect(()=>{const ot=Array.from(B.values());ot.length>0?localStorage.setItem("openEmbeddedCameras",JSON.stringify(ot)):localStorage.removeItem("openEmbeddedCameras")},[B]);const{data:K,isLoading:J}=$e({queryKey:["printers"],queryFn:ne.getPrinters}),{data:X}=$e({queryKey:["ui-preferences"],queryFn:ne.getUiPreferences}),ce=y.useMemo(()=>{if(X?.drying_presets)try{const ot=JSON.parse(X.drying_presets);if(typeof ot=="object"&&ot!==null&&Object.keys(ot).length>0)return{...Nz,...ot}}catch{}return Nz},[X?.drying_presets]);y.useEffect(()=>{X?.camera_view_mode==="window"&&B.size>0&&R(new Map)},[X?.camera_view_mode,B.size]);const{data:de}=$e({queryKey:["smart-plugs"],queryFn:ne.getSmartPlugs}),{data:oe}=$e({queryKey:["maintenanceOverview"],queryFn:ne.getMaintenanceOverview,staleTime:60*1e3}),{data:Y}=$e({queryKey:["spoolman-status"],queryFn:ne.getSpoolmanStatus,staleTime:60*1e3}),ie=Y?.enabled&&Y?.connected,{data:me}=$e({queryKey:["spoolman-settings"],queryFn:ne.getSpoolmanSettings,enabled:!!ie,staleTime:60*1e3}),he=me?.spoolman_sync_mode,{data:xe}=$e({queryKey:["unlinked-spools"],queryFn:ne.getUnlinkedSpools,enabled:!!ie,staleTime:30*1e3}),V=xe&&xe.length>0,{data:Q}=$e({queryKey:["linked-spools"],queryFn:ne.getLinkedSpools,enabled:!!ie,staleTime:30*1e3}),A=Q?.linked,{data:F}=$e({queryKey:["spool-assignments"],queryFn:()=>ne.getAssignments(),enabled:I("inventory:view_assignments"),staleTime:30*1e3}),U=at({mutationFn:({printerId:ot,amsId:vt,trayId:Ct})=>ne.unassignSpool(ot,vt,Ct),onSuccess:()=>{E.invalidateQueries({queryKey:["spool-assignments"]})}}),{data:$,isLoading:H}=$e({queryKey:["spoolman-inventory-spools"],queryFn:()=>ne.getSpoolmanInventorySpools(!1),enabled:!!ie,staleTime:30*1e3}),{data:le,isLoading:O}=$e({queryKey:["spoolman-slot-assignments"],queryFn:()=>ne.getSpoolmanSlotAssignments(),enabled:!!ie,staleTime:30*1e3}),q=at({mutationFn:ot=>ne.unassignSpoolmanSlot(ot),onSuccess:()=>{E.invalidateQueries({queryKey:["spoolman-inventory-spools"]}),E.invalidateQueries({queryKey:["spoolman-slot-assignments"]})}}),Z=(ot,vt,Ct)=>F?.find(ea=>ea.printer_id===ot&&ea.ams_id===Number(vt)&&ea.tray_id===Number(Ct)),ee=oe?.reduce((ot,vt)=>(ot[vt.printer_id]={due_count:vt.due_count,warning_count:vt.warning_count,total_print_hours:vt.total_print_hours},ot),{})||{},re=de?.reduce((ot,vt)=>(vt.printer_id&&(ot[vt.printer_id]=vt),ot),{})||{},se=at({mutationFn:ne.createPrinter,onSuccess:()=>{E.invalidateQueries({queryKey:["printers"]}),E.invalidateQueries({queryKey:["maintenanceOverview"]}),a(!1)},onError:ot=>{if(ot instanceof Hi&&ot.code==="printer_connection_failed"){z(t("printers.toast.connectionFailedNotAdded"),"error");return}z(ot.message||t("printers.toast.failedToAdd"),"error")}}),fe=at({mutationFn:ot=>ne.controlSmartPlug(ot,"on"),onSuccess:()=>{E.invalidateQueries({queryKey:["smart-plugs"]}),c(null)},onError:()=>{c(null)}}),[ue,pe]=y.useState(new Set),[G,L]=y.useState(!1),[ae,ge]=y.useState(null),[be,ve]=y.useState(!1),De=G||ue.size>0,je=y.useCallback(ot=>{pe(vt=>{const Ct=new Set(vt);return Ct.has(ot)?Ct.delete(ot):Ct.add(ot),Ct})},[]),Te=y.useCallback(()=>{pe(new Set),L(!1)},[]);y.useEffect(()=>{const ot=vt=>{vt.key==="Escape"&&De&&Te()};return window.addEventListener("keydown",ot),()=>window.removeEventListener("keydown",ot)},[De,Te]);const qe=y.useCallback(async ot=>{ve(!0);const Ct=Array.from(ue).filter(it=>{const Ae=E.getQueryData(["printerStatus",it]);if(!Ae?.connected)return!1;switch(ot){case"stop":return Ae.state==="RUNNING"||Ae.state==="PAUSE";case"pause":return Ae.state==="RUNNING";case"resume":return Ae.state==="PAUSE";case"clearPlate":return!!Ae.awaiting_plate_clear;case"clearHMS":return Ae.hms_errors&&Bm(Ae.hms_errors).length>0;default:return!1}});if(Ct.length===0){z(t("printers.bulk.noneApplicable"),"error"),ve(!1),ge(null);return}const ea={stop:ne.stopPrint,pause:ne.pausePrint,resume:ne.resumePrint,clearPlate:ne.clearPlate,clearHMS:ne.clearHMSErrors}[ot],aa=await Promise.allSettled(Ct.map(it=>ea(it))),Pe=aa.filter(it=>it.status==="fulfilled").length,Ye=aa.filter(it=>it.status==="rejected").length;Ye===0?z(t("printers.bulk.success",{action:t(`printers.bulk.actions.${ot}`),count:Pe})):z(t("printers.bulk.partial",{succeeded:Pe,failed:Ye}),"error"),Ct.forEach(it=>{E.invalidateQueries({queryKey:["printerStatus",it]})}),ve(!1),ge(null)},[ue,E,z,t]),Ce=y.useCallback(ot=>{ot==="stop"||ot==="pause"||ot==="clearPlate"?ge(ot):qe(ot)},[qe]),Ie=()=>{const ot=!n;i(ot),localStorage.setItem("hideDisconnectedPrinters",String(ot))},Re=ot=>{u(ot),localStorage.setItem("printerSortBy",ot)},Ue=()=>{const ot=!m;p(ot),localStorage.setItem("printerSortAsc",String(ot))},ze=()=>{switch(f){case 1:return"grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5";case 2:return"grid-cols-1 md:grid-cols-2 xl:grid-cols-3";case 3:return"grid-cols-1 lg:grid-cols-2";case 4:return"grid-cols-1";default:return"grid-cols-1 md:grid-cols-2 xl:grid-cols-3"}},nt=["S","M","L","XL"];y.useEffect(()=>E.getQueryCache().subscribe(vt=>{vt.type==="updated"&&Array.isArray(vt.query.queryKey)&&vt.query.queryKey[0]==="printerStatus"&&j(Ct=>Ct+1)}),[E]);const Oe=y.useMemo(()=>{if(!K)return[];let ot=K;if(b.trim()){const vt=b.trim().toLowerCase();ot=ot.filter(Ct=>Ct.name.toLowerCase().includes(vt)||(Ct.model||"").toLowerCase().includes(vt)||(Ct.location||"").toLowerCase().includes(vt)||(Ct.serial_number||"").toLowerCase().includes(vt))}return C!=="all"&&(ot=ot.filter(vt=>(vt.location||"")===C)),S!=="all"&&(ot=ot.filter(vt=>{const Ct=E.getQueryData(["printerStatus",vt.id]);if(!Ct?.connected)return S==="offline";const ea=Ct.hms_errors?Bm(Ct.hms_errors):[];switch(S){case"printing":return Ct.state==="RUNNING";case"paused":return Ct.state==="PAUSE";case"finished":return Ct.state==="FINISH";case"error":return Ct.state==="FAILED"||ea.length>0;case"idle":return Ct.state!=="RUNNING"&&Ct.state!=="PAUSE"&&Ct.state!=="FINISH"&&Ct.state!=="FAILED"&&ea.length===0;case"offline":return!1;default:return!0}})),ot},[K,b,S,C,E,T]),tt=y.useMemo(()=>K?[...new Set(K.map(ot=>ot.location||"").filter(Boolean))].sort():[],[K]),Fe=y.useMemo(()=>{const ot=[...Oe];switch(d){case"name":ot.sort((vt,Ct)=>vt.name.localeCompare(Ct.name));break;case"model":ot.sort((vt,Ct)=>(vt.model||"").localeCompare(Ct.model||""));break;case"location":ot.sort((vt,Ct)=>{const ea=vt.location||"",aa=Ct.location||"";return!ea&&aa?1:ea&&!aa?-1:ea.localeCompare(aa)||vt.name.localeCompare(Ct.name)});break;case"status":ot.sort((vt,Ct)=>{const ea=E.getQueryData(["printerStatus",vt.id]),aa=E.getQueryData(["printerStatus",Ct.id]),Pe=Ye=>Ye?.connected?(Ye.hms_errors?Bm(Ye.hms_errors):[]).length>0?0:Ye.state==="RUNNING"?1:2:3;return Pe(ea)-Pe(aa)});break}return m||ot.reverse(),ot},[Oe,d,m,E]),Ke=y.useCallback(()=>{pe(new Set(Fe.map(ot=>ot.id))),L(!0)},[Fe]),Ve=y.useCallback(ot=>{pe(vt=>{const Ct=new Set(vt);return Fe.forEach(ea=>{const aa=E.getQueryData(["printerStatus",ea.id]);_Y(aa)===ot&&Ct.add(ea.id)}),Ct}),L(!0)},[Fe,E]),Me=y.useCallback(ot=>{pe(vt=>{const Ct=new Set(vt);return Fe.filter(ea=>(ea.location||"")===ot).forEach(ea=>Ct.add(ea.id)),Ct}),L(!0)},[Fe]),Be=y.useCallback(ot=>{pe(vt=>{const Ct=new Set(vt);return Fe.filter(ea=>(ea.model||"Unknown")===ot).forEach(ea=>Ct.add(ea.id)),Ct}),L(!0)},[Fe]),Qe=y.useCallback(ot=>{P(vt=>{const Ct={...vt,[ot]:!vt[ot]};try{localStorage.setItem("printerCollapsedSections",JSON.stringify(Ct))}catch{}return Ct})},[]),Ge=y.useMemo(()=>{if(d==="name")return null;const ot={};return d==="location"?Fe.forEach(vt=>{const Ct=vt.location||"Ungrouped";ot[Ct]||(ot[Ct]=[]),ot[Ct].push(vt)}):d==="model"?Fe.forEach(vt=>{const Ct=vt.model||"Unknown";ot[Ct]||(ot[Ct]=[]),ot[Ct].push(vt)}):d==="status"&&Fe.forEach(vt=>{const Ct=E.getQueryData(["printerStatus",vt.id]),ea=_Y(Ct);ot[ea]||(ot[ea]=[]),ot[ea].push(vt)}),ot},[d,Fe,E,T]),Ee=y.useRef(null),rt=y.useRef(null),Xe=y.useRef(0),[Nt,Vt]=y.useState(!1),ht=y.useCallback(()=>{const ot=Ee.current;if(!ot)return;const vt=rt.current?.offsetWidth;vt&&(Xe.current=vt);const aa=Xe.current>0&&ot.clientWidthPe===aa?Pe:aa)},[]),It=Object.keys(re).length;y.useLayoutEffect(()=>{ht();const ot=Ee.current;if(!ot)return;if(typeof ResizeObserver>"u")return window.addEventListener("resize",ht),()=>window.removeEventListener("resize",ht);const vt=new ResizeObserver(()=>ht());return vt.observe(ot),window.addEventListener("resize",ht),()=>{vt.disconnect(),window.removeEventListener("resize",ht)}},[ht,K?.length,tt.length,n,It]);const Xt=(ot=!1)=>r.jsxs(r.Fragment,{children:[K&&K.length>0&&r.jsx(FF,{value:S,onChange:k,fullWidth:ot,options:[{value:"all",label:t("printers.filter.allStatuses")},{value:"printing",label:t("printers.status.printing")},{value:"paused",label:t("printers.status.paused")},{value:"idle",label:t("printers.status.idle")},{value:"finished",label:t("printers.status.finished")},{value:"error",label:t("printers.status.error")},{value:"offline",label:t("printers.status.offline")}]}),K&&K.length>0&&tt.length>0&&r.jsx(FF,{value:C,onChange:N,fullWidth:ot,options:[{value:"all",label:t("printers.filter.allLocations")},...tt.map(vt=>({value:vt,label:vt}))]}),r.jsx("button",{type:"button",onClick:Ie,"aria-pressed":n,className:`h-8 px-2 rounded-lg border text-sm font-medium transition-colors ${ot?"w-full":""} ${n?"bg-bambu-green border-bambu-green text-white":"bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary"}`,children:t("printers.hideOffline")})]}),la=(ot=!1)=>r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:`flex items-center gap-1 ${ot?"w-full":""}`,children:[r.jsx(FF,{value:d,onChange:Re,fullWidth:ot,options:[{value:"name",label:t("printers.sort.name")},{value:"status",label:t("printers.sort.status")},{value:"model",label:t("printers.sort.model")},{value:"location",label:t("printers.sort.location")}]}),r.jsx("button",{onClick:Ue,className:"h-8 shrink-0 px-2 rounded-lg border bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary transition-colors flex items-center justify-center",title:t(m?"printers.sort.descending":"printers.sort.ascending"),children:m?r.jsx(Qm,{className:"w-4 h-4 text-white"}):r.jsx(Qh,{className:"w-4 h-4 text-white"})})]}),r.jsx("div",{className:`flex h-8 items-center bg-bambu-dark rounded-lg border border-bambu-dark-tertiary ${ot?"w-full":""}`,children:nt.map((vt,Ct)=>{const ea=Ct+1,aa=f===ea;return r.jsx("button",{onClick:()=>{g(ea),localStorage.setItem("printerCardSize",String(ea))},className:`h-full px-2 text-xs font-medium transition-colors ${ot?"flex-1":""} ${Ct===0?"rounded-l-lg":""} ${Ct===nt.length-1?"rounded-r-lg":""} ${aa?"bg-bambu-green text-white":"text-white hover:bg-bambu-dark-tertiary"}`,title:t(vt==="S"?"printers.cardSize.small":vt==="M"?"printers.cardSize.medium":vt==="L"?"printers.cardSize.large":"printers.cardSize.extraLarge"),children:vt},vt)})})]}),ca=(ot=!1)=>r.jsxs(r.Fragment,{children:[r.jsxs("button",{onClick:()=>{De?Te():L(!0)},className:`h-8 px-2 rounded-lg border transition-colors ${ot?"w-full justify-center gap-1.5 text-sm font-medium flex items-center":""} ${De?"bg-bambu-green border-bambu-green text-white":"bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary"}`,title:t("printers.bulk.select"),disabled:!I("printers:control"),children:[r.jsx(xs,{className:"w-4 h-4"}),ot&&r.jsx("span",{children:t("printers.bulk.select")})]}),n&&Object.keys(re).length>0&&r.jsxs("div",{className:`relative ${ot?"w-full":""}`,children:[r.jsxs("button",{onClick:()=>o(!s),className:`h-8 flex items-center gap-1.5 px-2 text-sm rounded-lg border transition-colors ${ot?"w-full justify-between bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary hover:text-white":"bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary"}`,children:[r.jsxs("span",{className:"flex items-center gap-1.5",children:[r.jsx(Tu,{className:"w-4 h-4"}),t("printers.powerOn")]}),r.jsx(za,{className:`w-3 h-3 transition-transform ${s?"rotate-180":""}`})]}),s&&r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>o(!1)}),r.jsxs("div",{className:"absolute right-0 mt-2 w-56 bg-white dark:bg-bambu-dark-secondary border border-gray-200 dark:border-bambu-dark-tertiary rounded-lg shadow-lg z-20 py-1",children:[r.jsx("div",{className:"px-3 py-2 text-xs text-gray-500 dark:text-bambu-gray border-b border-gray-200 dark:border-bambu-dark-tertiary",children:t("printers.offlinePrintersWithPlugs")}),K?.filter(vt=>re[vt.id]).map(vt=>r.jsx(l7e,{printer:vt,plug:re[vt.id],onPowerOn:Ct=>{c(Ct),fe.mutate(Ct)},isPowering:l===re[vt.id]?.id},vt.id)),K?.filter(vt=>re[vt.id]).length===0&&r.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:"No printers with smart plugs"})]})]})]}),r.jsxs(Le,{onClick:()=>a(!0),disabled:!I("printers:create"),title:I("printers:create")?void 0:t("printers.permission.noAdd"),className:`!h-8 !min-h-8 px-2 py-0 ${ot?"w-full":""}`,children:[r.jsx(or,{className:"w-4 h-4"}),t("printers.addPrinter")]})]});return r.jsxs("div",{className:"p-4 md:p-8",children:[r.jsxs("div",{className:"space-y-3 mb-6",children:[r.jsxs("div",{children:[r.jsxs("h1",{className:"text-2xl font-bold text-white flex items-center gap-3",children:[r.jsx(xr,{className:"w-7 h-7 text-bambu-green"}),t("printers.title")]}),r.jsx(a7e,{printers:K})]}),r.jsxs("div",{ref:Ee,className:"relative flex items-center gap-2",children:[K&&K.length>0&&r.jsxs("div",{className:"relative min-w-0 flex-1",children:[r.jsx(br,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50"}),r.jsx("input",{type:"search",name:"printer-search",autoComplete:"off","data-1p-ignore":!0,"data-lpignore":"true",value:b,onChange:ot=>x(ot.target.value),placeholder:t("printers.search"),"aria-label":t("printers.search"),className:"w-full h-8 pl-9 pr-8 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green"}),b&&r.jsx("button",{type:"button","aria-label":t("common.clear"),onClick:()=>x(""),className:"absolute right-3 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white",children:r.jsx(Ht,{className:"w-4 h-4"})})]}),r.jsxs("div",{ref:rt,"aria-hidden":Nt,inert:Nt,className:`${Nt?"absolute -left-[9999px] top-0 flex w-max pointer-events-none opacity-0":"flex"} ml-auto items-center justify-end gap-2 flex-nowrap [&>*]:shrink-0`,children:[r.jsx("div",{className:"h-6 w-px bg-bambu-dark-tertiary"}),r.jsx("div",{className:"flex items-center gap-2",children:Xt()}),r.jsx("div",{className:"h-6 w-px bg-bambu-dark-tertiary"}),r.jsx("div",{className:"flex items-center gap-2",children:la()}),r.jsx("div",{className:"h-6 w-px bg-bambu-dark-tertiary"}),r.jsx("div",{className:"flex items-center gap-2",children:ca()})]}),Nt&&r.jsxs("div",{className:"ml-auto flex items-center justify-end gap-1",children:[r.jsx(LF,{label:t("printers.toolbar.filters","Filters"),icon:r.jsx(av,{className:"w-4 h-4"}),children:r.jsx("div",{className:"flex w-48 flex-col gap-2",children:Xt(!0)})}),r.jsx(LF,{label:t("printers.toolbar.view","View"),icon:r.jsx(xve,{className:"w-4 h-4"}),children:r.jsx("div",{className:"flex w-48 flex-col gap-2",children:la(!0)})}),r.jsx(LF,{label:t("printers.toolbar.actions","Actions"),icon:r.jsx(Ibe,{className:"w-4 h-4"}),children:r.jsx("div",{className:"flex w-48 flex-col gap-2",children:ca(!0)})})]})]})]}),J?r.jsx("div",{className:"text-center py-12 text-bambu-gray",children:t("common.loading")}):K?.length===0?r.jsx(Tt,{children:r.jsxs(jt,{className:"text-center py-12",children:[r.jsx("p",{className:"text-bambu-gray mb-4",children:t("printers.noPrintersConfigured")}),r.jsxs(Le,{onClick:()=>a(!0),disabled:!I("printers:create"),title:I("printers:create")?void 0:t("printers.permission.noAdd"),children:[r.jsx(or,{className:"w-4 h-4"}),t("printers.addPrinter")]})]})}):Fe.length===0&&(b.trim()||S!=="all"||C!=="all")?r.jsx(Tt,{children:r.jsx(jt,{className:"text-center py-12",children:r.jsx("p",{className:"text-bambu-gray",children:t("printers.noSearchResults")})})}):Ge?r.jsx("div",{className:"space-y-6",children:(()=>{const ot=d==="status"?r7e.filter(vt=>Ge[vt]?.length>0):Object.keys(Ge);return m?ot:[...ot].reverse()})().map(ot=>{const vt=Ge[ot],Ct=`${d}:${ot}`,ea=!D[Ct],aa=d==="status"&&kY[ot]?.dot||"bg-bambu-green",Pe=d==="status"?t(kY[ot]?.labelKey||ot):ot;return r.jsx(H1,{open:ea,onToggle:()=>Qe(Ct),summaryClassName:"py-1",summary:r.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[r.jsx("span",{className:`w-2 h-2 rounded-full ${aa}`}),Pe,r.jsxs("span",{className:"text-sm font-normal text-bambu-gray",children:["(",vt.length,")"]}),De&&r.jsx("button",{onClick:Ye=>{Ye.stopPropagation(),d==="location"?Me(ot==="Ungrouped"?"":ot):d==="status"?Ve(ot):d==="model"&&Be(ot)},className:"text-xs text-bambu-green hover:text-bambu-green-light transition-colors ml-1",children:t("printers.bulk.selectAll")})]}),children:r.jsx("div",{className:`grid gap-4 ${f>=3?"gap-6":""} ${ze()}`,children:vt.map(Ye=>r.jsx(CY,{printer:Ye,hideIfDisconnected:n,maintenanceInfo:ee[Ye.id],viewMode:v,cardSize:f,amsThresholds: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,spoolmanEnabled:ie,hasUnlinkedSpools:V,linkedSpools:A,spoolmanUrl:Y?.url,spoolmanSyncMode:he,onGetAssignment:Z,onUnassignSpool:(it,Ae,Se)=>U.mutate({printerId:it,amsId:Ae,trayId:Se}),spoolmanSpools:$,spoolmanSlotAssignments:le,spoolmanLoading:H||O,onUnassignSpoolmanSpool:it=>q.mutate(it),timeFormat:X?.time_format||"system",cameraViewMode:X?.camera_view_mode||"window",onOpenEmbeddedCamera:(it,Ae)=>R(Se=>new Map(Se).set(it,{id:it,name:Ae})),checkPrinterFirmware:X?.check_printer_firmware!==!1,dryingPresets:ce,requirePlateClear:X?.require_plate_clear===!0,selectionMode:De,isSelected:ue.has(Ye.id),onToggleSelect:je},Ye.id))})},ot)})}):r.jsx("div",{className:`grid gap-4 ${f>=3?"gap-6":""} ${ze()}`,children:Fe.map(ot=>r.jsx(CY,{printer:ot,hideIfDisconnected:n,maintenanceInfo:ee[ot.id],viewMode:v,cardSize:f,spoolmanEnabled:ie,hasUnlinkedSpools:V,linkedSpools:A,spoolmanUrl:Y?.url,spoolmanSyncMode:he,onGetAssignment:Z,onUnassignSpool:(vt,Ct,ea)=>U.mutate({printerId:vt,amsId:Ct,trayId:ea}),spoolmanSpools:$,spoolmanSlotAssignments:le,spoolmanLoading:H||O,onUnassignSpoolmanSpool:vt=>q.mutate(vt),amsThresholds: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,timeFormat:X?.time_format||"system",cameraViewMode:X?.camera_view_mode||"window",onOpenEmbeddedCamera:(vt,Ct)=>R(ea=>new Map(ea).set(vt,{id:vt,name:Ct})),checkPrinterFirmware:X?.check_printer_firmware!==!1,dryingPresets:ce,requirePlateClear:X?.require_plate_clear===!0,selectionMode:De,isSelected:ue.has(ot.id),onToggleSelect:je},ot.id))}),e&&r.jsx(n7e,{onClose:()=>a(!1),onAdd:ot=>se.mutate(ot),existingSerials:K?.map(ot=>ot.serial_number)||[]}),De&&K&&r.jsx(ewe,{selectedIds:ue,printers:K,onClose:Te,onSelectAll:Ke,onSelectByLocation:Me,onSelectByState:Ve,onAction:Ce,actionPending:be}),ae==="stop"&&r.jsx(ka,{title:t("printers.bulk.confirm.stopTitle",{count:ue.size}),message:t("printers.bulk.confirm.stopMessage",{count:ue.size}),confirmText:t("printers.bulk.confirm.stopButton"),variant:"danger",isLoading:be,onConfirm:()=>qe("stop"),onCancel:()=>ge(null)}),ae==="pause"&&r.jsx(ka,{title:t("printers.bulk.confirm.pauseTitle",{count:ue.size}),message:t("printers.bulk.confirm.pauseMessage",{count:ue.size}),confirmText:t("printers.bulk.confirm.pauseButton"),isLoading:be,onConfirm:()=>qe("pause"),onCancel:()=>ge(null)}),ae==="clearPlate"&&r.jsx(ka,{title:t("printers.bulk.confirm.clearPlateTitle",{count:ue.size}),message:t("printers.bulk.confirm.clearPlateMessage",{count:ue.size}),confirmText:t("printers.bulk.confirm.clearPlateButton"),isLoading:be,onConfirm:()=>qe("clearPlate"),onCancel:()=>ge(null)}),Array.from(B.values()).map((ot,vt)=>r.jsx(a2e,{printerId:ot.id,printerName:ot.name,viewerIndex:vt,onClose:()=>R(Ct=>{const ea=new Map(Ct);return ea.delete(ot.id),ea})},ot.id))]})}function d7e({title:t,message:e,subtitle:a,closeText:n,variant:i="error",onClose:s}){const{t:o}=wt(),l=n??o("common.close");y.useEffect(()=>{const d=u=>{u.key==="Escape"&&s()};return window.addEventListener("keydown",d),()=>window.removeEventListener("keydown",d)},[s]);const c=i==="warning"?"text-yellow-400":"text-red-400";return r.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center p-4 z-[120]",onClick:s,children:r.jsx(Tt,{className:"w-full max-w-md",onClick:d=>d.stopPropagation(),children:r.jsxs(jt,{className:"p-6",children:[r.jsxs("div",{className:"flex items-start gap-4",children:[r.jsx("div",{className:`p-2 rounded-full bg-bambu-dark ${c}`,children:r.jsx(xa,{className:"w-6 h-6"})}),r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsx("h3",{className:"text-lg font-semibold text-white mb-1",children:t}),a&&r.jsx("p",{className:"text-xs text-bambu-gray mb-2 truncate",children:a}),r.jsx("p",{className:"text-bambu-gray text-sm whitespace-pre-line break-words",children:e})]})]}),r.jsx("div",{className:"flex mt-6",children:r.jsx(Le,{onClick:s,className:"flex-1",children:l})})]})})})}const Bse=y.createContext(null),u7e=1500,m7e=1e3,zF=t=>`slice-job-${t}`;function aC(t){try{return decodeURIComponent(t)}catch{return t}}function p7e(t){const e=Math.max(0,Math.floor(t));if(e<60)return`${e}s`;const a=Math.floor(e/60),n=e%60;if(a<60)return`${a}m ${n}s`;const i=Math.floor(a/60),s=a%60;return`${i}h ${s}m`}function h7e({children:t}){const{t:e}=wt(),{showToast:a,showPersistentToast:n,dismissToast:i}=oa(),s=na(),[o,l]=y.useState([]),[c,d]=y.useState(null),u=y.useRef([]);u.current=o;const m=y.useRef(new Map),p=y.useRef(new Map),f=y.useRef(new Map),g=y.useCallback(x=>{const S=m.current.get(x.id);if(S==null)return;const k=(Date.now()-S)/1e3,C=p.current.get(x.id)??"pending",N=p7e(k),T=f.current.get(x.id)??null,j=T&&T.stage&&T.total_percent>0;if(C==="running"&&j){const E=aC(x.sourceName),z=T.stage,I=Math.min(100,Math.max(0,Math.round(T.total_percent))),R=typeof T.multi_plate_index=="number"&&typeof T.multi_plate_count=="number"&&T.multi_plate_count>1?e("slice.runningWithProgressMultiPlate","Plate {{plateIndex}} of {{plateCount}} • {{name}} — {{stage}} ({{percent}}%) — {{elapsed}}",{plateIndex:T.multi_plate_index,plateCount:T.multi_plate_count,name:E,stage:z,percent:I,elapsed:N}):e("slice.runningWithProgress","{{name}} — {{stage}} ({{percent}}%) — {{elapsed}}",{name:E,stage:z,percent:I,elapsed:N});n(zF(x.id),R,"loading");return}const D=C==="pending"?"slice.queuedToast":"slice.runningToast",P=C==="pending"?"Queued: {{name}} — {{elapsed}}":"Slicing {{name}} — {{elapsed}}";n(zF(x.id),e(D,P,{name:aC(x.sourceName),elapsed:N}),"loading")},[n,e]),v=y.useCallback((x,S,k)=>{l(C=>C.some(N=>N.id===x)?C:[...C,{id:x,kind:S,sourceName:k}]),m.current.set(x,Date.now()),p.current.set(x,"pending"),f.current.set(x,null),g({id:x,kind:S,sourceName:k})},[g]),b=y.useCallback((x,S)=>{l(k=>k.filter(C=>C.id!==x.id)),m.current.delete(x.id),p.current.delete(x.id),f.current.delete(x.id),i(zF(x.id)),S.status==="completed"?a(e("slice.completedToast","Sliced {{name}}",{name:aC(x.sourceName)}),"success"):S.status==="failed"&&d({name:aC(x.sourceName),detail:S.error_detail||e("slice.failed")}),s.invalidateQueries({queryKey:["library-files"]}),s.invalidateQueries({queryKey:["archives"]})},[i,s,a,e]);return y.useEffect(()=>{if(o.length===0)return;let x=!1;const S=setInterval(async()=>{if(x)return;const k=[...u.current];for(const C of k)try{const N=await ne.getSliceJob(C.id);p.current.set(C.id,N.status),N.progress&&f.current.set(C.id,N.progress),(N.status==="completed"||N.status==="failed")&&b(C,N)}catch{}},u7e);return()=>{x=!0,clearInterval(S)}},[o.length,b]),y.useEffect(()=>{if(o.length===0)return;const x=setInterval(()=>{for(const S of u.current)g(S)},m7e);return()=>clearInterval(x)},[o.length,g]),r.jsxs(Bse.Provider,{value:{trackJob:v,activeJobs:o},children:[t,c&&r.jsx(d7e,{title:e("slice.failedTitle"),subtitle:c.name,message:c.detail,onClose:()=>d(null)})]})}function f7e(){const t=y.useContext(Bse);if(!t)throw new Error("useSliceJobTracker must be used inside SliceJobTrackerProvider");return t}function MB({plates:t,onSelect:e,onClose:a}){const{t:n}=wt();return r.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4",onClick:a,children:r.jsxs("div",{className:"w-full max-w-3xl max-h-[85vh] flex flex-col rounded-lg bg-bambu-dark-secondary border border-bambu-dark-tertiary/60",onClick:i=>i.stopPropagation(),children:[r.jsxs("div",{className:"flex-shrink-0 flex items-start justify-between gap-3 px-4 pt-4 pb-3 border-b border-bambu-dark-tertiary/40",children:[r.jsxs("div",{className:"min-w-0",children:[r.jsx("h3",{className:"text-white font-medium",children:n("archives.platePicker.title")}),r.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:n("archives.platePicker.hint")})]}),r.jsx("button",{onClick:a,className:"flex-shrink-0 text-bambu-gray hover:text-white transition-colors","aria-label":n("common.close","Close"),children:r.jsx(Ht,{className:"w-5 h-5"})})]}),r.jsx("div",{className:"flex-1 overflow-y-auto p-4",children:r.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2",children:t.map(i=>r.jsxs("button",{type:"button",onClick:()=>e(i.index),className:"flex items-center gap-2 p-2 rounded-lg border border-bambu-dark-tertiary bg-bambu-dark hover:border-bambu-gray transition-colors text-left",children:[i.has_thumbnail&&i.thumbnail_url!=null?r.jsx("img",{src:zn(i.thumbnail_url),alt:`Plate ${i.index}`,className:"w-12 h-12 rounded object-cover bg-bambu-dark-tertiary flex-shrink-0"}):r.jsx("div",{className:"w-12 h-12 rounded bg-bambu-dark-tertiary flex items-center justify-center flex-shrink-0",children:r.jsx(tn,{className:"w-5 h-5 text-bambu-gray"})}),r.jsxs("div",{className:"min-w-0 flex-1",children:[r.jsx("p",{className:"text-sm text-white font-medium truncate",children:i.name?`${n("archives.platePicker.plateLabel",{index:i.index})} — ${i.name}`:n("archives.platePicker.plateLabel",{index:i.index})}),r.jsxs("p",{className:"text-xs text-bambu-gray truncate",children:[i.objects.length>0?i.objects.slice(0,3).join(", ")+(i.objects.length>3?"…":""):i.object_count!=null&&i.object_count>0?n("archives.platePicker.objectCount",{count:i.object_count}):`${i.filaments.length} filament${i.filaments.length!==1?"s":""}`,i.print_time_seconds!=null?` • ${ds(i.print_time_seconds)}`:""]})]})]},i.index))})})]})})}const YA=["orca_cloud","local","cloud","standard"];function EB(t,e){for(const a of YA){const n=t[a][e];if(n.length>0)return{source:n[0].source,id:n[0].id}}return null}function $C(t,e,a){return e?t[e.source][a].find(n=>n.id===e.id)??null:null}function Use(t,e,a){if(!a)return null;for(const n of YA){const i=t[n][e].find(s=>s.name===a);if(i)return{source:i.source,id:i.id}}return null}function g7e(t,e,a,n){const i=Use(t,"process",n);if(i){const s=$C(t,i,"process");if(s&&Uy(s,"process",e,a)!=="mismatch")return i}for(const s of["match","unknown"])for(const o of YA)for(const l of t[o].process)if(Uy(l,"process",e,a)===s)return{source:l.source,id:l.id};return EB(t,"process")}const b7e={orca_cloud:1.75,local:1.5,cloud:1,standard:.5};function x7e(t,e,a,n){const i=e.type.trim().toUpperCase(),s=On(e.color);let o=null;for(const l of YA)for(const c of t[l].filament){let d=0;const u=(c.filament_type??"").trim().toUpperCase(),m=On(c.filament_colour??"");i&&u&&i===u&&(d+=10),s&&m&&(m===s?d+=5:fd(c.filament_colour??"",e.color)&&(d+=2)),d+=b7e[l],Uy(c,"filament",a,n)==="mismatch"&&(d-=100),(o==null||d>o.score)&&(o={ref:{source:c.source,id:c.id},score:d})}return o==null?EB(t,"filament"):o.ref}function y7e(t){return t?`${t.source}:${t.id}`:""}function v7e(t){if(!t)return null;const e=t.indexOf(":");if(e<0)return null;const a=t.slice(0,e),n=t.slice(e+1);return a!=="orca_cloud"&&a!=="cloud"&&a!=="local"&&a!=="standard"?null:{source:a,id:n}}function w7e({requestId:t,sourceName:e}){const{t:a}=wt(),{showPersistentToast:n,dismissToast:i}=oa(),[s,o]=y.useState(0),[l,c]=y.useState(null);let d=e;try{d=decodeURIComponent(e)}catch{}y.useEffect(()=>{const g=Date.now(),v=setInterval(()=>o(Math.floor((Date.now()-g)/1e3)),1e3);return()=>clearInterval(v)},[]),y.useEffect(()=>{let g=!1;const v=setInterval(async()=>{if(g)return;const b=await ne.getPreviewSliceProgress(t);!g&&b&&c(b)},1e3);return()=>{g=!0,clearInterval(v)}},[t]);const u=`slice-preview-${t}`;y.useEffect(()=>{const g=l&&l.stage&&l.total_percent>0,v=S7e(s);return g?n(u,a("slice.previewWithProgress","Analyzing {{name}} — {{stage}} ({{percent}}%) — {{elapsed}}",{name:d,stage:l.stage,percent:Math.min(100,Math.max(0,Math.round(l.total_percent))),elapsed:v}),"loading"):n(u,a("slice.previewToast",{name:d,elapsed:v}),"loading"),()=>{i(u)}},[s,l,d,n,i,a,u]);const m=l?.stage,p=l?.total_percent,f=m&&typeof p=="number"&&p>0?`${m} (${Math.min(100,Math.max(0,Math.round(p)))}%)`:a("slice.analyzingPlateFilaments");return r.jsxs("div",{className:"flex flex-col gap-1 text-bambu-gray text-sm py-2",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(lt,{className:"w-4 h-4 animate-spin"}),f,r.jsxs("span",{className:"text-xs tabular-nums",children:[s,"s"]})]}),s>=5&&r.jsx("div",{className:"text-xs text-bambu-gray/70 pl-6",children:a("slice.analyzingPlateFilamentsHint","Running a preview slice to discover which AMS slots this plate uses. Cached after — re-opening is instant.")})]})}function S7e(t){const e=Math.max(0,Math.floor(t));if(e<60)return`${e}s`;const a=Math.floor(e/60),n=e%60;if(a<60)return`${a}m ${n}s`;const i=Math.floor(a/60),s=a%60;return`${i}h ${s}m`}function QA({source:t,onClose:e}){const{t:a}=wt(),{trackJob:n}=f7e(),i=na(),[s,o]=y.useState(null),[l,c]=y.useState(null),[d,u]=y.useState([]),[m,p]=y.useState(null),[f,g]=y.useState(null),[v,b]=y.useState([]),[x,S]=y.useState(null),[k,C]=y.useState(null),[N,T]=y.useState(!1),[j,D]=y.useState(null),P=$e({queryKey:["slicePlates",t.kind,t.id],queryFn:async()=>t.kind==="libraryFile"?ne.getLibraryFilePlates(t.id):ne.getArchivePlates(t.id),staleTime:6e4}),E=!!P.data?.is_multi_plate&&(P.data?.plates?.length??0)>1,z=E&&k==null,I=k??1,B=y.useMemo(()=>{const O=typeof crypto<"u"&&"randomUUID"in crypto?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2)}`;return`${t.kind}-${t.id}-p${I}-${O}`},[t.kind,t.id,I]),R=$e({queryKey:["sliceFilamentReqs",t.kind,t.id,I],queryFn:async()=>t.kind==="libraryFile"?ne.getLibraryFileFilamentRequirements(t.id,I,B):ne.getArchiveFilamentRequirements(t.id,I,B),enabled:!z,staleTime:6e4}),K=y.useMemo(()=>{const O=R.data?.filaments??[],q=O.length>0?O:[{slot_id:1,type:"",color:"",used_grams:0,used_meters:0}];return N?q.map(Z=>({...Z,used_in_plate:!0})):q},[N,R.data]),J=$e({queryKey:["slicerPresets"],queryFn:()=>ne.getSlicerPresets(),staleTime:6e4,enabled:!P.isLoading&&!z}),[X,ce]=y.useState(!1),de=async()=>{if(!X){ce(!0);try{const O=await ne.getSlicerPresets({refresh:!0});i.setQueryData(["slicerPresets"],O)}catch{i.invalidateQueries({queryKey:["slicerPresets"]})}finally{ce(!1)}}},oe=$e({queryKey:["slicerBundles"],queryFn:ne.listSlicerBundles,staleTime:6e4,enabled:!P.isLoading&&!z,retry:!1}),Y=$e({queryKey:["slicerPrinterModels"],queryFn:ne.getSlicerPrinterModels,staleTime:1/0}),ie=y.useMemo(()=>!m||!oe.data?null:oe.data.find(O=>O.id===m)??null,[m,oe.data]),me=ie!=null,he=y.useMemo(()=>!J.data||!s?null:$C(J.data,s,"printer")?.name??null,[J.data,s]),xe=y.useMemo(()=>g9e(oe.data??[],Y.data??{}),[oe.data,Y.data]),V=P.data?.embedded_printer??null,Q=P.data?.embedded_process??null;y.useEffect(()=>{const O=J.data;O&&s==null&&o(Use(O,"printer",V)??EB(O,"printer"))},[J.data,V]),y.useEffect(()=>{const O=J.data;O&&c(q=>{if(q){const Z=$C(O,q,"process");if(Z&&Uy(Z,"process",he,xe)!=="mismatch")return q}return g7e(O,he,xe,Q)})},[J.data,he,xe,Q]),y.useEffect(()=>{const O=J.data;O&&u(q=>K.map((Z,ee)=>{const re=q[ee]??null;if(re){const se=$C(O,re,"filament");if(se&&Uy(se,"filament",he,xe)!=="mismatch")return re}return x7e(O,{type:Z.type,color:Z.color},he,xe)}))},[J.data,K,he,xe]),y.useEffect(()=>{if(!ie){g(null),b([]);return}g(O=>O&&ie.process.includes(O)?O:ie.process[0]??null),b(O=>{if(O.length===K.length&&O.every(Z=>Z!=null))return O;const q=ie.filament[0]??null;return K.map((Z,ee)=>O[ee]??q)})},[ie,K]);const A=at({mutationFn:async O=>{const q=F(O);return t.kind==="libraryFile"?ne.sliceLibraryFile(t.id,q):ne.sliceArchive(t.id,q)},onSuccess:O=>{n(O.job_id,t.kind,t.filename),e()},onError:O=>{const q=O instanceof Error?O.message:String(O);S(q)}});function F(O){if(me){if(!ie||!f||v.length===0||v.some(Z=>Z==null))throw new Error(a("slice.bundleAllRequired"));return{bundle:{bundle_id:ie.id,printer_name:ie.printer[0]??ie.printer_preset_name,process_name:f,filament_names:v},...O!=null?{plate:O}:{},...j!=null?{bed_type:j}:{}}}if(!s||!l||d.length===0||d.some(q=>q==null))throw new Error(a("slice.allPresetsRequired"));return{printer_preset:s,process_preset:l,filament_preset:d[0],filament_presets:d,...O!=null?{plate:O}:{},...j!=null?{bed_type:j}:{}}}const U=me?ie!=null&&f!=null&&R.isSuccess&&v.length>0&&v.every(O=>O!=null):s!=null&&l!=null&&R.isSuccess&&d.length>0&&d.every(O=>O!=null),$=A.isPending,H=P.data?.plates?.length??0,le=E&&H>1&&!z;return z&&P.data?r.jsx(MB,{plates:P.data.plates,onSelect:O=>C(O),onClose:e}):r.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4",onClick:()=>{$||e()},children:r.jsxs("div",{className:"w-full max-w-xl max-h-[85vh] flex flex-col rounded-lg bg-bambu-dark-secondary border border-bambu-dark-tertiary/60",onClick:O=>O.stopPropagation(),children:[r.jsxs("div",{className:"flex-shrink-0 flex items-start justify-between gap-3 px-4 pt-4 pb-3 border-b border-bambu-dark-tertiary/40",children:[r.jsxs("div",{className:"min-w-0",children:[r.jsxs("h3",{className:"text-white font-medium flex items-center gap-2",children:[r.jsx(bd,{className:"w-4 h-4"}),a("slice.title")]}),r.jsxs("p",{className:"text-xs text-bambu-gray mt-1 truncate",title:t.filename,children:[t.filename,k!=null?` • ${a("archives.platePicker.plateLabel",{index:k})}`:""]})]}),r.jsx("button",{onClick:e,disabled:$,className:"flex-shrink-0 text-bambu-gray hover:text-white transition-colors disabled:opacity-50","aria-label":a("common.close"),children:r.jsx(Ht,{className:"w-5 h-5"})})]}),r.jsxs("div",{className:"flex-1 overflow-y-auto p-4 space-y-4",children:[(P.isLoading||J.isLoading)&&r.jsxs("div",{className:"flex items-center gap-2 text-bambu-gray text-sm",children:[r.jsx(lt,{className:"w-4 h-4 animate-spin"}),a("slice.loadingPresets")]}),J.isError&&r.jsx("div",{className:"text-sm text-red-400",role:"alert",children:a("slice.presetsLoadFailed","Failed to load presets. Open Settings → Profiles to import them, or sign in to Bambu Cloud.")}),J.data&&r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"flex items-start justify-between gap-2",children:[r.jsxs("div",{className:"flex-1 space-y-2",children:[r.jsx(NY,{status:J.data.cloud_status,cloudName:"bambu"}),r.jsx(NY,{status:J.data.orca_cloud_status,cloudName:"orca"})]}),r.jsxs("button",{type:"button",onClick:de,disabled:X||$,className:"flex-shrink-0 inline-flex items-center gap-1 px-2 py-1 rounded-md text-xs text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary/40 disabled:opacity-50 disabled:cursor-not-allowed transition-colors",title:a("slice.refreshPresetsTitle"),"aria-label":a("slice.refreshPresets"),children:[r.jsx(tr,{className:`w-3.5 h-3.5 ${X?"animate-spin":""}`}),a("slice.refreshPresets")]})]}),oe.data&&oe.data.length>0&&r.jsx(P7e,{bundles:oe.data,selectedId:m,onChange:p,disabled:$}),!me&&r.jsxs(r.Fragment,{children:[r.jsx(IF,{label:a("slice.printer"),slot:"printer",data:J.data,value:s,onChange:o,disabled:$}),r.jsx(IF,{label:a("slice.process"),slot:"process",data:J.data,value:l,onChange:c,disabled:$,selectedPrinterName:he,compatIndex:xe})]}),me&&ie&&r.jsxs(r.Fragment,{children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("slice.printer")}),r.jsx("div",{className:"px-3 py-2 rounded-md bg-bambu-dark/40 border border-bambu-dark-tertiary text-white text-sm",children:ie.printer_preset_name})]}),r.jsx(TY,{label:a("slice.process"),options:ie.process,value:f,onChange:g,disabled:$})]}),r.jsx(_7e,{value:j,onChange:D,disabled:$}),R.isLoading?r.jsx(w7e,{requestId:B,sourceName:t.filename}):me&&ie?K.map((O,q)=>{const Z=O.used_in_plate!==!1,ee=K.length>1?a("slice.filamentSlot",{index:q+1,type:O.type}):a("slice.filament"),re=Z?ee:`${ee} ${a("slice.notUsedByPlate")}`;return r.jsx(TY,{label:re,options:ie.filament,value:v[q]??null,onChange:se=>b(fe=>{const ue=fe.length===K.length?[...fe]:K.map((pe,G)=>fe[G]??null);return ue[q]=se,ue}),disabled:$||!Z,swatchColor:K.length>1?O.color:void 0},`bundle-filament-${q}`)}):K.map((O,q)=>{const Z=O.used_in_plate!==!1,ee=K.length>1?a("slice.filamentSlot",{index:q+1,type:O.type}):a("slice.filament"),re=Z?ee:`${ee} ${a("slice.notUsedByPlate")}`;return r.jsx(IF,{label:re,slot:"filament",data:J.data,value:d[q]??null,onChange:se=>u(fe=>{const ue=fe.length===K.length?[...fe]:K.map((pe,G)=>fe[G]??null);return ue[q]=se,ue}),disabled:$||!Z,swatchColor:K.length>1?O.color:void 0,selectedPrinterName:he,compatIndex:xe},`filament-${q}`)})]}),x&&r.jsx("div",{className:"text-sm text-red-400 bg-red-900/20 border border-red-900/40 rounded p-2",role:"alert",children:x})]}),r.jsxs("div",{className:"flex-shrink-0 flex justify-end gap-2 px-4 py-3 border-t border-bambu-dark-tertiary/40",children:[r.jsx("button",{type:"button",onClick:e,disabled:$,className:"px-3 py-1.5 text-sm rounded-md border border-bambu-dark-tertiary text-bambu-gray hover:text-white hover:border-bambu-gray transition-colors disabled:opacity-50",children:a("common.cancel")}),le&&r.jsxs("label",{className:"flex items-center gap-2 mr-auto text-sm text-bambu-gray cursor-pointer select-none",title:a("slice.actionAllTitle",{count:H}),children:[r.jsx("input",{type:"checkbox",checked:N,onChange:O=>T(O.target.checked),disabled:$,className:"cursor-pointer"}),a("slice.allPlatesToggle",{count:H})]}),r.jsx("button",{type:"button",onClick:()=>{S(null);const O=N?0:k;A.mutate(O)},disabled:!U||$,className:"px-3 py-1.5 text-sm rounded-md bg-bambu-green hover:bg-bambu-green/90 text-bambu-dark font-medium transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-2",children:$?r.jsxs(r.Fragment,{children:[r.jsx(lt,{className:"w-4 h-4 animate-spin"}),a("slice.enqueuing")]}):N?a("slice.actionAll",{count:H}):a("slice.action")})]})]})})}function NY({status:t,cloudName:e="bambu"}){const{t:a}=wt();if(t==="ok")return null;const n=e==="orca"?{not_authenticated:{key:"slice.orcaCloud.notAuthenticated",fallback:"Sign in to Orca Cloud (Profiles → Orca Cloud) to see your Orca presets."},expired:{key:"slice.orcaCloud.expired",fallback:"Orca Cloud session expired — sign in again to refresh your Orca presets."},unreachable:{key:"slice.orcaCloud.unreachable",fallback:"Orca Cloud is unreachable right now. Other presets still work."}}:{not_authenticated:{key:"slice.cloud.notAuthenticated",fallback:"Sign in to Bambu Cloud (Settings → Profiles → Cloud) to see your cloud presets."},expired:{key:"slice.cloud.expired",fallback:"Bambu Cloud session expired — sign in again to refresh your cloud presets."},unreachable:{key:"slice.cloud.unreachable",fallback:"Bambu Cloud is unreachable right now. Local and standard presets still work."}},i={not_authenticated:{tone:"border-bambu-dark-tertiary/40 bg-bambu-dark text-bambu-gray",icon:mu},expired:{tone:"border-amber-700/40 bg-amber-900/20 text-amber-200",icon:s3},unreachable:{tone:"border-bambu-dark-tertiary/40 bg-bambu-dark text-bambu-gray",icon:s3}},{tone:s,icon:o}=i[t],{key:l,fallback:c}=n[t];return r.jsxs("div",{className:`flex items-start gap-2 text-xs rounded-md border p-2 ${s}`,role:"status",children:[r.jsx(o,{className:"w-4 h-4 flex-shrink-0 mt-0.5"}),r.jsx("span",{children:a(l,c)})]})}const k7e=[{value:"Cool Plate",labelKey:"slice.bedType.coolPlate",fallback:"Cool Plate"},{value:"Cool Plate (SuperTack)",labelKey:"slice.bedType.coolPlateSuperTack",fallback:"Cool Plate SuperTack"},{value:"Engineering Plate",labelKey:"slice.bedType.engineering",fallback:"Engineering Plate"},{value:"High Temp Plate",labelKey:"slice.bedType.highTemp",fallback:"High Temp Plate"},{value:"Textured PEI Plate",labelKey:"slice.bedType.texturedPEI",fallback:"Textured PEI Plate"},{value:"Smooth PEI Plate",labelKey:"slice.bedType.smoothPEI",fallback:"Smooth PEI Plate"}];function _7e({value:t,onChange:e,disabled:a}){const{t:n}=wt();return r.jsxs("label",{className:"block",children:[r.jsx("span",{className:"block text-xs text-bambu-gray mb-1",children:n("slice.bedType.label")}),r.jsxs("select",{value:t??"",onChange:i=>e(i.target.value===""?null:i.target.value),disabled:a,className:"w-full px-3 py-2 rounded-md bg-bambu-dark border border-bambu-dark-tertiary text-white text-sm focus:outline-none focus:border-bambu-gray disabled:opacity-50",children:[r.jsx("option",{value:"",children:n("slice.bedType.auto")}),k7e.map(i=>r.jsx("option",{value:i.value,children:n(i.labelKey,i.fallback)},i.value))]})]})}function IF({label:t,slot:e,data:a,value:n,onChange:i,disabled:s,swatchColor:o,selectedPrinterName:l,compatIndex:c}){const{t:d}=wt(),{sections:u,otherEntries:m}=y.useMemo(()=>{const f=[{key:"orca_cloud",label:"slice.tier.orcaCloud",fallback:"Orca Cloud"},{key:"local",label:"slice.tier.local",fallback:"Imported"},{key:"cloud",label:"slice.tier.cloud",fallback:"Bambu Cloud"},{key:"standard",label:"slice.tier.standard",fallback:"Standard"}],g=e!=="printer",v=[],b=[];for(const{key:x,label:S,fallback:k}of f){const C=a[x][e];if(!g){C.length>0&&v.push({tierLabel:d(S,k),entries:C});continue}const N=[];for(const T of C)Uy(T,e,l??null,c??h9e)==="mismatch"?b.push(T):N.push(T);N.length>0&&v.push({tierLabel:d(S,k),entries:N})}return{sections:v,otherEntries:b}},[a,e,d,l,c]),p=u.reduce((f,g)=>f+g.entries.length,0)+m.length;return r.jsxs("label",{className:"block",children:[r.jsxs("span",{className:"flex items-center gap-2 text-xs text-bambu-gray mb-1",children:[o&&r.jsx("span",{className:"inline-block w-3 h-3 rounded-full border border-bambu-dark-tertiary",style:{backgroundColor:o||"transparent"},"aria-hidden":!0}),r.jsx("span",{children:t})]}),r.jsxs("select",{value:y7e(n),onChange:f=>i(v7e(f.target.value)),disabled:s||p===0,className:"w-full px-3 py-2 rounded-md bg-bambu-dark border border-bambu-dark-tertiary text-white text-sm focus:outline-none focus:border-bambu-gray disabled:opacity-50",children:[r.jsx("option",{value:"",children:d(p===0?"slice.noPresetsForSlot":"slice.selectPreset")}),u.map(f=>r.jsx("optgroup",{label:f.tierLabel,children:f.entries.map(g=>r.jsx("option",{value:`${g.source}:${g.id}`,children:g.name},`${g.source}:${g.id}`))},f.tierLabel)),m.length>0&&r.jsx("optgroup",{label:d("slice.otherPrinters"),children:m.map(f=>r.jsx("option",{value:`${f.source}:${f.id}`,children:f.name},`${f.source}:${f.id}`))})]})]})}function P7e({bundles:t,selectedId:e,onChange:a,disabled:n}){const{t:i}=wt();return r.jsxs("label",{className:"block",children:[r.jsxs("span",{className:"block text-sm text-bambu-gray mb-1 inline-flex items-center gap-1.5",children:[r.jsx(Kr,{className:"w-3.5 h-3.5"}),i("slice.bundle")]}),r.jsxs("select",{value:e??"",onChange:s=>a(s.target.value||null),disabled:n,className:"w-full px-3 py-2 rounded-md bg-bambu-dark border border-bambu-dark-tertiary text-white text-sm focus:outline-none focus:border-bambu-gray disabled:opacity-50",children:[r.jsx("option",{value:"",children:i("slice.bundleNone")}),t.map(s=>r.jsx("option",{value:s.id,children:s.printer_preset_name},s.id))]})]})}function TY({label:t,options:e,value:a,onChange:n,disabled:i,swatchColor:s}){const{t:o}=wt();return r.jsxs("label",{className:"block",children:[r.jsxs("span",{className:"block text-sm text-bambu-gray mb-1 inline-flex items-center gap-1.5",children:[s&&r.jsx("span",{className:"inline-block w-3 h-3 rounded-sm border border-black/20",style:{backgroundColor:s||"transparent"},"aria-hidden":!0}),r.jsx("span",{children:t})]}),r.jsxs("select",{value:a??"",onChange:l=>n(l.target.value||null),disabled:i||e.length===0,className:"w-full px-3 py-2 rounded-md bg-bambu-dark border border-bambu-dark-tertiary text-white text-sm focus:outline-none focus:border-bambu-gray disabled:opacity-50",children:[r.jsx("option",{value:"",children:e.length===0?o("slice.noPresetsForSlot"):o("slice.selectPreset")}),e.map(l=>r.jsx("option",{value:l,children:l},l))]})]})}function C7e(){const t=navigator.userAgent.toLowerCase(),e=navigator.platform?.toLowerCase()||"";return t.includes("win")||e.includes("win")?"windows":t.includes("mac")||e.includes("mac")?"macos":t.includes("linux")||e.includes("linux")?"linux":"unknown"}function Rm(t,e="bambu_studio"){let a;const n=encodeURIComponent(t);e==="orcaslicer"?a=`orcaslicer://open?file=${n}`:C7e()==="macos"?a=`bambustudioopen://${n}`:a=`bambustudio://open?file=${n}`;const i=document.createElement("a");i.href=a,i.style.display="none",document.body.appendChild(i),i.click(),document.body.removeChild(i)}const AY=768;function Hse(){const[t,e]=y.useState(()=>typeof window<"u"?window.innerWidth{const a=window.matchMedia(`(max-width: ${AY-1}px)`),n=i=>{e(i.matches)};return e(a.matches),a.addEventListener("change",n),()=>a.removeEventListener("change",n)},[]),t}function N7e({onClose:t,initialFiles:e}){const{t:a}=wt(),n=na(),{showToast:i}=oa(),s=y.useRef(null),[o,l]=y.useState(()=>e?.filter(N=>N.name.endsWith(".3mf")).map(N=>({file:N,status:"pending"}))||[]),[c,d]=y.useState(!1),[u,m]=y.useState(null);y.useEffect(()=>{const N=T=>{T.key==="Escape"&&t()};return window.addEventListener("keydown",N),()=>window.removeEventListener("keydown",N)},[t]);const p=at({mutationFn:N=>ne.uploadArchivesBulk(N),onSuccess:N=>{m(N),n.invalidateQueries({queryKey:["archives"]}),n.invalidateQueries({queryKey:["archiveStats"]}),l(T=>T.map(j=>{const D=N.results.find(E=>E.filename===j.file.name),P=N.errors.find(E=>E.filename===j.file.name);return D?{...j,status:"success",archiveId:D.id}:P?{...j,status:"error",error:P.error}:j})),N.failed===0?i(`${N.uploaded} file${N.uploaded!==1?"s":""} uploaded`):N.uploaded===0?i(`Failed to upload ${N.failed} file${N.failed!==1?"s":""}`,"error"):i(`${N.uploaded} uploaded, ${N.failed} failed`,"warning")},onError:()=>{l(N=>N.map(T=>({...T,status:"error",error:"Upload failed"}))),i("Upload failed","error")}}),f=y.useCallback(N=>{N.preventDefault(),d(!0)},[]),g=y.useCallback(N=>{N.preventDefault(),d(!1)},[]),v=y.useCallback(N=>{N.preventDefault(),d(!1);const T=Array.from(N.dataTransfer.files).filter(j=>j.name.endsWith(".3mf"));T.length>0&&l(j=>[...j,...T.map(D=>({file:D,status:"pending"}))])},[]),b=y.useCallback(N=>{const T=Array.from(N.target.files||[]).filter(j=>j.name.endsWith(".3mf"));T.length>0&&l(j=>[...j,...T.map(D=>({file:D,status:"pending"}))]),s.current&&(s.current.value="")},[]),x=y.useCallback(N=>{l(T=>T.filter((j,D)=>D!==N))},[]),S=()=>{if(o.length===0)return;const N=o.filter(T=>T.status==="pending");N.length!==0&&(l(T=>T.map(j=>j.status==="pending"?{...j,status:"uploading"}:j)),p.mutate(N.map(T=>T.file)))},k=o.filter(N=>N.status==="pending").length,C=p.isPending;return r.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:r.jsx(Tt,{className:"w-full max-w-2xl max-h-[90vh] flex flex-col",children:r.jsxs(jt,{className:"p-0 flex flex-col h-full",children:[r.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[r.jsx("h2",{className:"text-xl font-semibold text-white",children:a("uploadModal.title")}),r.jsx("button",{onClick:t,className:"text-bambu-gray hover:text-white transition-colors",children:r.jsx(Ht,{className:"w-5 h-5"})})]}),r.jsx("div",{className:"p-4",children:r.jsxs("div",{className:`border-2 border-dashed rounded-lg p-8 text-center transition-colors ${c?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary hover:border-bambu-gray"}`,onDragOver:f,onDragLeave:g,onDrop:v,children:[r.jsx(fn,{className:"w-12 h-12 mx-auto mb-4 text-bambu-gray"}),r.jsx("p",{className:"text-white mb-2",children:a("uploadModal.dragDrop")}),r.jsx("p",{className:"text-bambu-gray text-sm mb-4",children:a("uploadModal.or")}),r.jsx(Le,{variant:"secondary",onClick:()=>s.current?.click(),disabled:C,children:a("uploadModal.browseFiles")}),r.jsx("input",{ref:s,type:"file",accept:".3mf",multiple:!0,className:"hidden",onChange:b})]})}),r.jsx("div",{className:"px-4 pb-4",children:r.jsx("p",{className:"text-xs text-bambu-gray",children:a("uploadModal.extractionInfo")})}),o.length>0&&r.jsx("div",{className:"px-4 pb-4 max-h-60 overflow-y-auto",children:r.jsx("div",{className:"space-y-2",children:o.map((N,T)=>r.jsxs("div",{className:"flex items-center gap-3 p-3 bg-bambu-dark rounded-lg",children:[r.jsx(F1,{className:"w-5 h-5 text-bambu-gray flex-shrink-0"}),r.jsx("span",{className:"flex-1 text-white text-sm truncate",children:N.file.name}),r.jsxs("span",{className:"text-xs text-bambu-gray",children:[(N.file.size/(1024*1024)).toFixed(1)," MB"]}),N.status==="pending"&&r.jsx("button",{onClick:()=>x(T),className:"text-bambu-gray hover:text-red-400 transition-colors",disabled:C,children:r.jsx(Ht,{className:"w-4 h-4"})}),N.status==="uploading"&&r.jsx(lt,{className:"w-4 h-4 text-bambu-green animate-spin"}),N.status==="success"&&r.jsx(fr,{className:"w-4 h-4 text-bambu-green"}),N.status==="error"&&r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("span",{className:"text-xs text-red-400",children:N.error}),r.jsx(Sn,{className:"w-4 h-4 text-red-400"})]})]},`${N.file.name}-${T}`))})}),u&&r.jsx("div",{className:"px-4 pb-4",children:r.jsx("div",{className:"p-3 bg-bambu-dark rounded-lg",children:r.jsxs("p",{className:"text-sm text-white",children:[r.jsx("span",{className:"text-bambu-green",children:u.uploaded})," ",a("uploadModal.uploaded"),u.failed>0&&r.jsxs(r.Fragment,{children:[", ",r.jsx("span",{className:"text-red-400",children:u.failed})," ",a("uploadModal.failed")]})]})})}),r.jsxs("div",{className:"flex gap-3 p-4 border-t border-bambu-dark-tertiary",children:[r.jsx(Le,{variant:"secondary",onClick:t,className:"flex-1",children:a(u?"common.close":"common.cancel")}),!u&&r.jsx(Le,{onClick:S,disabled:k===0||C,className:"flex-1",children:C?r.jsxs(r.Fragment,{children:[r.jsx(lt,{className:"w-4 h-4 animate-spin"}),a("uploadModal.uploading")]}):r.jsxs(r.Fragment,{children:[r.jsx(fn,{className:"w-4 h-4"}),a("uploadModal.upload")," ",k>0&&`(${k})`]})})]})]})})})}const T7e=365;function A7e({onClose:t,initialDays:e}){const{t:a}=wt(),n=na(),{showToast:i}=oa(),[s,o]=y.useState(e??T7e),[l,c]=y.useState(!1),[d,u]=y.useState(s);y.useEffect(()=>{const x=window.setTimeout(()=>u(s),300);return()=>window.clearTimeout(x)},[s]);const m=$e({queryKey:["archive-purge-preview",d,l],queryFn:()=>ne.previewArchivePurge(d,l),enabled:d>=1}),p=at({mutationFn:()=>ne.executeArchivePurge(s,l),onSuccess:x=>{i(a("archivePurge.toast.success",{count:x.deleted}),"success"),n.invalidateQueries({queryKey:["archives"]}),n.invalidateQueries({queryKey:["archive-stats"]}),t()},onError:x=>i(x.message||a("archivePurge.toast.failed"),"error")});y.useEffect(()=>{const x=S=>{S.key==="Escape"&&!p.isPending&&t()};return window.addEventListener("keydown",x),()=>window.removeEventListener("keydown",x)},[t,p.isPending]);const f=m.data,g=f?.count??0,v=f?.total_bytes??0,b=g>0&&!p.isPending;return r.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4",children:r.jsxs("div",{className:"bg-white dark:bg-gray-900 rounded-lg shadow-xl max-w-lg w-full",children:[r.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-gray-200 dark:border-gray-700",children:[r.jsxs("h2",{className:"text-lg font-semibold text-gray-900 dark:text-gray-100 flex items-center gap-2",children:[r.jsx(ra,{className:"w-5 h-5"}),a("archivePurge.title")]}),r.jsx("button",{onClick:t,className:"text-gray-400 hover:text-gray-600 dark:hover:text-gray-200","aria-label":a("common.close"),disabled:p.isPending,children:r.jsx(Ht,{className:"w-5 h-5"})})]}),r.jsxs("div",{className:"p-4 space-y-4",children:[r.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-400",children:a("archivePurge.description")}),r.jsxs("div",{children:[r.jsx("label",{htmlFor:"archive-purge-days",className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1",children:a("archivePurge.ageLabel")}),r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("input",{id:"archive-purge-days",type:"number",min:1,max:3650,value:s,onChange:x=>o(Math.max(1,Math.min(3650,parseInt(x.target.value||"0",10)||0))),className:"w-24 rounded border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-sm px-2 py-1 text-gray-900 dark:text-gray-100"}),r.jsx("span",{className:"text-sm text-gray-600 dark:text-gray-400",children:a("archivePurge.days")})]})]}),r.jsxs("div",{className:"rounded border border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-800/30 p-3",children:[r.jsx("div",{className:"text-xs font-semibold uppercase tracking-wide text-gray-600 dark:text-gray-300 mb-2",children:a("archivePurge.effectsTitle")}),r.jsxs("ul",{className:"text-xs text-gray-700 dark:text-gray-300 space-y-1 list-disc pl-4",children:[r.jsx("li",{children:a("archivePurge.effect1")}),r.jsx("li",{children:a("archivePurge.effect2")}),r.jsx("li",{children:a("archivePurge.effect3")}),r.jsx("li",{children:a("archivePurge.effect4")})]})]}),r.jsx("div",{className:"rounded border border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-800/50 p-3",children:m.isLoading||m.isFetching?r.jsxs("div",{className:"flex items-center gap-2 text-sm text-gray-500 dark:text-gray-400",children:[r.jsx(lt,{className:"w-4 h-4 animate-spin"})," ",a("archivePurge.previewLoading")]}):m.isError?r.jsx("div",{className:"text-sm text-red-600 dark:text-red-400",children:m.error?.message??a("archivePurge.previewFailed")}):r.jsxs("div",{className:"text-sm text-gray-900 dark:text-gray-100",children:[r.jsx("div",{className:"font-medium",children:a("archivePurge.previewSummary",{count:g,size:cs(v)})}),f?.sample_filenames&&f.sample_filenames.length>0&&r.jsxs("ul",{className:"mt-2 text-xs text-gray-600 dark:text-gray-400 space-y-0.5 list-disc pl-4",children:[f.sample_filenames.map(x=>r.jsx("li",{className:"truncate",children:x},x)),g>f.sample_filenames.length&&r.jsx("li",{className:"list-none italic text-gray-500",children:a("archivePurge.andMore",{count:g-f.sample_filenames.length})})]})]})}),r.jsxs("label",{className:"flex gap-2 items-start rounded border border-gray-200 dark:border-gray-700 px-3 py-2 cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-800/50",children:[r.jsx("input",{type:"checkbox",checked:l,onChange:x=>c(x.target.checked),disabled:p.isPending,className:"mt-0.5 shrink-0"}),r.jsxs("span",{className:"text-xs text-gray-700 dark:text-gray-300",children:[r.jsx("span",{className:"font-medium block mb-0.5",children:a("archivePurge.purgeStatsLabel")}),r.jsx("span",{className:"text-gray-500 dark:text-gray-400",children:a("archivePurge.purgeStatsHint")})]})]}),r.jsxs("div",{className:"flex gap-2 items-start text-xs text-amber-700 dark:text-amber-400 bg-amber-50 dark:bg-amber-900/20 rounded px-3 py-2",children:[r.jsx(xa,{className:"w-4 h-4 mt-0.5 shrink-0"}),r.jsx("span",{children:a("archivePurge.warning")})]})]}),r.jsxs("div",{className:"flex justify-end gap-2 p-4 border-t border-gray-200 dark:border-gray-700",children:[r.jsx(Le,{variant:"secondary",onClick:t,disabled:p.isPending,children:a("common.cancel")}),r.jsx(Le,{variant:"danger",disabled:!b,onClick:()=>p.mutate(),children:p.isPending?r.jsxs(r.Fragment,{children:[r.jsx(lt,{className:"w-4 h-4 animate-spin mr-1"}),a("archivePurge.purging")]}):a("archivePurge.confirmCta",{count:g})})]})]})})}function j7e(t){if(!t||t<=0)return"—";const e=Math.floor(t/3600),a=Math.floor(t%3600/60);return e>0?`${e}h ${a}m`:`${a}m`}function M7e(t){if(!t)return"—";const e=Ga(t);return e?e.toLocaleString():"—"}function qse({archiveId:t}){const{t:e}=wt(),{data:a,isLoading:n}=$e({queryKey:["archive-runs",t],queryFn:()=>ne.getArchiveRuns(t)});if(n)return r.jsx("div",{className:"flex justify-center py-4",children:r.jsx(lt,{className:"w-5 h-5 text-bambu-gray animate-spin"})});const i=a?.items||[];return i.length===0?r.jsx("p",{className:"text-sm text-bambu-gray italic py-2",children:e("archives.runLog.empty")}):r.jsx("div",{className:"overflow-x-auto",children:r.jsxs("table",{className:"w-full text-xs",children:[r.jsx("thead",{children:r.jsxs("tr",{className:"text-bambu-gray border-b border-bambu-dark-tertiary",children:[r.jsx("th",{className:"text-left py-1.5 pr-2 font-medium",children:e("archives.runLog.col.date")}),r.jsx("th",{className:"text-left py-1.5 pr-2 font-medium",children:e("archives.runLog.col.status")}),r.jsx("th",{className:"text-right py-1.5 pr-2 font-medium",children:e("archives.runLog.col.duration")}),r.jsx("th",{className:"text-right py-1.5 pr-2 font-medium",children:e("archives.runLog.col.filament")}),r.jsx("th",{className:"text-right py-1.5 font-medium",children:e("archives.runLog.col.cost")})]})}),r.jsx("tbody",{children:i.map(s=>{const o=s.status==="completed"?"text-bambu-green":s.status==="failed"?"text-red-400":"text-bambu-gray";return r.jsxs("tr",{className:"border-b border-bambu-dark-tertiary/40 last:border-0",children:[r.jsx("td",{className:"py-1.5 pr-2 text-bambu-gray-light",children:M7e(s.started_at||s.created_at)}),r.jsxs("td",{className:`py-1.5 pr-2 font-medium ${o}`,children:[e(`archives.runLog.status.${s.status}`,{defaultValue:s.status}),s.failure_reason&&r.jsx("span",{className:"block text-[10px] text-bambu-gray font-normal",children:e(`editArchive.failureReasons.${s.failure_reason}`,{defaultValue:s.failure_reason})})]}),r.jsx("td",{className:"py-1.5 pr-2 text-right text-bambu-gray-light",children:j7e(s.duration_seconds)}),r.jsx("td",{className:"py-1.5 pr-2 text-right text-bambu-gray-light",children:s.filament_used_grams!=null?`${s.filament_used_grams.toFixed(1)} g`:"—"}),r.jsx("td",{className:"py-1.5 text-right text-bambu-gray-light",children:s.cost!=null?s.cost.toFixed(2):"—"})]},s.id)})})]})})}const WC=["adhesionFailure","spaghettiDetached","layerShift","cloggedNozzle","filamentRunout","warping","stringing","underExtrusion","powerFailure","userCancelled","other"],E7e=["completed","failed","aborted","printing"];function Vse({archive:t,onClose:e,existingTags:a=[]}){const{t:n}=wt();y.useEffect(()=>{const F=U=>{U.key==="Escape"&&e()};return window.addEventListener("keydown",F),()=>window.removeEventListener("keydown",F)},[e]);const i=na(),[s,o]=y.useState(t.print_name||""),[l,c]=y.useState(t.printer_id),[d,u]=y.useState(t.project_id??null),[m,p]=y.useState(t.notes||""),[f,g]=y.useState(t.tags||""),[v,b]=y.useState(()=>{const F=t.failure_reason||"";return F?WC.includes(F)?F:WC.find($=>n(`editArchive.failureReasons.${$}`)===F)||"":""}),[x,S]=y.useState(t.status),[k,C]=y.useState(t.quantity??1),[N,T]=y.useState(t.photos||[]),[j,D]=y.useState(t.external_url||""),[P,E]=y.useState(!1),[z,I]=y.useState(!1),B=y.useRef(null),R=y.useRef(null),K=y.useRef(null),{data:J}=$e({queryKey:["printers"],queryFn:ne.getPrinters}),{data:X}=$e({queryKey:["projects"],queryFn:()=>ne.getProjects(),select:F=>[...F].sort((U,$)=>U.name.localeCompare($.name))}),{data:ce}=$e({queryKey:["tags"],queryFn:ne.getTags,enabled:a.length===0}),de=a.length>0?a:ce?.map(F=>F.name)||[],oe=f.split(",").map(F=>F.trim()).filter(Boolean),Y=f.includes(",")?f.substring(f.lastIndexOf(",")+1).trim().toLowerCase():f.trim().toLowerCase(),ie=de.filter(F=>!oe.includes(F)&&(Y===""||F.toLowerCase().includes(Y))),me=F=>{let U;if(Y&&!de.includes(Y)?U=f.includes(",")?f.substring(0,f.lastIndexOf(",")).split(",").map($=>$.trim()).filter(Boolean):[]:U=oe,!U.includes(F)){const $=[...U,F].join(", ");g($)}K.current!==null&&clearTimeout(K.current),B.current?.focus()},he=F=>{const U=oe.filter($=>$!==F).join(", ");g(U)},xe=at({mutationFn:F=>ne.updateArchive(t.id,F),onSuccess:()=>{i.invalidateQueries({queryKey:["archives"]}),i.invalidateQueries({queryKey:["projects"]}),e()}}),V=async F=>{const U=F.target.files?.[0];if(U){E(!0);try{const $=await ne.uploadArchivePhoto(t.id,U);T($.photos),i.invalidateQueries({queryKey:["archives"]})}catch($){console.error("Failed to upload photo:",$)}finally{E(!1),R.current&&(R.current.value="")}}},Q=async F=>{try{const U=await ne.deleteArchivePhoto(t.id,F);T(U.photos||[]),i.invalidateQueries({queryKey:["archives"]})}catch(U){console.error("Failed to delete photo:",U)}},A=F=>{F.preventDefault();const U={print_name:s||void 0,printer_id:l,project_id:d,notes:m||void 0,tags:f||void 0,quantity:k,external_url:j||null};x!==t.status&&(U.status=x),x==="failed"||x==="aborted"?U.failure_reason=v||void 0:(t.status==="failed"||t.status==="aborted")&&(U.failure_reason=null),xe.mutate(U)};return r.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:e,children:r.jsxs("div",{className:"bg-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary w-full max-w-md max-h-[90vh] flex flex-col",onClick:F=>F.stopPropagation(),children:[r.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary",children:[r.jsx("h2",{className:"text-lg font-semibold text-white",children:n("editArchive.title")}),r.jsx("button",{onClick:e,className:"text-bambu-gray hover:text-white transition-colors",children:r.jsx(Ht,{className:"w-5 h-5"})})]}),r.jsxs("form",{onSubmit:A,className:"p-6 space-y-4 overflow-y-auto flex-1",children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("archives.runLog.title")}),r.jsx(qse,{archiveId:t.id})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("editArchive.name")}),r.jsx("input",{type:"text",value:s,onChange:F=>o(F.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",placeholder:n("editArchive.namePlaceholder")})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("editArchive.printer")}),r.jsxs("select",{value:l??"",onChange:F=>c(F.target.value?Number(F.target.value):null),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[r.jsx("option",{value:"",children:n("editArchive.noPrinter")}),J?.map(F=>r.jsx("option",{value:F.id,children:F.name},F.id))]})]}),r.jsxs("div",{children:[r.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[r.jsx(no,{className:"w-4 h-4 inline mr-1"}),n("editArchive.project")]}),r.jsxs("select",{value:d??"",onChange:F=>u(F.target.value?Number(F.target.value):null),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[r.jsx("option",{value:"",children:n("editArchive.noProject")}),X?.map(F=>r.jsx("option",{value:F.id,children:F.name},F.id))]})]}),r.jsxs("div",{children:[r.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[r.jsx(Cxe,{className:"w-4 h-4 inline mr-1"}),n("editArchive.itemsPrinted")]}),r.jsx("input",{type:"number",min:1,value:k,onChange:F=>C(Math.max(1,parseInt(F.target.value)||1)),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",placeholder:"1"}),r.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:n("editArchive.itemsPrintedHelp")})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("editArchive.notes")}),r.jsx("textarea",{value:m,onChange:F=>p(F.target.value),rows:3,className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none resize-none",placeholder:n("editArchive.notesPlaceholder")})]}),r.jsxs("div",{children:[r.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[r.jsx(rv,{className:"w-4 h-4 inline mr-1"}),n("editArchive.externalLink")]}),r.jsx("input",{type:"url",value:j,onChange:F=>D(F.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",placeholder:"https://printables.com/model/..."}),r.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:n("editArchive.externalLinkHelp")})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("editArchive.tags")}),oe.length>0&&r.jsx("div",{className:"flex flex-wrap gap-1.5 mb-2",children:oe.map(F=>r.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 bg-bambu-dark-tertiary rounded text-sm text-white",children:[r.jsx(Xm,{className:"w-3 h-3"}),F,r.jsx("button",{type:"button",onClick:()=>he(F),className:"ml-0.5 text-bambu-gray hover:text-white",children:r.jsx(Ht,{className:"w-3 h-3"})})]},F))}),r.jsxs("div",{className:"relative",children:[r.jsx("input",{ref:B,type:"text",value:f,onChange:F=>g(F.target.value),onFocus:()=>{K.current!==null&&clearTimeout(K.current),I(!0)},onBlur:()=>{K.current=window.setTimeout(()=>I(!1),200)},className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",placeholder:oe.length>0?n("editArchive.addMoreTags"):n("editArchive.tagsPlaceholder")}),z&&ie.length>0&&r.jsxs("div",{className:"absolute top-full left-0 right-0 mt-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-lg z-10 max-h-40 overflow-y-auto",children:[r.jsxs("div",{className:"p-2 text-xs text-bambu-gray border-b border-bambu-dark-tertiary",children:[Y?n("editArchive.matchingTags",{query:Y}):n("editArchive.existingTags")," ",n("editArchive.clickToAdd")]}),r.jsx("div",{className:"p-2 flex flex-wrap gap-1.5",children:ie.map(F=>r.jsx("button",{type:"button",onClick:()=>me(F),className:"px-2 py-0.5 bg-bambu-dark-tertiary hover:bg-bambu-green/20 rounded text-sm text-bambu-gray hover:text-white transition-colors",children:F},F))})]})]})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("editArchive.status")}),r.jsx("select",{value:x,onChange:F=>{S(F.target.value),F.target.value==="completed"&&b("")},className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:E7e.map(F=>r.jsx("option",{value:F,children:n(`editArchive.statuses.${F}`)},F))})]}),(x==="failed"||x==="aborted")&&r.jsxs("div",{children:[r.jsx("label",{htmlFor:"failure-reason-select",className:"block text-sm text-bambu-gray mb-1",children:n("editArchive.failureReason")}),r.jsxs("select",{id:"failure-reason-select",value:v,onChange:F=>b(F.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[r.jsx("option",{value:"",children:n("editArchive.selectReason")}),WC.map(F=>r.jsx("option",{value:F,children:n(`editArchive.failureReasons.${F}`)},F))]})]}),r.jsxs("div",{children:[r.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[r.jsx(wy,{className:"w-4 h-4 inline mr-1"}),n("editArchive.photos")]}),r.jsxs("div",{className:"flex flex-wrap gap-2 mb-2",children:[N.map(F=>r.jsxs("div",{className:"relative group",children:[r.jsx("img",{src:ne.getArchivePhotoUrl(t.id,F),alt:n("editArchive.printResult"),className:"w-20 h-20 object-cover rounded-lg border border-bambu-dark-tertiary"}),r.jsx("button",{type:"button",onClick:()=>Q(F),className:"absolute -top-1 -right-1 p-1 bg-red-500 rounded-full opacity-0 group-hover:opacity-100 transition-opacity",children:r.jsx(ra,{className:"w-3 h-3 text-white"})})]},F)),r.jsxs("label",{className:"w-20 h-20 flex items-center justify-center border-2 border-dashed border-bambu-dark-tertiary rounded-lg cursor-pointer hover:border-bambu-green transition-colors",children:[r.jsx("input",{ref:R,type:"file",accept:"image/jpeg,image/png,image/webp",onChange:V,className:"hidden",disabled:P}),P?r.jsx(lt,{className:"w-6 h-6 text-bambu-gray animate-spin"}):r.jsx(or,{className:"w-6 h-6 text-bambu-gray"})]})]}),r.jsx("p",{className:"text-xs text-bambu-gray",children:n("editArchive.photosHelp")})]}),r.jsxs("div",{className:"flex gap-3 pt-2",children:[r.jsx(Le,{type:"button",variant:"secondary",onClick:e,className:"flex-1",children:n("common.cancel")}),r.jsxs(Le,{type:"submit",disabled:xe.isPending,className:"flex-1",children:[r.jsx(ms,{className:"w-4 h-4"}),xe.isPending?n("common.saving"):n("common.save")]})]})]})]})})}function Gse({archiveId:t,archiveName:e,onClose:a}){const{t:n}=wt();return y.useEffect(()=>{const i=s=>{s.key==="Escape"&&a()};return window.addEventListener("keydown",i),()=>window.removeEventListener("keydown",i)},[a]),r.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:a,children:r.jsxs("div",{className:"bg-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary w-full max-w-2xl max-h-[85vh] flex flex-col",onClick:i=>i.stopPropagation(),children:[r.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[r.jsx(Zh,{className:"w-5 h-5 text-bambu-green flex-shrink-0"}),r.jsx("h2",{className:"text-lg font-semibold text-white truncate",title:e||"",children:n("archives.runLog.modalTitle",{name:e||n("archives.runLog.modalTitleFallback")})})]}),r.jsx("button",{onClick:a,className:"text-bambu-gray hover:text-white transition-colors",title:n("common.close"),children:r.jsx(Ht,{className:"w-5 h-5"})})]}),r.jsx("div",{className:"p-6 overflow-y-auto flex-1",children:r.jsx(qse,{archiveId:t})})]})})}function D7e({items:t,searchPlaceholder:e,onClose:a,className:n,onMouseEnter:i,onMouseLeave:s}){const[o,l]=y.useState(""),c=y.useRef(null);y.useEffect(()=>{if(e){const m=window.setTimeout(()=>c.current?.focus(),0);return()=>window.clearTimeout(m)}},[e]);const d=o.trim().toLowerCase(),u=e&&d?t.filter(m=>m.label.toLowerCase().includes(d)):t;return r.jsxs("div",{className:n,onMouseEnter:i,onMouseLeave:s,children:[e&&r.jsx("div",{className:"sticky top-0 z-[1] px-2 py-1.5 bg-bambu-dark-secondary border-b border-bambu-dark-tertiary",children:r.jsxs("div",{className:"relative",children:[r.jsx(br,{className:"absolute left-2 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-bambu-gray pointer-events-none"}),r.jsx("input",{ref:c,type:"text",value:o,onChange:m=>l(m.target.value),onKeyDown:m=>{if(m.key==="Enter"){const p=u.find(f=>!f.disabled);p&&(p.onClick(),a())}},placeholder:e,className:"w-full pl-7 pr-2 py-1 text-sm bg-bambu-dark border border-bambu-dark-tertiary rounded text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]})}),u.map((m,p)=>r.jsxs("button",{onClick:()=>{m.disabled||(m.onClick(),a())},disabled:m.disabled,className:`w-full flex items-center gap-2 px-3 py-2 text-sm text-left transition-colors ${m.disabled?"text-bambu-gray cursor-not-allowed":m.danger?"text-red-400 hover:bg-red-400/10":"text-white hover:bg-bambu-dark-tertiary"}`,children:[m.icon&&r.jsx("span",{className:"w-4 h-4 flex-shrink-0 flex items-center justify-center",children:m.icon}),r.jsx("span",{className:"flex-1 truncate",children:m.label})]},p)),e&&u.length===0&&r.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray text-center italic",children:"—"})]})}function $se({x:t,y:e,items:a,onClose:n}){const i=y.useRef(null),[s,o]=y.useState(null),l=y.useRef(null),[c,d]=y.useState({x:t,y:e,visible:!1}),[u,m]=y.useState(!1),[p,f]=y.useState({});y.useEffect(()=>{const b=k=>{i.current&&!i.current.contains(k.target)&&n()},x=k=>{k.key==="Escape"&&n()},S=k=>{i.current&&i.current.contains(k.target)||n()};return document.addEventListener("mousedown",b),document.addEventListener("keydown",x),document.addEventListener("scroll",S,!0),()=>{document.removeEventListener("mousedown",b),document.removeEventListener("keydown",x),document.removeEventListener("scroll",S,!0),l.current&&clearTimeout(l.current)}},[n]),y.useLayoutEffect(()=>{if(i.current){i.current.style.visibility="hidden",i.current.style.display="block";const b=i.current.getBoundingClientRect(),x=window.innerWidth,S=window.innerHeight,k=8;let C=t,N=e;t+b.width>x-k&&(C=Math.max(k,x-b.width-k)),CS-k&&(N=Math.max(k,S-b.height-k)),NT),d({x:C,y:N,visible:!0})}},[t,e]);const g=(b,x)=>{l.current&&(clearTimeout(l.current),l.current=null);const S=x.getBoundingClientRect(),k=window.innerHeight,C=300,j=k-S.top-8C;f(D=>({...D,[b]:j?"bottom":"top"})),o(b)},v=()=>{l.current=window.setTimeout(()=>{o(null)},150)};return r.jsx("div",{ref:i,className:"fixed z-50 min-w-[180px] max-w-[280px] bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl py-1",style:{left:c.x,top:c.y,visibility:c.visible?"visible":"hidden"},children:a.map((b,x)=>{if(b.divider)return r.jsx("div",{className:"my-1 border-t border-bambu-dark-tertiary"},x);const S=b.submenu&&b.submenu.length>0;return r.jsxs("div",{className:"relative",onMouseEnter:k=>S&&g(x,k.currentTarget),onMouseLeave:()=>S&&v(),children:[r.jsxs("button",{onMouseEnter:k=>S&&g(x,k.currentTarget.parentElement),onClick:()=>{S?o(s===x?null:x):b.disabled||(b.onClick(),n())},disabled:b.disabled,title:b.title,className:`w-full flex items-center gap-2 px-3 py-2 text-sm text-left transition-colors ${b.disabled?"text-bambu-gray cursor-not-allowed":b.danger?"text-red-400 hover:bg-red-400/10":"text-white hover:bg-bambu-dark-tertiary"} ${S&&s===x?"bg-bambu-dark-tertiary":""}`,children:[b.icon&&r.jsx("span",{className:"w-4 h-4 flex-shrink-0 flex items-center justify-center",children:b.icon}),r.jsx("span",{className:"flex-1",children:b.label}),S&&r.jsx(Vn,{className:"w-4 h-4 text-bambu-gray"})]}),S&&s===x&&r.jsx(D7e,{items:b.submenu,searchPlaceholder:b.submenuSearchPlaceholder,onClose:n,className:`absolute min-w-[200px] bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl py-1 overflow-hidden max-h-[300px] overflow-y-auto z-[60] ${u?"right-full mr-1":"left-full ml-1"} ${p[x]==="bottom"?"bottom-0":"top-0"}`,onMouseEnter:()=>{l.current&&(clearTimeout(l.current),l.current=null)},onMouseLeave:()=>v()})]},x)})})}function F7e({selectedIds:t,existingTags:e,onClose:a}){const n=na(),{showToast:i}=oa(),[s,o]=y.useState(""),[l,c]=y.useState(new Set),[d,u]=y.useState("add");y.useEffect(()=>{const v=b=>{b.key==="Escape"&&a()};return window.addEventListener("keydown",v),()=>window.removeEventListener("keydown",v)},[a]);const m=at({mutationFn:async()=>{const v=Array.from(l);let b=0;for(const x of t)try{const S=await ne.getArchive(x),k=S.tags?S.tags.split(",").map(N=>N.trim()).filter(Boolean):[];let C;d==="add"?C=[...new Set([...k,...v])]:C=k.filter(N=>!l.has(N)),await ne.updateArchive(x,{tags:C.join(", ")}),b++}catch(S){throw console.error(`Failed to update archive ${x}:`,S),new Error(`Failed on archive ${x}: ${S instanceof Error?S.message:"Unknown error"}`)}return{count:b,mode:d,tags:v}},onSuccess:({count:v,mode:b,tags:x})=>{n.invalidateQueries({queryKey:["archives"]}),i(`${b==="add"?"Added":"Removed"} ${x.length} tag${x.length!==1?"s":""} ${b==="add"?"to":"from"} ${v} archive${v!==1?"s":""}`),a()},onError:v=>{i(v.message||"Failed to update tags","error")}}),p=v=>{c(b=>{const x=new Set(b);return x.has(v)?x.delete(v):x.add(v),x})},f=()=>{s.trim()&&!l.has(s.trim())&&(c(v=>new Set([...v,s.trim()])),o(""))},g=v=>{v.key==="Enter"&&(v.preventDefault(),f())};return r.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:r.jsx(Tt,{className:"w-full max-w-md",children:r.jsxs(jt,{className:"p-0",children:[r.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(Xm,{className:"w-5 h-5 text-bambu-green"}),r.jsx("h2",{className:"text-xl font-semibold text-white",children:d==="add"?"Add Tags":"Remove Tags"})]}),r.jsx("button",{onClick:a,className:"text-bambu-gray hover:text-white transition-colors",children:r.jsx(Ht,{className:"w-5 h-5"})})]}),r.jsxs("div",{className:"p-4 space-y-4",children:[r.jsxs("p",{className:"text-sm text-bambu-gray",children:[d==="add"?"Add":"Remove"," tags for ",t.length," selected archive",t.length!==1?"s":""]}),r.jsxs("div",{className:"flex gap-2",children:[r.jsx(Le,{size:"sm",variant:d==="add"?"primary":"secondary",onClick:()=>u("add"),children:"Add Tags"}),r.jsx(Le,{size:"sm",variant:d==="remove"?"primary":"secondary",onClick:()=>u("remove"),children:"Remove Tags"})]}),d==="add"&&r.jsxs("div",{className:"flex gap-2",children:[r.jsx("input",{type:"text",placeholder:"Enter new tag...",className:"flex-1 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",value:s,onChange:v=>o(v.target.value),onKeyDown:g}),r.jsx(Le,{size:"sm",variant:"secondary",onClick:f,disabled:!s.trim(),children:r.jsx(or,{className:"w-4 h-4"})})]}),e.length>0&&r.jsxs("div",{children:[r.jsx("p",{className:"text-xs text-bambu-gray mb-2",children:"Existing tags:"}),r.jsx("div",{className:"flex flex-wrap gap-2",children:e.map(v=>r.jsx("button",{onClick:()=>p(v),className:`px-2 py-1 rounded text-sm transition-colors ${l.has(v)?"bg-bambu-green text-white":"bg-bambu-dark-tertiary text-bambu-gray-light hover:bg-bambu-dark"}`,children:v},v))})]}),l.size>0&&r.jsxs("div",{children:[r.jsxs("p",{className:"text-xs text-bambu-gray mb-2",children:["Tags to ",d==="add"?"add":"remove",":"]}),r.jsx("div",{className:"flex flex-wrap gap-2",children:Array.from(l).map(v=>r.jsxs("span",{className:`px-2 py-1 rounded text-sm flex items-center gap-1 ${d==="add"?"bg-green-500/20 text-green-400":"bg-red-500/20 text-red-400"}`,children:[v,r.jsx("button",{onClick:()=>p(v),className:"hover:opacity-70",children:r.jsx(Ht,{className:"w-3 h-3"})})]},v))})]})]}),r.jsxs("div",{className:"flex gap-3 p-4 border-t border-bambu-dark-tertiary",children:[r.jsx(Le,{variant:"secondary",onClick:a,className:"flex-1",children:"Cancel"}),r.jsx(Le,{onClick:()=>m.mutate(),disabled:l.size===0||m.isPending,className:"flex-1",children:m.isPending?r.jsxs(r.Fragment,{children:[r.jsx(lt,{className:"w-4 h-4 animate-spin"}),"Processing..."]}):r.jsxs(r.Fragment,{children:[r.jsx(Xm,{className:"w-4 h-4"}),d==="add"?"Add Tags":"Remove Tags"]})})]})]})})})}function L7e({selectedIds:t,onClose:e}){const{t:a}=wt(),n=na(),{showToast:i}=oa(),[s,o]=y.useState(""),{data:l,isLoading:c}=$e({queryKey:["projects"],queryFn:()=>ne.getProjects()}),d=y.useMemo(()=>l?[...l].sort((x,S)=>x.name.localeCompare(S.name)):void 0,[l]),u=s.trim().toLowerCase(),m=u?d?.filter(x=>x.name.toLowerCase().includes(u)):d,p=(d?.length??0)>5;y.useEffect(()=>{const x=S=>{S.key==="Escape"&&e()};return window.addEventListener("keydown",x),()=>window.removeEventListener("keydown",x)},[e]);const f=()=>{n.invalidateQueries({queryKey:["archives"]}),n.invalidateQueries({queryKey:["projects"]}),n.invalidateQueries({queryKey:["project"]}),n.invalidateQueries({queryKey:["project-archives"]})},g=at({mutationFn:async x=>(await ne.addArchivesToProject(x,t),x),onSuccess:x=>{const S=l?.find(k=>k.id===x);f(),i(`Added ${t.length} archive${t.length!==1?"s":""} to "${S?.name}"`),e()},onError:()=>{i("Failed to assign project","error")}}),v=at({mutationFn:async()=>{for(const x of t)await ne.updateArchive(x,{project_id:null});return t.length},onSuccess:x=>{f(),i(`Removed ${x} archive${x!==1?"s":""} from project`),e()},onError:()=>{i("Failed to remove from project","error")}}),b=g.isPending||v.isPending;return r.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:r.jsx(Tt,{className:"w-full max-w-md max-h-[80vh] flex flex-col",children:r.jsxs(jt,{className:"p-0 flex flex-col min-h-0",children:[r.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary shrink-0",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(no,{className:"w-5 h-5 text-bambu-green"}),r.jsx("h2",{className:"text-xl font-semibold text-white",children:"Assign to Project"})]}),r.jsx("button",{onClick:e,className:"text-bambu-gray hover:text-white transition-colors",disabled:b,children:r.jsx(Ht,{className:"w-5 h-5"})})]}),r.jsxs("div",{className:"p-4 space-y-3 overflow-y-auto min-h-0",children:[r.jsxs("p",{className:"text-sm text-bambu-gray",children:["Assign ",t.length," selected archive",t.length!==1?"s":""," to a project"]}),c?r.jsx("div",{className:"flex items-center justify-center py-8",children:r.jsx(lt,{className:"w-6 h-6 animate-spin text-bambu-gray"})}):r.jsxs("div",{className:"space-y-2",children:[r.jsxs("button",{onClick:()=>v.mutate(),disabled:b,className:"w-full flex items-center gap-3 p-3 rounded-lg bg-bambu-dark hover:bg-bambu-dark-tertiary border border-bambu-dark-tertiary transition-colors text-left disabled:opacity-50",children:[r.jsx("div",{className:"w-8 h-8 rounded-full bg-red-500/20 flex items-center justify-center shrink-0",children:r.jsx(Fr,{className:"w-4 h-4 text-red-400"})}),r.jsxs("div",{className:"min-w-0 flex-1",children:[r.jsx("p",{className:"text-white font-medium",children:"Remove from project"}),r.jsx("p",{className:"text-sm text-bambu-gray truncate",children:"Clear project assignment"})]}),v.isPending&&r.jsx(lt,{className:"w-4 h-4 animate-spin text-bambu-gray shrink-0"})]}),d&&d.length>0&&r.jsxs("div",{className:"flex items-center gap-2 py-2",children:[r.jsx("div",{className:"flex-1 h-px bg-bambu-dark-tertiary"}),r.jsx("span",{className:"text-xs text-bambu-gray",children:"or assign to"}),r.jsx("div",{className:"flex-1 h-px bg-bambu-dark-tertiary"})]}),p&&r.jsxs("div",{className:"relative",children:[r.jsx(br,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"}),r.jsx("input",{type:"text",value:s,onChange:x=>o(x.target.value),placeholder:a("archives.menu.searchProjects"),className:"w-full pl-9 pr-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray text-sm focus:border-bambu-green focus:outline-none"})]}),m?.map(x=>r.jsxs("button",{onClick:()=>g.mutate(x.id),disabled:b,className:"w-full flex items-center gap-3 p-3 rounded-lg bg-bambu-dark hover:bg-bambu-dark-tertiary border border-bambu-dark-tertiary transition-colors text-left disabled:opacity-50",children:[r.jsx("div",{className:"w-8 h-8 rounded-full flex items-center justify-center shrink-0",style:{backgroundColor:x.color?`${x.color}20`:"rgb(var(--bambu-green) / 0.2)"},children:r.jsx(no,{className:"w-4 h-4",style:{color:x.color||"rgb(var(--bambu-green))"}})}),r.jsxs("div",{className:"min-w-0 flex-1",children:[r.jsx("p",{className:"text-white font-medium truncate",children:x.name}),r.jsxs("p",{className:"text-sm text-bambu-gray truncate",children:[x.archive_count," archive",x.archive_count!==1?"s":"",x.status&&` • ${x.status}`]})]}),g.isPending&&g.variables===x.id&&r.jsx(lt,{className:"w-4 h-4 animate-spin text-bambu-gray shrink-0"})]},x.id)),(!d||d.length===0)&&r.jsx("p",{className:"text-center text-bambu-gray py-4",children:"No projects yet. Create one from the Projects page."}),d&&d.length>0&&m?.length===0&&r.jsx("p",{className:"text-center text-bambu-gray text-sm py-4",children:"—"})]})]}),r.jsx("div",{className:"flex gap-3 p-4 border-t border-bambu-dark-tertiary shrink-0",children:r.jsx(Le,{variant:"secondary",onClick:e,className:"flex-1",disabled:b,children:"Cancel"})})]})})})}function R7e(t,e){return new Date(t,e+1,0).getDate()}function z7e(t,e){return new Date(t,e,1).getDay()}const I7e=["January","February","March","April","May","June","July","August","September","October","November","December"],O7e=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];function B7e({archives:t,onArchiveClick:e,highlightedArchiveId:a}){const n=new Date,[i,s]=y.useState(n.getMonth()),[o,l]=y.useState(n.getFullYear()),[c,d]=y.useState(null),[u,m]=y.useState(null),p=y.useMemo(()=>{const N=new Map;return t.forEach(T=>{const j=Ga(T.completed_at||T.created_at)||new Date,D=`${j.getFullYear()}-${String(j.getMonth()+1).padStart(2,"0")}-${String(j.getDate()).padStart(2,"0")}`,P=N.get(D)||[];P.push(T),N.set(D,P)}),N},[t]),f=R7e(o,i),g=z7e(o,i),v=()=>{i===0?(s(11),l(o-1)):s(i-1)},b=()=>{i===11?(s(0),l(o+1)):s(i+1)},x=()=>{s(n.getMonth()),l(n.getFullYear())},S=[];for(let N=0;N{N!==c&&m(null),d(N)};return r.jsxs("div",{className:"flex flex-col lg:flex-row gap-6",children:[r.jsxs("div",{className:"flex-1",children:[r.jsxs("div",{className:"flex items-center justify-between mb-4",children:[r.jsx("button",{onClick:v,className:"p-2 hover:bg-bambu-dark-tertiary rounded-lg transition-colors",children:r.jsx(Jo,{className:"w-5 h-5 text-bambu-gray"})}),r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsxs("h2",{className:"text-lg font-semibold text-white",children:[I7e[i]," ",o]}),r.jsx("button",{onClick:x,className:"px-2 py-1 text-xs bg-bambu-dark-tertiary hover:bg-bambu-green/20 text-bambu-gray hover:text-white rounded transition-colors",children:"Today"})]}),r.jsx("button",{onClick:b,className:"p-2 hover:bg-bambu-dark-tertiary rounded-lg transition-colors",children:r.jsx(Vn,{className:"w-5 h-5 text-bambu-gray"})})]}),r.jsx("div",{className:"grid grid-cols-7 gap-1 mb-1",children:O7e.map(N=>r.jsx("div",{className:"text-center text-xs text-bambu-gray py-2",children:N},N))}),r.jsx("div",{className:"grid grid-cols-7 gap-1",children:S.map((N,T)=>{if(N===null)return r.jsx("div",{className:"aspect-square"},`empty-${T}`);const j=`${o}-${String(i+1).padStart(2,"0")}-${String(N).padStart(2,"0")}`,D=p.get(j)||[],P=D.length>0,E=N===n.getDate()&&i===n.getMonth()&&o===n.getFullYear(),z=j===c,I=D.filter(R=>R.status==="completed").length,B=D.filter(R=>R.status==="failed").length;return r.jsxs("button",{onClick:()=>C(z?null:j),className:`aspect-square rounded-lg p-1 flex flex-col items-center justify-center transition-colors relative ${z?"bg-bambu-green text-white":E?"bg-bambu-green/20 text-white ring-2 ring-bambu-green":P?"bg-bambu-dark-tertiary hover:bg-bambu-dark-tertiary/70 text-white":"hover:bg-bambu-dark-tertiary/50 text-bambu-gray"}`,children:[r.jsx("span",{className:`text-sm font-medium ${E&&!z?"text-bambu-green":""}`,children:N}),P&&r.jsxs("div",{className:"absolute bottom-1 left-1/2 -translate-x-1/2 flex items-center gap-1",children:[r.jsx("div",{className:`w-2 h-2 rounded-full ${B>0&&I===0?"bg-red-400":B>0?"bg-yellow-400":"bg-green-400"}`}),r.jsx("span",{className:"text-xs font-medium",children:D.length})]})]},N)})}),r.jsx("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary",children:r.jsxs("div",{className:"grid grid-cols-3 gap-4 text-center",children:[r.jsxs("div",{children:[r.jsx("div",{className:"text-2xl font-bold text-white",children:t.filter(N=>{const T=Ga(N.completed_at||N.created_at)||new Date;return T.getMonth()===i&&T.getFullYear()===o}).length}),r.jsx("div",{className:"text-xs text-bambu-gray",children:"Prints this month"})]}),r.jsxs("div",{children:[r.jsx("div",{className:"text-2xl font-bold text-green-400",children:t.filter(N=>{const T=Ga(N.completed_at||N.created_at)||new Date;return T.getMonth()===i&&T.getFullYear()===o&&N.status==="completed"}).length}),r.jsx("div",{className:"text-xs text-bambu-gray",children:"Successful"})]}),r.jsxs("div",{children:[r.jsx("div",{className:"text-2xl font-bold text-red-400",children:t.filter(N=>{const T=Ga(N.completed_at||N.created_at)||new Date;return T.getMonth()===i&&T.getFullYear()===o&&N.status==="failed"}).length}),r.jsx("div",{className:"text-xs text-bambu-gray",children:"Failed"})]})]})})]}),r.jsx("div",{className:"lg:w-80 bg-bambu-dark rounded-xl p-4",children:c?r.jsxs(r.Fragment,{children:[r.jsx("h3",{className:"text-sm font-medium text-bambu-gray mb-3",children:new Date(c+"T12:00:00").toLocaleDateString("en-US",{weekday:"long",month:"long",day:"numeric",year:"numeric"})}),k.length>0?r.jsx("div",{className:"calendar-scroll space-y-2 max-h-96 overflow-y-auto",children:k.map(N=>{const T=N.id===u||N.id===a;return r.jsxs("button",{onClick:()=>{m(N.id),e?.(N)},className:`w-full flex items-center gap-3 p-2 rounded-lg transition-colors text-left ${T?"":"hover:bg-bambu-dark-tertiary"}`,style:T?{outline:"4px solid #facc15",outlineOffset:"2px"}:void 0,children:[N.thumbnail_path?r.jsx("img",{src:ne.getArchiveThumbnail(N.id),alt:"",className:"w-12 h-12 rounded object-cover"}):r.jsx("div",{className:"w-12 h-12 rounded bg-bambu-dark-tertiary flex items-center justify-center",children:r.jsx("span",{className:"text-xs text-bambu-gray",children:"3MF"})}),r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsx("p",{className:"text-sm text-white truncate",children:N.print_name||N.filename}),r.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[r.jsx("span",{className:N.status==="failed"?"text-red-400":"text-green-400",children:N.status==="failed"?"Failed":"Completed"}),N.filament_color&&r.jsx("div",{className:"flex gap-0.5",children:N.filament_color.split(",").map((j,D)=>r.jsx("div",{className:"w-3 h-3 rounded-full border border-black/20",style:{backgroundColor:j}},D))})]})]})]},N.id)})}):r.jsx("p",{className:"text-sm text-bambu-gray",children:"No prints on this day"})]}):r.jsx("div",{className:"text-center py-8",children:r.jsx("p",{className:"text-sm text-bambu-gray",children:"Select a day to see prints"})})})]})}function Wse({archiveId:t,archiveName:e,onClose:a}){const n=ne.getArchiveQRCodeUrl(t,300);y.useEffect(()=>{const s=o=>{o.key==="Escape"&&a()};return window.addEventListener("keydown",s),()=>window.removeEventListener("keydown",s)},[a]);const i=()=>{const s=document.createElement("a");s.href=n,s.download=`${e}_qrcode.png`,s.click()};return r.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:a,children:r.jsxs("div",{className:"bg-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary w-full max-w-sm",onClick:s=>s.stopPropagation(),children:[r.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary",children:[r.jsx("h2",{className:"text-lg font-semibold text-white",children:"QR Code"}),r.jsx("button",{onClick:a,className:"text-bambu-gray hover:text-white transition-colors",children:r.jsx(Ht,{className:"w-5 h-5"})})]}),r.jsxs("div",{className:"p-6 flex flex-col items-center",children:[r.jsx("p",{className:"text-sm text-bambu-gray mb-4 text-center truncate max-w-full",children:e}),r.jsx("div",{className:"bg-white p-4 rounded-lg mb-4",children:r.jsx("img",{src:n,alt:"QR Code",className:"w-64 h-64"})}),r.jsx("p",{className:"text-xs text-bambu-gray mb-4 text-center",children:"Scan to open this archive"}),r.jsxs(Le,{onClick:i,className:"w-full",children:[r.jsx(Ur,{className:"w-4 h-4"}),"Download QR Code"]})]})]})})}function Kse({archiveId:t,archiveName:e,photos:a,onClose:n,onDelete:i}){const[s,o]=y.useState(0),[l,c]=y.useState(!1);if(y.useEffect(()=>{const f=g=>{g.key==="Escape"&&n(),g.key==="ArrowLeft"&&o(v=>Math.max(0,v-1)),g.key==="ArrowRight"&&o(v=>Math.min(a.length-1,v+1))};return window.addEventListener("keydown",f),()=>window.removeEventListener("keydown",f)},[n,a.length]),y.useEffect(()=>{s>=a.length&&o(Math.max(0,a.length-1))},[a.length,s]),a.length===0)return n(),null;const d=a[s],u=ne.getArchivePhotoUrl(t,d),m=()=>{const f=document.createElement("a");f.href=u,f.download=`${e}_photo_${s+1}.jpg`,f.click()},p=()=>{i&&c(!0)};return r.jsxs("div",{className:"fixed inset-0 bg-black/90 flex items-center justify-center z-50",onClick:n,children:[r.jsxs("div",{className:"relative w-full h-full flex flex-col",onClick:f=>f.stopPropagation(),children:[r.jsxs("div",{className:"flex items-center justify-between px-6 py-4 bg-black/50",children:[r.jsxs("div",{children:[r.jsx("h2",{className:"text-lg font-semibold text-white",children:e}),r.jsxs("p",{className:"text-sm text-bambu-gray",children:["Photo ",s+1," of ",a.length]})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsxs(Le,{variant:"secondary",size:"sm",onClick:m,children:[r.jsx(Ur,{className:"w-4 h-4"}),"Download"]}),i&&r.jsx(Le,{variant:"secondary",size:"sm",onClick:p,className:"text-red-400 hover:text-red-300",children:r.jsx(ra,{className:"w-4 h-4"})}),r.jsx("button",{onClick:n,className:"p-2 text-bambu-gray hover:text-white transition-colors",children:r.jsx(Ht,{className:"w-6 h-6"})})]})]}),r.jsxs("div",{className:"flex-1 min-h-0 flex items-center justify-center p-4 relative overflow-hidden",children:[s>0&&r.jsx("button",{onClick:()=>o(f=>f-1),className:"absolute left-4 z-10 p-3 bg-black/50 hover:bg-black/70 rounded-full transition-colors",children:r.jsx(Jo,{className:"w-8 h-8 text-white"})}),r.jsx("img",{src:u,alt:`Photo ${s+1}`,className:"max-w-full max-h-full object-contain rounded-lg",style:{maxHeight:"calc(100vh - 200px)"}}),so(f=>f+1),className:"absolute right-4 z-10 p-3 bg-black/50 hover:bg-black/70 rounded-full transition-colors",children:r.jsx(Vn,{className:"w-8 h-8 text-white"})})]}),a.length>1&&r.jsx("div",{className:"flex justify-center gap-2 p-4 bg-black/50",children:a.map((f,g)=>r.jsx("button",{onClick:()=>o(g),className:`w-16 h-16 rounded-lg overflow-hidden border-2 transition-colors ${g===s?"border-bambu-green":"border-transparent hover:border-bambu-gray"}`,children:r.jsx("img",{src:ne.getArchivePhotoUrl(t,f),alt:`Thumbnail ${g+1}`,className:"w-full h-full object-cover"})},f))})]}),l&&r.jsx(ka,{title:"Delete Photo",message:"Delete this photo? This cannot be undone.",confirmText:"Delete",variant:"danger",onConfirm:()=>{i?.(d),c(!1)},onCancel:()=>c(!1)})]})}const{entries:Yse,setPrototypeOf:jY,isFrozen:U7e,getPrototypeOf:H7e,getOwnPropertyDescriptor:q7e}=Object;let{freeze:Co,seal:Rc,create:Q0}=Object,{apply:Tz,construct:Az}=typeof Reflect<"u"&&Reflect;Co||(Co=function(e){return e});Rc||(Rc=function(e){return e});Tz||(Tz=function(e,a){for(var n=arguments.length,i=new Array(n>2?n-2:0),s=2;s1?a-1:0),i=1;i1?a-1:0),i=1;i2&&arguments[2]!==void 0?arguments[2]:KC;jY&&jY(t,null);let n=e.length;for(;n--;){let i=e[n];if(typeof i=="string"){const s=a(i);s!==i&&(U7e(e)||(e[n]=s),i=s)}t[i]=!0}return t}function Y7e(t){for(let e=0;e/gm),eKe=Rc(/\$\{[\w\W]*/gm),tKe=Rc(/^data-[\-\w.\u00B7-\uFFFF]+$/),aKe=Rc(/^aria-[\-\w]+$/),Qse=Rc(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),rKe=Rc(/^(?:\w+script|data):/i),nKe=Rc(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),Xse=Rc(/^html$/i),iKe=Rc(/^[a-z][.\w]*(-[.\w]+)+$/i);var RY=Object.freeze({__proto__:null,ARIA_ATTR:aKe,ATTR_WHITESPACE:nKe,CUSTOM_ELEMENT:iKe,DATA_ATTR:tKe,DOCTYPE_NAME:Xse,ERB_EXPR:J7e,IS_ALLOWED_URI:Qse,IS_SCRIPT_OR_DATA:rKe,MUSTACHE_EXPR:Z7e,TMPLIT_EXPR:eKe});const R0={element:1,text:3,progressingInstruction:7,comment:8,document:9},sKe=function(){return typeof window>"u"?null:window},oKe=function(e,a){if(typeof e!="object"||typeof e.createPolicy!="function")return null;let n=null;const i="data-tt-policy-suffix";a&&a.hasAttribute(i)&&(n=a.getAttribute(i));const s="dompurify"+(n?"#"+n:"");try{return e.createPolicy(s,{createHTML(o){return o},createScriptURL(o){return o}})}catch{return console.warn("TrustedTypes policy "+s+" could not be created."),null}},zY=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}};function Zse(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:sKe();const e=Ae=>Zse(Ae);if(e.version="3.4.0",e.removed=[],!t||!t.document||t.document.nodeType!==R0.document||!t.Element)return e.isSupported=!1,e;let{document:a}=t;const n=a,i=n.currentScript,{DocumentFragment:s,HTMLTemplateElement:o,Node:l,Element:c,NodeFilter:d,NamedNodeMap:u=t.NamedNodeMap||t.MozNamedAttrMap,HTMLFormElement:m,DOMParser:p,trustedTypes:f}=t,g=c.prototype,v=L0(g,"cloneNode"),b=L0(g,"remove"),x=L0(g,"nextSibling"),S=L0(g,"childNodes"),k=L0(g,"parentNode");if(typeof o=="function"){const Ae=a.createElement("template");Ae.content&&Ae.content.ownerDocument&&(a=Ae.content.ownerDocument)}let C,N="";const{implementation:T,createNodeIterator:j,createDocumentFragment:D,getElementsByTagName:P}=a,{importNode:E}=n;let z=zY();e.isSupported=typeof Yse=="function"&&typeof k=="function"&&T&&T.createHTMLDocument!==void 0;const{MUSTACHE_EXPR:I,ERB_EXPR:B,TMPLIT_EXPR:R,DATA_ATTR:K,ARIA_ATTR:J,IS_SCRIPT_OR_DATA:X,ATTR_WHITESPACE:ce,CUSTOM_ELEMENT:de}=RY;let{IS_ALLOWED_URI:oe}=RY,Y=null;const ie=Sr({},[...EY,...UF,...HF,...qF,...DY]);let me=null;const he=Sr({},[...FY,...VF,...LY,...rC]);let xe=Object.seal(Q0(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),V=null,Q=null;const A=Object.seal(Q0(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}}));let F=!0,U=!0,$=!1,H=!0,le=!1,O=!0,q=!1,Z=!1,ee=!1,re=!1,se=!1,fe=!1,ue=!0,pe=!1;const G="user-content-";let L=!0,ae=!1,ge={},be=null;const ve=Sr({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","style","svg","template","thead","title","video","xmp"]);let De=null;const je=Sr({},["audio","video","img","source","image","track"]);let Te=null;const qe=Sr({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),Ce="http://www.w3.org/1998/Math/MathML",Ie="http://www.w3.org/2000/svg",Re="http://www.w3.org/1999/xhtml";let Ue=Re,ze=!1,nt=null;const Oe=Sr({},[Ce,Ie,Re],OF);let tt=Sr({},["mi","mo","mn","ms","mtext"]),Fe=Sr({},["annotation-xml"]);const Ke=Sr({},["title","style","font","a","script"]);let Ve=null;const Me=["application/xhtml+xml","text/html"],Be="text/html";let Qe=null,Ge=null;const Ee=a.createElement("form"),rt=function(Se){return Se instanceof RegExp||Se instanceof Function},Xe=function(){let Se=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!(Ge&&Ge===Se)){if((!Se||typeof Se!="object")&&(Se={}),Se=Kd(Se),Ve=Me.indexOf(Se.PARSER_MEDIA_TYPE)===-1?Be:Se.PARSER_MEDIA_TYPE,Qe=Ve==="application/xhtml+xml"?OF:KC,Y=rd(Se,"ALLOWED_TAGS")?Sr({},Se.ALLOWED_TAGS,Qe):ie,me=rd(Se,"ALLOWED_ATTR")?Sr({},Se.ALLOWED_ATTR,Qe):he,nt=rd(Se,"ALLOWED_NAMESPACES")?Sr({},Se.ALLOWED_NAMESPACES,OF):Oe,Te=rd(Se,"ADD_URI_SAFE_ATTR")?Sr(Kd(qe),Se.ADD_URI_SAFE_ATTR,Qe):qe,De=rd(Se,"ADD_DATA_URI_TAGS")?Sr(Kd(je),Se.ADD_DATA_URI_TAGS,Qe):je,be=rd(Se,"FORBID_CONTENTS")?Sr({},Se.FORBID_CONTENTS,Qe):ve,V=rd(Se,"FORBID_TAGS")?Sr({},Se.FORBID_TAGS,Qe):Kd({}),Q=rd(Se,"FORBID_ATTR")?Sr({},Se.FORBID_ATTR,Qe):Kd({}),ge=rd(Se,"USE_PROFILES")?Se.USE_PROFILES:!1,F=Se.ALLOW_ARIA_ATTR!==!1,U=Se.ALLOW_DATA_ATTR!==!1,$=Se.ALLOW_UNKNOWN_PROTOCOLS||!1,H=Se.ALLOW_SELF_CLOSE_IN_ATTR!==!1,le=Se.SAFE_FOR_TEMPLATES||!1,O=Se.SAFE_FOR_XML!==!1,q=Se.WHOLE_DOCUMENT||!1,re=Se.RETURN_DOM||!1,se=Se.RETURN_DOM_FRAGMENT||!1,fe=Se.RETURN_TRUSTED_TYPE||!1,ee=Se.FORCE_BODY||!1,ue=Se.SANITIZE_DOM!==!1,pe=Se.SANITIZE_NAMED_PROPS||!1,L=Se.KEEP_CONTENT!==!1,ae=Se.IN_PLACE||!1,oe=Se.ALLOWED_URI_REGEXP||Qse,Ue=Se.NAMESPACE||Re,tt=Se.MATHML_TEXT_INTEGRATION_POINTS||tt,Fe=Se.HTML_INTEGRATION_POINTS||Fe,xe=Se.CUSTOM_ELEMENT_HANDLING||Q0(null),Se.CUSTOM_ELEMENT_HANDLING&&rt(Se.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(xe.tagNameCheck=Se.CUSTOM_ELEMENT_HANDLING.tagNameCheck),Se.CUSTOM_ELEMENT_HANDLING&&rt(Se.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(xe.attributeNameCheck=Se.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),Se.CUSTOM_ELEMENT_HANDLING&&typeof Se.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements=="boolean"&&(xe.allowCustomizedBuiltInElements=Se.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),le&&(U=!1),se&&(re=!0),ge&&(Y=Sr({},DY),me=Q0(null),ge.html===!0&&(Sr(Y,EY),Sr(me,FY)),ge.svg===!0&&(Sr(Y,UF),Sr(me,VF),Sr(me,rC)),ge.svgFilters===!0&&(Sr(Y,HF),Sr(me,VF),Sr(me,rC)),ge.mathMl===!0&&(Sr(Y,qF),Sr(me,LY),Sr(me,rC))),A.tagCheck=null,A.attributeCheck=null,Se.ADD_TAGS&&(typeof Se.ADD_TAGS=="function"?A.tagCheck=Se.ADD_TAGS:(Y===ie&&(Y=Kd(Y)),Sr(Y,Se.ADD_TAGS,Qe))),Se.ADD_ATTR&&(typeof Se.ADD_ATTR=="function"?A.attributeCheck=Se.ADD_ATTR:(me===he&&(me=Kd(me)),Sr(me,Se.ADD_ATTR,Qe))),Se.ADD_URI_SAFE_ATTR&&Sr(Te,Se.ADD_URI_SAFE_ATTR,Qe),Se.FORBID_CONTENTS&&(be===ve&&(be=Kd(be)),Sr(be,Se.FORBID_CONTENTS,Qe)),Se.ADD_FORBID_CONTENTS&&(be===ve&&(be=Kd(be)),Sr(be,Se.ADD_FORBID_CONTENTS,Qe)),L&&(Y["#text"]=!0),q&&Sr(Y,["html","head","body"]),Y.table&&(Sr(Y,["tbody"]),delete V.tbody),Se.TRUSTED_TYPES_POLICY){if(typeof Se.TRUSTED_TYPES_POLICY.createHTML!="function")throw F0('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof Se.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw F0('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');C=Se.TRUSTED_TYPES_POLICY,N=C.createHTML("")}else C===void 0&&(C=oKe(f,i)),C!==null&&typeof N=="string"&&(N=C.createHTML(""));Co&&Co(Se),Ge=Se}},Nt=Sr({},[...UF,...HF,...Q7e]),Vt=Sr({},[...qF,...X7e]),ht=function(Se){let ct=k(Se);(!ct||!ct.tagName)&&(ct={namespaceURI:Ue,tagName:"template"});const Ne=KC(Se.tagName),We=KC(ct.tagName);return nt[Se.namespaceURI]?Se.namespaceURI===Ie?ct.namespaceURI===Re?Ne==="svg":ct.namespaceURI===Ce?Ne==="svg"&&(We==="annotation-xml"||tt[We]):!!Nt[Ne]:Se.namespaceURI===Ce?ct.namespaceURI===Re?Ne==="math":ct.namespaceURI===Ie?Ne==="math"&&Fe[We]:!!Vt[Ne]:Se.namespaceURI===Re?ct.namespaceURI===Ie&&!Fe[We]||ct.namespaceURI===Ce&&!tt[We]?!1:!Vt[Ne]&&(Ke[Ne]||!Nt[Ne]):!!(Ve==="application/xhtml+xml"&&nt[Se.namespaceURI]):!1},It=function(Se){D0(e.removed,{element:Se});try{k(Se).removeChild(Se)}catch{b(Se)}},Xt=function(Se,ct){try{D0(e.removed,{attribute:ct.getAttributeNode(Se),from:ct})}catch{D0(e.removed,{attribute:null,from:ct})}if(ct.removeAttribute(Se),Se==="is")if(re||se)try{It(ct)}catch{}else try{ct.setAttribute(Se,"")}catch{}},la=function(Se){let ct=null,Ne=null;if(ee)Se=""+Se;else{const Je=BF(Se,/^[\r\n\t ]+/);Ne=Je&&Je[0]}Ve==="application/xhtml+xml"&&Ue===Re&&(Se=''+Se+"");const We=C?C.createHTML(Se):Se;if(Ue===Re)try{ct=new p().parseFromString(We,Ve)}catch{}if(!ct||!ct.documentElement){ct=T.createDocument(Ue,"template",null);try{ct.documentElement.innerHTML=ze?N:We}catch{}}const st=ct.body||ct.documentElement;return Se&&Ne&&st.insertBefore(a.createTextNode(Ne),st.childNodes[0]||null),Ue===Re?P.call(ct,q?"html":"body")[0]:q?ct.documentElement:st},ca=function(Se){return j.call(Se.ownerDocument||Se,Se,d.SHOW_ELEMENT|d.SHOW_COMMENT|d.SHOW_TEXT|d.SHOW_PROCESSING_INSTRUCTION|d.SHOW_CDATA_SECTION,null)},ot=function(Se){return Se instanceof m&&(typeof Se.nodeName!="string"||typeof Se.textContent!="string"||typeof Se.removeChild!="function"||!(Se.attributes instanceof u)||typeof Se.removeAttribute!="function"||typeof Se.setAttribute!="function"||typeof Se.namespaceURI!="string"||typeof Se.insertBefore!="function"||typeof Se.hasChildNodes!="function")},vt=function(Se){return typeof l=="function"&&Se instanceof l};function Ct(Ae,Se,ct){E0(Ae,Ne=>{Ne.call(e,Se,ct,Ge)})}const ea=function(Se){let ct=null;if(Ct(z.beforeSanitizeElements,Se,null),ot(Se))return It(Se),!0;const Ne=Qe(Se.nodeName);if(Ct(z.uponSanitizeElement,Se,{tagName:Ne,allowedTags:Y}),O&&Se.hasChildNodes()&&!vt(Se.firstElementChild)&&fo(/<[/\w!]/g,Se.innerHTML)&&fo(/<[/\w!]/g,Se.textContent)||O&&Se.namespaceURI===Re&&Ne==="style"&&vt(Se.firstElementChild)||Se.nodeType===R0.progressingInstruction||O&&Se.nodeType===R0.comment&&fo(/<[/\w]/g,Se.data))return It(Se),!0;if(V[Ne]||!(A.tagCheck instanceof Function&&A.tagCheck(Ne))&&!Y[Ne]){if(!V[Ne]&&Pe(Ne)&&(xe.tagNameCheck instanceof RegExp&&fo(xe.tagNameCheck,Ne)||xe.tagNameCheck instanceof Function&&xe.tagNameCheck(Ne)))return!1;if(L&&!be[Ne]){const We=k(Se)||Se.parentNode,st=S(Se)||Se.childNodes;if(st&&We){const Je=st.length;for(let Ze=Je-1;Ze>=0;--Ze){const kt=v(st[Ze],!0);kt.__removalCount=(Se.__removalCount||0)+1,We.insertBefore(kt,x(Se))}}}return It(Se),!0}return Se instanceof c&&!ht(Se)||(Ne==="noscript"||Ne==="noembed"||Ne==="noframes")&&fo(/<\/no(script|embed|frames)/i,Se.innerHTML)?(It(Se),!0):(le&&Se.nodeType===R0.text&&(ct=Se.textContent,E0([I,B,R],We=>{ct=Bx(ct,We," ")}),Se.textContent!==ct&&(D0(e.removed,{element:Se.cloneNode()}),Se.textContent=ct)),Ct(z.afterSanitizeElements,Se,null),!1)},aa=function(Se,ct,Ne){if(Q[ct]||ue&&(ct==="id"||ct==="name")&&(Ne in a||Ne in Ee))return!1;if(!(U&&!Q[ct]&&fo(K,ct))){if(!(F&&fo(J,ct))){if(!(A.attributeCheck instanceof Function&&A.attributeCheck(ct,Se))){if(!me[ct]||Q[ct]){if(!(Pe(Se)&&(xe.tagNameCheck instanceof RegExp&&fo(xe.tagNameCheck,Se)||xe.tagNameCheck instanceof Function&&xe.tagNameCheck(Se))&&(xe.attributeNameCheck instanceof RegExp&&fo(xe.attributeNameCheck,ct)||xe.attributeNameCheck instanceof Function&&xe.attributeNameCheck(ct,Se))||ct==="is"&&xe.allowCustomizedBuiltInElements&&(xe.tagNameCheck instanceof RegExp&&fo(xe.tagNameCheck,Ne)||xe.tagNameCheck instanceof Function&&xe.tagNameCheck(Ne))))return!1}else if(!Te[ct]){if(!fo(oe,Bx(Ne,ce,""))){if(!((ct==="src"||ct==="xlink:href"||ct==="href")&&Se!=="script"&&$7e(Ne,"data:")===0&&De[Se])){if(!($&&!fo(X,Bx(Ne,ce,"")))){if(Ne)return!1}}}}}}}return!0},Pe=function(Se){return Se!=="annotation-xml"&&BF(Se,de)},Ye=function(Se){Ct(z.beforeSanitizeAttributes,Se,null);const{attributes:ct}=Se;if(!ct||ot(Se))return;const Ne={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:me,forceKeepAttr:void 0};let We=ct.length;for(;We--;){const st=ct[We],{name:Je,namespaceURI:Ze,value:kt}=st,ft=Qe(Je),_t=kt;let St=Je==="value"?_t:W7e(_t);if(Ne.attrName=ft,Ne.attrValue=St,Ne.keepAttr=!0,Ne.forceKeepAttr=void 0,Ct(z.uponSanitizeAttribute,Se,Ne),St=Ne.attrValue,pe&&(ft==="id"||ft==="name")&&(Xt(Je,Se),St=G+St),O&&fo(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,St)){Xt(Je,Se);continue}if(ft==="attributename"&&BF(St,"href")){Xt(Je,Se);continue}if(Ne.forceKeepAttr)continue;if(!Ne.keepAttr){Xt(Je,Se);continue}if(!H&&fo(/\/>/i,St)){Xt(Je,Se);continue}le&&E0([I,B,R],yt=>{St=Bx(St,yt," ")});const qt=Qe(Se.nodeName);if(!aa(qt,ft,St)){Xt(Je,Se);continue}if(C&&typeof f=="object"&&typeof f.getAttributeType=="function"&&!Ze)switch(f.getAttributeType(qt,ft)){case"TrustedHTML":{St=C.createHTML(St);break}case"TrustedScriptURL":{St=C.createScriptURL(St);break}}if(St!==_t)try{Ze?Se.setAttributeNS(Ze,Je,St):Se.setAttribute(Je,St),ot(Se)?It(Se):MY(e.removed)}catch{Xt(Je,Se)}}Ct(z.afterSanitizeAttributes,Se,null)},it=function(Se){let ct=null;const Ne=ca(Se);for(Ct(z.beforeSanitizeShadowDOM,Se,null);ct=Ne.nextNode();)Ct(z.uponSanitizeShadowNode,ct,null),ea(ct),Ye(ct),ct.content instanceof s&&it(ct.content);Ct(z.afterSanitizeShadowDOM,Se,null)};return e.sanitize=function(Ae){let Se=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},ct=null,Ne=null,We=null,st=null;if(ze=!Ae,ze&&(Ae=""),typeof Ae!="string"&&!vt(Ae))if(typeof Ae.toString=="function"){if(Ae=Ae.toString(),typeof Ae!="string")throw F0("dirty is not a string, aborting")}else throw F0("toString is not a function");if(!e.isSupported)return Ae;if(Z||Xe(Se),e.removed=[],typeof Ae=="string"&&(ae=!1),ae){if(Ae.nodeName){const kt=Qe(Ae.nodeName);if(!Y[kt]||V[kt])throw F0("root node is forbidden and cannot be sanitized in-place")}}else if(Ae instanceof l)ct=la(""),Ne=ct.ownerDocument.importNode(Ae,!0),Ne.nodeType===R0.element&&Ne.nodeName==="BODY"||Ne.nodeName==="HTML"?ct=Ne:ct.appendChild(Ne);else{if(!re&&!le&&!q&&Ae.indexOf("<")===-1)return C&&fe?C.createHTML(Ae):Ae;if(ct=la(Ae),!ct)return re?null:fe?N:""}ct&&ee&&It(ct.firstChild);const Je=ca(ae?Ae:ct);for(;We=Je.nextNode();)ea(We),Ye(We),We.content instanceof s&&it(We.content);if(ae)return Ae;if(re){if(le){ct.normalize();let kt=ct.innerHTML;E0([I,B,R],ft=>{kt=Bx(kt,ft," ")}),ct.innerHTML=kt}if(se)for(st=D.call(ct.ownerDocument);ct.firstChild;)st.appendChild(ct.firstChild);else st=ct;return(me.shadowroot||me.shadowrootmode)&&(st=E.call(n,st,!0)),st}let Ze=q?ct.outerHTML:ct.innerHTML;return q&&Y["!doctype"]&&ct.ownerDocument&&ct.ownerDocument.doctype&&ct.ownerDocument.doctype.name&&fo(Xse,ct.ownerDocument.doctype.name)&&(Ze=" + `,title:B("printers:control")?P(Bt?"printers.resume":"printers.pause"):P("printers.permission.noControl"),children:[Bt?r.jsx(gs,{className:"w-3 h-3"}):r.jsx(US,{className:"w-3 h-3"}),P(Bt?"printers.resume":"printers.pause")]})]})]})]})})(),(Mo?.length>0||ke.vt_tray.length>0)&&n==="expanded"&&(()=>{const dt=Mo.filter(ut=>ut.tray.length>1),Bt=Mo.filter(ut=>ut.tray.length===1),Yt=t.nozzle_count===2||ke?.temperatures?.nozzle_2!==void 0;return r.jsxs("div",{className:"mt-3",children:[r.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[r.jsx("span",{className:"text-[10px] uppercase tracking-wider text-bambu-gray font-medium",children:P("printers.filaments")}),r.jsx("div",{className:"flex-1 h-px bg-bambu-dark-tertiary/30"})]}),r.jsxs("div",{className:"space-y-3",children:[dt.length>0&&r.jsx("div",{className:"grid grid-cols-2 gap-3",children:dt.map(ut=>{const Da=Ol[String(ut.id)],qr=ut.id>=128?ut.id-128:ut.id,Xa=Da!==void 0?Da:qr,bn=Xa===1,En=Xa===0;return r.jsxs("div",{className:"p-2.5 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary/30",children:[r.jsxs("div",{className:"flex items-center justify-between mb-2",children:[r.jsxs("div",{className:"flex items-center gap-1.5",children:[r.jsx(PY,{ams:ut,printerId:t.id,label:qo(ut.id,ut.tray.length),amsLabels:$a,canEdit:B("printers:update"),onSaved:Oa,children:r.jsx("span",{className:"text-[10px] text-white font-medium cursor-default select-none",children:$a?.[ut.id]||qo(ut.id,ut.tray.length)})}),Yt&&(bn||En)&&r.jsx(yY,{side:bn?"L":"R"})]}),(ut.humidity!=null||ut.temp!=null)&&r.jsxs("div",{className:"flex items-center gap-1.5 max-[550px]:flex-col max-[550px]:items-start",children:[ut.humidity!=null&&r.jsx(wY,{humidity:ut.humidity,goodThreshold:s?.humidityGood,fairThreshold:s?.humidityFair,onClick:()=>ea({amsId:ut.id,amsLabel:qo(ut.id,ut.tray.length),mode:"humidity"}),compact:!0}),ut.temp!=null&&r.jsx(SY,{temp:ut.temp,goodThreshold:s?.tempGood,fairThreshold:s?.tempFair,onClick:()=>ea({amsId:ut.id,amsLabel:qo(ut.id,ut.tray.length),mode:"temperature"}),compact:!0}),ke.supports_drying&&(ut.module_type==="n3f"||ut.module_type==="n3s")&&B("printers:control")&&r.jsx("button",{disabled:!!(ut.dry_sf_reason?.length&&ut.dry_time===0),onClick:sa=>{if(ut.dry_time>0)Do.mutate(ut.id);else if(Fe===ut.id)Ke(null);else{const Dn=(ut.tray.find($c=>$c.tray_type)?.tray_type||"PLA").split(" ")[0].toUpperCase(),Qn=C[Dn]||C.PLA,ki=ut.module_type;Qe(Dn),Ee(Qn[ki]||Qn.n3f),Xe(ki==="n3s"?Qn.n3s_hours:Qn.n3f_hours),Vt(!1),Me(ut.module_type),Ke(ut.id);const Gc=sa.currentTarget.getBoundingClientRect();It($8({triggerRect:Gc,popoverWidth:bY,estimatedHeight:xY}))}},className:`flex items-center gap-0.5 px-1 py-0.5 rounded text-[9px] transition-colors ${ut.dry_time>0?"bg-amber-500/20 text-amber-400":ut.dry_sf_reason?.length?"bg-bambu-dark-tertiary/30 text-bambu-gray/50 cursor-not-allowed":"bg-bambu-dark-tertiary/50 text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary"}`,title:ut.dry_time>0?P("printers.drying.stop"):ut.dry_sf_reason?.length?P("printers.drying.powerRequired"):P("printers.drying.start"),children:r.jsx(ym,{className:"w-3 h-3"})})]})]}),ut.dry_time>0&&r.jsxs("div",{className:"flex items-center gap-2 px-2 py-1 mb-1 bg-amber-500/10 border border-amber-500/20 rounded text-[9px]",children:[r.jsx(ym,{className:"w-3 h-3 text-amber-400 shrink-0"}),r.jsx("span",{className:"text-amber-400 font-medium",children:P("printers.drying.active")}),r.jsx("span",{className:"text-amber-300/70",children:P("printers.drying.timeRemaining",{time:ut.dry_time>=60?`${Math.floor(ut.dry_time/60)}h ${ut.dry_time%60}m`:`${ut.dry_time}m`})}),r.jsx("button",{onClick:()=>Do.mutate(ut.id),disabled:Do.isPending,className:"ml-auto text-amber-400 hover:text-amber-300 transition-colors disabled:opacity-50",title:P("printers.drying.stop"),children:r.jsx(Ht,{className:"w-3 h-3"})})]}),r.jsx("div",{className:"grid grid-cols-4 gap-1.5",children:[0,1,2,3].map(sa=>{const Ta=ut.tray[sa]||ut.tray.find(ha=>ha.id===sa),Dn=Ta?.tray_type&&Ta.remain>=0,Qn=!Ta?.tray_type,ki=DF(Ta),Gc=ut.id*4+sa,$c=ir===Gc,Ou=Ta?.tray_info_idx?Jt?.[Ta.tray_info_idx]:null,Qr=fa?.[Gc],Xn=(Ta?.tray_uuid||Ta?.tag_uid||Sm(t.serial_number,ut.id,sa))?.toUpperCase(),Fn=Xn?l?.[Xn]:void 0,Ss=GC(Fn),Fo=o&&!g?f?.find(ha=>ha.printer_id===t.id&&ha.ams_id===ut.id&&ha.tray_id===sa):void 0,rn=Fo?p?.find(ha=>ha.id===Fo.spoolman_spool_id):void 0,Lo=rn&&(rn.label_weight??0)>0?Math.round(Math.max(0,(rn.label_weight??0)-rn.weight_used)/(rn.label_weight??1)*100):null,mo=u?.(t.id,ut.id,sa),_i=(()=>{const ha=mo?.spool;return ha&&ha.label_weight>0&&ha.weight_used!=null?Math.round(Math.max(0,ha.label_weight-ha.weight_used)/ha.label_weight*100):null})(),Md=_i===0&&Dn&&Ta.remain>0?null:_i,fi=Ss??Lo??Md??(Dn?Ta.remain:null),wr=Ss!==null||Lo!==null?"spoolman":Md!==null?"inventory":Dn?"ams":void 0,zr=Ta?.tray_type?{vendor:Qs(Ta)?"Bambu Lab":"Generic",profile:Qr?.preset_name||(rn?[rn.brand,rn.slicer_filament_name?.split("@")[0].trim()||rn.material].filter(Boolean).join(" ").trim():null)||mo?.spool?.slicer_filament_name||Ou?.name||Ta.tray_sub_brands||Ta.tray_type,colorName:_c(Ta.tray_color||""),colorHex:Ta.tray_color||null,kFactor:MF(Ta.k),fillLevel:fi,trayUuid:Ta.tray_uuid||null,tagUid:Ta.tag_uid||null,fillSource:wr}:null,Zn=Vl?.amsId===ut.id&&Vl?.slotId===sa,kp=r.jsxs("div",{className:`bg-bambu-dark-tertiary rounded p-1 text-center ${Qn?"opacity-50":""} ${$c?"ring-2 ring-bambu-green ring-offset-1 ring-offset-bambu-dark":""}`,children:[r.jsx(jF,{trayColor:Ta?.tray_color,trayType:Ta?.tray_type,isEmpty:Qn,emptyKind:ki,slotNumber:sa+1}),r.jsx("div",{className:"text-[9px] text-white font-bold truncate",children:Ta?.tray_type||P(ki==="reset"?"ams.slotUnconfigured":"ams.slotEmpty")}),r.jsx("div",{className:"mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden",children:fi!==null&&fi>=0&&!Qn&&Ta&&r.jsx("div",{className:"h-full rounded-full transition-all",style:{width:`${fi}%`,backgroundColor:by(fi)}})})]});return r.jsxs("div",{className:"relative group",children:[Zn&&r.jsx("div",{className:"absolute inset-0 bg-bambu-dark-tertiary/80 rounded flex items-center justify-center z-20",children:r.jsx(tr,{className:"w-4 h-4 text-bambu-green animate-spin"})}),ke?.state!=="RUNNING"&&r.jsx("button",{onClick:ha=>{ha.stopPropagation(),qs(hi?.amsId===ut.id&&hi?.slotId===sa?null:{amsId:ut.id,slotId:sa})},className:"absolute -top-1 -right-1 w-4 h-4 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-full flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity z-10 hover:bg-bambu-dark-tertiary",title:P("printers.slotOptions"),children:r.jsx(Cm,{className:"w-2.5 h-2.5 text-bambu-gray"})}),ke?.state!=="RUNNING"&&hi?.amsId===ut.id&&hi?.slotId===sa&&r.jsxs("div",{className:"absolute top-full left-0 mt-1 z-50 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl py-1 min-w-[120px]",children:[r.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-xs flex items-center gap-2 ${B("printers:ams_rfid")?"text-white hover:bg-bambu-dark-tertiary":"text-bambu-gray/50 cursor-not-allowed"}`,onClick:ha=>{ha.stopPropagation(),B("printers:ams_rfid")&&(Ru.mutate({amsId:ut.id,slotId:sa}),qs(null))},disabled:Zn||!B("printers:ams_rfid"),title:B("printers:ams_rfid")?void 0:P("printers.permission.noAmsRfid"),children:[r.jsx(tr,{className:`w-3 h-3 ${Zn?"animate-spin":""}`}),P("printers.rfid.reread")]}),r.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-xs flex items-center gap-2 ${B("printers:control")?"text-white hover:bg-bambu-dark-tertiary":"text-bambu-gray/50 cursor-not-allowed"}`,onClick:ha=>{ha.stopPropagation(),B("printers:control")&&(Td.mutate({trayId:ut.id*4+sa}),qs(null))},disabled:!B("printers:control"),title:B("printers:control")?void 0:P("printers.permission.noControl"),children:[r.jsx(lw,{className:"w-3 h-3"}),P("printers.ams.load")]}),r.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-xs flex items-center gap-2 ${B("printers:control")?"text-white hover:bg-bambu-dark-tertiary":"text-bambu-gray/50 cursor-not-allowed"}`,onClick:ha=>{ha.stopPropagation(),B("printers:control")&&(Ad.mutate(),qs(null))},disabled:!B("printers:control"),title:B("printers:control")?void 0:P("printers.permission.noControl"),children:[r.jsx(Sg,{className:"w-3 h-3"}),P("printers.ams.unload")]})]}),zr?r.jsx(_F,{data:zr,spoolman:{enabled:o,linkedSpoolId:Fo?.spoolman_spool_id??(Xn?l?.[Xn]?.id:void 0),spoolmanUrl:c,syncMode:d,onLinkSpool:o&&!Fo&&!mo?()=>{const ha=(zr.trayUuid||zr.tagUid||Sm(t.serial_number,ut.id,sa)).toUpperCase();Pe({tagUid:zr.tagUid||ha,trayUuid:zr.trayUuid||"",printerId:t.id,amsId:ut.id,trayId:sa})}:void 0,onUnlinkSpool:Fn?.id?()=>pi.mutate(Fn.id):void 0},inventory:(()=>{if(o){if(g)return;const Wc=Fo,nn=rn;return{assignedSpool:nn?{id:nn.id,material:nn.material,brand:nn.brand??null,color_name:nn.color_name??null,remainingWeightGrams:nn.label_weight?Math.max(0,Math.round(nn.label_weight-nn.weight_used)):void 0}:null,onAssignSpool:()=>it({printerId:t.id,amsId:ut.id,trayId:sa,trayInfo:{type:Ta?.tray_type||zr.profile,material:Ta?.tray_type??void 0,profile:zr.profile,color:zr.colorHex||"",location:`${qo(ut.id,ut.tray.length)} Slot ${sa+1}`}}),onUnassignSpool:nn&&!Qs(Ta)?()=>v?.(nn.id):void 0,isAssigned:!!Wc||Qs(Ta)}}const ha=u?.(t.id,ut.id,sa);return{assignedSpool:ha?.spool?{id:ha.spool.id,material:ha.spool.material,brand:ha.spool.brand,color_name:ha.spool.color_name,remainingWeightGrams:Math.max(0,Math.round(ha.spool.label_weight-ha.spool.weight_used))}:null,onAssignSpool:()=>it({printerId:t.id,amsId:ut.id,trayId:sa,trayInfo:{type:Ta?.tray_type||zr.profile,material:Ta?.tray_type??void 0,profile:zr.profile,color:zr.colorHex||"",location:`${qo(ut.id,ut.tray.length)} Slot ${sa+1}`}}),onUnassignSpool:ha&&!Qs(Ta)?()=>m?.(t.id,ut.id,sa):void 0,isAssigned:!!ha||Qs(Ta)}})(),configureSlot:{enabled:B("printers:control"),onConfigure:()=>Se({amsId:ut.id,trayId:sa,trayCount:ut.tray.length,trayType:Ta?.tray_type||void 0,trayColor:Ta?.tray_color||void 0,traySubBrands:Ta?.tray_sub_brands||void 0,trayInfoIdx:Ta?.tray_info_idx||void 0,extruderId:Da,caliIdx:Ta?.cali_idx,savedPresetId:Qr?.preset_id})},children:kp}):r.jsx(PF,{kind:ki??void 0,configureSlot:{enabled:B("printers:control"),onConfigure:()=>Se({amsId:ut.id,trayId:sa,trayCount:ut.tray.length,extruderId:Da})},onAssignSpool:()=>it({printerId:t.id,amsId:ut.id,trayId:sa,trayInfo:{type:"",material:void 0,profile:"",color:"",location:`${qo(ut.id,ut.tray.length)} Slot ${sa+1}`}}),children:kp})]},sa)})})]},ut.id)})}),(Bt.length>0||ke.vt_tray.length>0)&&r.jsxs("div",{className:"grid grid-cols-4 gap-3",children:[Bt.map(ut=>{const Da=Ol[String(ut.id)],qr=ut.id>=128?ut.id-128:ut.id,Xa=Da!==void 0?Da:qr,bn=Xa===1,En=Xa===0,sa=ut.tray[0],Ta=sa?.tray_type&&sa.remain>=0,Dn=!sa?.tray_type,Qn=DF(sa),ki=ib(ut.id,sa?.id??0,!1),Gc=ir===ki,$c=sa?.tray_info_idx?Jt?.[sa.tray_info_idx]:null,Ou=fa?.[ki],Qr=sa?.id??0,Xn=(sa?.tray_uuid||sa?.tag_uid||Sm(t.serial_number,ut.id,Qr))?.toUpperCase(),Fn=Xn?l?.[Xn]:void 0,Ss=GC(Fn),Fo=u?.(t.id,ut.id,Qr),rn=(()=>{const ha=Fo?.spool;return ha&&ha.label_weight>0&&ha.weight_used!=null?Math.round(Math.max(0,ha.label_weight-ha.weight_used)/ha.label_weight*100):null})(),Lo=rn===0&&Ta&&sa.remain>0?null:rn,mo=o&&!g?f?.find(ha=>ha.printer_id===t.id&&ha.ams_id===ut.id&&ha.tray_id===Qr):void 0,_i=mo?p?.find(ha=>ha.id===mo.spoolman_spool_id):void 0,Md=_i&&(_i.label_weight??0)>0?Math.round(Math.max(0,(_i.label_weight??0)-_i.weight_used)/(_i.label_weight??1)*100):null,fi=Ss??Md??Lo??(Ta?sa.remain:null),wr=Ss!==null||Md!==null?"spoolman":Lo!==null?"inventory":Ta?"ams":void 0,zr=sa?.tray_type?{vendor:Qs(sa)?"Bambu Lab":"Generic",profile:Ou?.preset_name||(_i?[_i.brand,_i.slicer_filament_name?.split("@")[0].trim()||_i.material].filter(Boolean).join(" ").trim():null)||Fo?.spool?.slicer_filament_name||$c?.name||sa.tray_sub_brands||sa.tray_type,colorName:_c(sa.tray_color||""),colorHex:sa.tray_color||null,kFactor:MF(sa.k),fillLevel:fi,trayUuid:sa.tray_uuid||null,tagUid:sa.tag_uid||null,fillSource:wr}:null,Zn=Vl?.amsId===ut.id&&Vl?.slotId===Qr,kp=r.jsxs("div",{className:`bg-bambu-dark-tertiary rounded p-1 text-center ${Dn?"opacity-50":""} ${Gc?"ring-2 ring-bambu-green ring-offset-1 ring-offset-bambu-dark":""}`,children:[r.jsx(jF,{trayColor:sa?.tray_color,trayType:sa?.tray_type,isEmpty:Dn,emptyKind:Qn,slotNumber:1}),r.jsx("div",{className:"text-[9px] text-white font-bold truncate",children:sa?.tray_type||P(Qn==="reset"?"ams.slotUnconfigured":"ams.slotEmpty")}),r.jsx("div",{className:"mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden",children:fi!==null&&fi>=0&&!Dn&&r.jsx("div",{className:"h-full rounded-full transition-all",style:{width:`${fi}%`,backgroundColor:by(fi)}})})]});return r.jsxs("div",{className:"p-2.5 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary/30",children:[r.jsxs("div",{className:"flex items-center gap-1 mb-2",children:[r.jsx(PY,{ams:ut,printerId:t.id,label:qo(ut.id,ut.tray.length),amsLabels:$a,canEdit:B("printers:update"),onSaved:Oa,children:r.jsx("span",{className:"text-[10px] text-white font-medium cursor-default select-none",children:$a?.[ut.id]||qo(ut.id,ut.tray.length)})}),Yt&&(bn||En)&&r.jsx(yY,{side:bn?"L":"R"}),ke.supports_drying&&(ut.module_type==="n3f"||ut.module_type==="n3s")&&B("printers:control")&&r.jsx("div",{className:"relative ml-auto",children:r.jsx("button",{onClick:ha=>{if(ut.dry_time>0)Do.mutate(ut.id);else if(Fe===ut.id)Ke(null);else{const nn=(ut.tray.find(jk=>jk.tray_type)?.tray_type||"PLA").split(" ")[0].toUpperCase(),Pf=C[nn]||C.PLA,Ed=ut.module_type;Qe(nn),Ee(Pf[Ed]||Pf.n3f),Xe(Ed==="n3s"?Pf.n3s_hours:Pf.n3f_hours),Vt(!1),Me(ut.module_type),Ke(ut.id);const Ak=ha.currentTarget.getBoundingClientRect();It($8({triggerRect:Ak,popoverWidth:bY,estimatedHeight:xY}))}},className:`flex items-center gap-0.5 px-1 py-0.5 rounded text-[9px] transition-colors ${ut.dry_time>0?"bg-amber-500/20 text-amber-400":"bg-bambu-dark-tertiary/50 text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary"}`,title:ut.dry_time>0?P("printers.drying.stop"):P("printers.drying.start"),children:r.jsx(ym,{className:"w-3 h-3"})})})]}),ut.dry_time>0&&r.jsxs("div",{className:"flex items-center gap-1.5 px-2 py-1 mb-1 bg-amber-500/10 border border-amber-500/20 rounded text-[9px] whitespace-nowrap overflow-hidden",children:[r.jsx(ym,{className:"w-3 h-3 text-amber-400 shrink-0"}),r.jsx("span",{className:"text-amber-300/70 text-[8px] truncate",children:ut.dry_time>=60?`${Math.floor(ut.dry_time/60)}h ${ut.dry_time%60}m`:`${ut.dry_time}m`}),r.jsx("button",{onClick:()=>Do.mutate(ut.id),disabled:Do.isPending,className:"ml-auto text-amber-400 hover:text-amber-300 transition-colors disabled:opacity-50 shrink-0",title:P("printers.drying.stop"),children:r.jsx(Ht,{className:"w-3 h-3"})})]}),r.jsxs("div",{className:"flex gap-1.5 max-[550px]:flex-col max-[550px]:items-start",children:[r.jsxs("div",{className:"relative group flex-1 max-[550px]:w-full",children:[Zn&&r.jsx("div",{className:"absolute inset-0 bg-bambu-dark-tertiary/80 rounded flex items-center justify-center z-20",children:r.jsx(tr,{className:"w-4 h-4 text-bambu-green animate-spin"})}),ke?.state!=="RUNNING"&&r.jsx("button",{onClick:ha=>{ha.stopPropagation(),qs(hi?.amsId===ut.id&&hi?.slotId===Qr?null:{amsId:ut.id,slotId:Qr})},className:"absolute -top-1 -right-1 w-4 h-4 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-full flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity z-10 hover:bg-bambu-dark-tertiary",title:P("printers.slotOptions"),children:r.jsx(Cm,{className:"w-2.5 h-2.5 text-bambu-gray"})}),ke?.state!=="RUNNING"&&hi?.amsId===ut.id&&hi?.slotId===Qr&&r.jsxs("div",{className:"absolute top-full left-0 mt-1 z-50 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl py-1 min-w-[120px]",children:[r.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-xs flex items-center gap-2 ${B("printers:ams_rfid")?"text-white hover:bg-bambu-dark-tertiary":"text-bambu-gray/50 cursor-not-allowed"}`,onClick:ha=>{ha.stopPropagation(),B("printers:ams_rfid")&&(Ru.mutate({amsId:ut.id,slotId:Qr}),qs(null))},disabled:Zn||!B("printers:ams_rfid"),title:B("printers:ams_rfid")?void 0:P("printers.permission.noAmsRfid"),children:[r.jsx(tr,{className:`w-3 h-3 ${Zn?"animate-spin":""}`}),P("printers.rfid.reread")]}),r.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-xs flex items-center gap-2 ${B("printers:control")?"text-white hover:bg-bambu-dark-tertiary":"text-bambu-gray/50 cursor-not-allowed"}`,onClick:ha=>{ha.stopPropagation(),B("printers:control")&&(Td.mutate({trayId:ut.id*4+Qr}),qs(null))},disabled:!B("printers:control"),title:B("printers:control")?void 0:P("printers.permission.noControl"),children:[r.jsx(lw,{className:"w-3 h-3"}),P("printers.ams.load")]}),r.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-xs flex items-center gap-2 ${B("printers:control")?"text-white hover:bg-bambu-dark-tertiary":"text-bambu-gray/50 cursor-not-allowed"}`,onClick:ha=>{ha.stopPropagation(),B("printers:control")&&(Ad.mutate(),qs(null))},disabled:!B("printers:control"),title:B("printers:control")?void 0:P("printers.permission.noControl"),children:[r.jsx(Sg,{className:"w-3 h-3"}),P("printers.ams.unload")]})]}),zr?r.jsx(_F,{data:zr,spoolman:{enabled:o,linkedSpoolId:mo?.spoolman_spool_id??(Xn?l?.[Xn]?.id:void 0),spoolmanUrl:c,syncMode:d,onLinkSpool:o&&!mo&&!Fo?()=>{const ha=(zr.trayUuid||zr.tagUid||Sm(t.serial_number,ut.id,Qr)).toUpperCase();Pe({tagUid:zr.tagUid||ha,trayUuid:zr.trayUuid||"",printerId:t.id,amsId:ut.id,trayId:Qr})}:void 0,onUnlinkSpool:Fn?.id?()=>pi.mutate(Fn.id):void 0},inventory:(()=>{if(o){if(g)return;const Wc=mo,nn=_i;return{assignedSpool:nn?{id:nn.id,material:nn.material,brand:nn.brand??null,color_name:nn.color_name??null,remainingWeightGrams:nn.label_weight?Math.max(0,Math.round(nn.label_weight-nn.weight_used)):void 0}:null,onAssignSpool:()=>it({printerId:t.id,amsId:ut.id,trayId:Qr,trayInfo:{type:sa?.tray_type||zr.profile,material:sa?.tray_type??void 0,profile:zr.profile,color:zr.colorHex||"",location:qo(ut.id,ut.tray.length)}}),onUnassignSpool:nn&&!Qs(sa)?()=>v?.(nn.id):void 0,isAssigned:!!Wc||Qs(sa)}}const ha=u?.(t.id,ut.id,Qr);return{assignedSpool:ha?.spool?{id:ha.spool.id,material:ha.spool.material,brand:ha.spool.brand,color_name:ha.spool.color_name,remainingWeightGrams:Math.max(0,Math.round(ha.spool.label_weight-ha.spool.weight_used))}:null,onAssignSpool:()=>it({printerId:t.id,amsId:ut.id,trayId:Qr,trayInfo:{type:sa?.tray_type||zr.profile,material:sa?.tray_type??void 0,profile:zr.profile,color:zr.colorHex||"",location:qo(ut.id,ut.tray.length)}}),onUnassignSpool:ha&&!Qs(sa)?()=>m?.(t.id,ut.id,Qr):void 0,isAssigned:!!ha||Qs(sa)}})(),configureSlot:{enabled:B("printers:control"),onConfigure:()=>Se({amsId:ut.id,trayId:Qr,trayCount:ut.tray.length,trayType:sa?.tray_type||void 0,trayColor:sa?.tray_color||void 0,traySubBrands:sa?.tray_sub_brands||void 0,trayInfoIdx:sa?.tray_info_idx||void 0,extruderId:Da,caliIdx:sa?.cali_idx,savedPresetId:Ou?.preset_id})},children:kp}):r.jsx(PF,{kind:Qn??void 0,configureSlot:{enabled:B("printers:control"),onConfigure:()=>Se({amsId:ut.id,trayId:Qr,trayCount:ut.tray.length,extruderId:Da})},onAssignSpool:()=>it({printerId:t.id,amsId:ut.id,trayId:Qr,trayInfo:{type:"",material:void 0,profile:"",color:"",location:qo(ut.id,ut.tray.length)}}),children:kp})]}),(ut.humidity!=null||ut.temp!=null)&&r.jsxs("div",{className:"flex flex-col justify-center gap-1 shrink-0 max-[550px]:w-full",children:[ut.temp!=null&&r.jsx(SY,{temp:ut.temp,goodThreshold:s?.tempGood,fairThreshold:s?.tempFair,onClick:()=>ea({amsId:ut.id,amsLabel:qo(ut.id,ut.tray.length),mode:"temperature"}),compact:!0}),ut.humidity!=null&&r.jsx(wY,{humidity:ut.humidity,goodThreshold:s?.humidityGood,fairThreshold:s?.humidityFair,onClick:()=>ea({amsId:ut.id,amsLabel:qo(ut.id,ut.tray.length),mode:"humidity"}),compact:!0})]})]})]},ut.id)}),ke.vt_tray.length>0&&r.jsxs("div",{className:`p-2.5 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary/30 ${ke.vt_tray.length===1?"max-w-[50%]":""}`,children:[r.jsx("div",{className:"flex items-center gap-1 mb-2",children:r.jsx("span",{className:"text-[10px] text-white font-medium",children:P("printers.external")})}),r.jsx("div",{className:`grid ${ke.vt_tray.length>1?"grid-cols-2":"grid-cols-1"} gap-1.5`,children:[...ke.vt_tray].sort((ut,Da)=>(ut.id??254)-(Da.id??254)).map(ut=>{const Da=ut.id??254,qr=Yt&&ir===254?Da===254&&ke.active_extruder===1||Da===255&&ke.active_extruder===0:ir===Da,Xa=Da-254,bn=Yt?P(Da===254?"printers.extL":"printers.extR"):"",En=ut.tray_info_idx?Jt?.[ut.tray_info_idx]:null,sa=fa?.[1020+Xa],Ta=(ut.tray_uuid||ut.tag_uid||Sm(t.serial_number,255,Xa))?.toUpperCase(),Dn=Ta?l?.[Ta]:void 0,Qn=GC(Dn),ki=u?.(t.id,255,Xa),Gc=(()=>{const wr=ki?.spool;return wr&&wr.label_weight>0&&wr.weight_used!=null?Math.round(Math.max(0,wr.label_weight-wr.weight_used)/wr.label_weight*100):null})(),$c=ut.tray_type&&ut.remain>=0,Ou=Gc===0&&$c&&ut.remain>0?null:Gc,Qr=o&&!g?f?.find(wr=>wr.printer_id===t.id&&wr.ams_id===255&&wr.tray_id===Xa):void 0,Xn=Qr?p?.find(wr=>wr.id===Qr.spoolman_spool_id):void 0,Fn=Xn&&(Xn.label_weight??0)>0?Math.round(Math.max(0,(Xn.label_weight??0)-Xn.weight_used)/(Xn.label_weight??1)*100):null,Ss=Qn??Fn??Ou??($c?ut.remain:null),Fo=Qn!==null||Fn!==null?"spoolman":Ou!==null?"inventory":$c?"ams":void 0,rn={vendor:Qs(ut)?"Bambu Lab":"Generic",profile:sa?.preset_name||(Xn?[Xn.brand,Xn.slicer_filament_name?.split("@")[0].trim()||Xn.material].filter(Boolean).join(" ").trim():null)||ki?.spool?.slicer_filament_name||En?.name||ut.tray_sub_brands||ut.tray_type||"Unknown",colorName:_c(ut.tray_color||""),colorHex:ut.tray_color||null,kFactor:MF(ut.k),fillLevel:Ss,trayUuid:ut.tray_uuid||null,tagUid:ut.tag_uid||null,fillSource:Fo},Lo=!ut.tray_type,mo=DF(ut),_i=r.jsxs("div",{className:`bg-bambu-dark-tertiary rounded p-1 text-center ${Lo?"opacity-50":""} ${qr?"ring-2 ring-bambu-green ring-offset-1 ring-offset-bambu-dark":""}`,children:[r.jsx(jF,{trayColor:ut.tray_color,trayType:ut.tray_type,isEmpty:Lo,emptyKind:mo,slotNumber:Xa+1}),r.jsx("div",{className:`text-[9px] font-bold truncate ${Lo?"text-white/40":"text-white"}`,children:ut.tray_type||P("ams.slotEmpty")}),r.jsx("div",{className:"mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden",children:Ss!==null&&Ss>=0&&!Lo&&r.jsx("div",{className:"h-full rounded-full transition-all",style:{width:`${Ss}%`,backgroundColor:by(Ss)}})}),bn&&r.jsx("div",{className:"text-[7px] text-white/40 mt-0.5 truncate",children:bn})]}),Md=2550+Xa,fi=hi?.amsId===255&&hi?.slotId===Md;return r.jsxs("div",{className:"relative group",children:[ke?.state!=="RUNNING"&&r.jsx("button",{onClick:wr=>{wr.stopPropagation(),qs(fi?null:{amsId:255,slotId:Md})},className:"absolute -top-1 -right-1 w-4 h-4 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-full flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity z-10 hover:bg-bambu-dark-tertiary",title:P("printers.slotOptions"),children:r.jsx(Cm,{className:"w-2.5 h-2.5 text-bambu-gray"})}),ke?.state!=="RUNNING"&&fi&&r.jsxs("div",{className:"absolute top-full left-0 mt-1 z-50 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl py-1 min-w-[120px]",children:[r.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-xs flex items-center gap-2 ${B("printers:control")?"text-white hover:bg-bambu-dark-tertiary":"text-bambu-gray/50 cursor-not-allowed"}`,onClick:wr=>{wr.stopPropagation(),B("printers:control")&&(Td.mutate({trayId:Da}),qs(null))},disabled:!B("printers:control"),title:B("printers:control")?void 0:P("printers.permission.noControl"),children:[r.jsx(lw,{className:"w-3 h-3"}),P("printers.ams.load")]}),r.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-xs flex items-center gap-2 ${B("printers:control")?"text-white hover:bg-bambu-dark-tertiary":"text-bambu-gray/50 cursor-not-allowed"}`,onClick:wr=>{wr.stopPropagation(),B("printers:control")&&(Ad.mutate(),qs(null))},disabled:!B("printers:control"),title:B("printers:control")?void 0:P("printers.permission.noControl"),children:[r.jsx(Sg,{className:"w-3 h-3"}),P("printers.ams.unload")]})]}),Lo?r.jsx(PF,{kind:mo??void 0,configureSlot:{enabled:B("printers:control"),onConfigure:()=>Se({amsId:255,trayId:Xa,trayCount:1,extruderId:Yt?Da===254?1:0:void 0})},onAssignSpool:()=>it({printerId:t.id,amsId:255,trayId:Xa,trayInfo:{type:"",material:void 0,profile:"",color:"",location:`External Slot ${Xa+1}`}}),children:_i}):r.jsx(_F,{data:rn,spoolman:{enabled:o,linkedSpoolId:Qr?.spoolman_spool_id??(Ta?l?.[Ta]?.id:void 0),spoolmanUrl:c,syncMode:d,onLinkSpool:o&&!Qr&&!ki?()=>{const wr=(rn.trayUuid||rn.tagUid||Sm(t.serial_number,255,Xa)).toUpperCase();Pe({tagUid:rn.tagUid||wr,trayUuid:rn.trayUuid||"",printerId:t.id,amsId:255,trayId:Xa})}:void 0,onUnlinkSpool:Dn?.id?()=>pi.mutate(Dn.id):void 0},inventory:(()=>{if(o){if(g)return;const zr=Qr,Zn=Xn;return{assignedSpool:Zn?{id:Zn.id,material:Zn.material,brand:Zn.brand??null,color_name:Zn.color_name??null,remainingWeightGrams:Zn.label_weight?Math.max(0,Math.round(Zn.label_weight-Zn.weight_used)):void 0}:null,onAssignSpool:()=>it({printerId:t.id,amsId:255,trayId:Xa,trayInfo:{type:ut.tray_type||rn.profile,material:ut.tray_type??void 0,profile:rn.profile,color:rn.colorHex||"",location:bn||P("printers.external")}}),onUnassignSpool:Zn&&!Qs(ut)?()=>v?.(Zn.id):void 0,isAssigned:!!zr||Qs(ut)}}const wr=u?.(t.id,255,Xa);return{assignedSpool:wr?.spool?{id:wr.spool.id,material:wr.spool.material,brand:wr.spool.brand,color_name:wr.spool.color_name,remainingWeightGrams:Math.max(0,Math.round(wr.spool.label_weight-wr.spool.weight_used))}:null,onAssignSpool:()=>it({printerId:t.id,amsId:255,trayId:Xa,trayInfo:{type:ut.tray_type||rn.profile,material:ut.tray_type??void 0,profile:rn.profile,color:rn.colorHex||"",location:bn||P("printers.external")}}),onUnassignSpool:wr&&!Qs(ut)?()=>m?.(t.id,255,Xa):void 0,isAssigned:!!wr||Qs(ut)}})(),configureSlot:{enabled:B("printers:control"),onConfigure:()=>Se({amsId:255,trayId:Xa,trayCount:1,trayType:ut.tray_type||void 0,trayColor:ut.tray_color||void 0,traySubBrands:ut.tray_sub_brands||void 0,trayInfoIdx:ut.tray_info_idx||void 0,extruderId:Yt?Da===254?1:0:void 0,caliIdx:ut.cali_idx,savedPresetId:sa?.preset_id})},children:_i})]},Da)})})]})]})]})]})})()]}),$t&&n==="expanded"&&r.jsxs("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[r.jsx(jc,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"}),r.jsx("span",{className:"text-sm text-white truncate",children:$t.name}),$r&&r.jsxs("span",{className:`text-xs px-1.5 py-0.5 rounded flex-shrink-0 ${$r.state==="ON"?"bg-bambu-green/20 text-bambu-green":$r.state==="OFF"?"bg-red-500/20 text-red-400":"bg-bambu-gray/20 text-bambu-gray"}`,children:[$r.state||"?",$r.state==="ON"&&$r.energy?.power!=null&&r.jsxs("span",{className:"text-yellow-400 ml-1.5",children:["· ",Math.round($r.energy.power),"W"]})]})]}),r.jsx("div",{className:"flex-1"}),r.jsxs("div",{className:"flex items-center gap-1",children:[r.jsxs("button",{onClick:()=>Q(!0),disabled:Bl.isPending||$r?.state==="ON"||!B("smart_plugs:control"),className:`px-2 py-1 text-xs rounded transition-colors flex items-center gap-1 ${B("smart_plugs:control")?$r?.state==="ON"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary":"bg-bambu-dark text-bambu-gray/50 cursor-not-allowed"}`,title:B("smart_plugs:control")?void 0:P("printers.permission.noSmartPlugControl"),children:[r.jsx(Tu,{className:"w-3 h-3"}),"On"]}),r.jsxs("button",{onClick:()=>F(!0),disabled:Bl.isPending||$r?.state==="OFF"||!B("smart_plugs:control"),className:`px-2 py-1 text-xs rounded transition-colors flex items-center gap-1 ${B("smart_plugs:control")?$r?.state==="OFF"?"bg-red-500/30 text-red-400":"bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary":"bg-bambu-dark text-bambu-gray/50 cursor-not-allowed"}`,title:B("smart_plugs:control")?void 0:P("printers.permission.noSmartPlugControl"),children:[r.jsx(HS,{className:"w-3 h-3"}),"Off"]})]}),r.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[r.jsx("span",{className:`text-xs hidden sm:inline ${$t.auto_off_executed?"text-bambu-green":"text-bambu-gray"}`,children:$t.auto_off_executed?"Auto-off done":"Auto-off"}),r.jsx("button",{onClick:()=>Hc.mutate(!$t.auto_off),disabled:Hc.isPending||$t.auto_off_executed||!B("smart_plugs:control"),title:B("smart_plugs:control")?$t.auto_off_executed?P("printers.autoOffExecuted"):P("printers.autoOffAfterPrint"):P("printers.permission.noSmartPlugControl"),className:`relative w-9 h-5 rounded-full transition-colors flex-shrink-0 ${B("smart_plugs:control")?$t.auto_off_executed?"bg-bambu-green/50 cursor-not-allowed":$t.auto_off?"bg-bambu-green":"bg-bambu-dark-tertiary":"bg-bambu-dark-tertiary/50 cursor-not-allowed"}`,children:r.jsx("span",{className:`absolute top-[2px] left-[2px] w-4 h-4 bg-white rounded-full transition-transform ${$t.auto_off||$t.auto_off_executed?"translate-x-4":"translate-x-0"}`})})]})]}),Eo&&Eo.length>0&&r.jsxs("div",{className:"flex items-center gap-2 mt-2 pt-2 border-t border-bambu-dark-tertiary/50",children:[r.jsx(zS,{className:"w-3.5 h-3.5 text-blue-400 flex-shrink-0"}),r.jsx("span",{className:"text-xs text-bambu-gray",children:"HA:"}),r.jsx("div",{className:"flex flex-wrap gap-1",children:Eo.map(dt=>{const Bt=dt.ha_entity_id?.startsWith("script.");return r.jsxs("button",{onClick:()=>{Bt?Fu.mutate({id:dt.id,action:"on"}):$(dt)},disabled:Fu.isPending,title:`${Bt?"Run":"Toggle"} ${dt.ha_entity_id}`,className:"px-2 py-0.5 text-xs bg-blue-500/20 text-blue-400 hover:bg-blue-500/30 rounded transition-colors flex items-center gap-1",children:[r.jsx(gs,{className:"w-2.5 h-2.5"}),dt.name]},dt.id)})})]})]}),n==="expanded"&&r.jsxs("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary flex items-center justify-end gap-2 flex-wrap",children:[r.jsx(Le,{variant:"secondary",size:"sm",onClick:()=>kb.mutate(!ke?.chamber_light),disabled:!ke?.connected||kb.isPending||!B("printers:control"),title:B("printers:control")?ke?.chamber_light?P("printers.chamberLightOff"):P("printers.chamberLightOn"):P("printers.permission.noControl"),className:ke?.chamber_light?"!border-yellow-500 !text-yellow-400 hover:!bg-yellow-500/20":"",children:r.jsx(PO,{on:ke?.chamber_light??!1,className:`w-4 h-4 ${ke?.chamber_light?"text-yellow-400":""}`})}),r.jsx(Le,{variant:"secondary",size:"sm",onClick:()=>{if(x==="embedded"&&S)S(t.id,t.name);else{const dt=localStorage.getItem("cameraWindowState"),Bt=dt?JSON.parse(dt):{width:640,height:400},Yt=[`width=${Bt.width}`,`height=${Bt.height}`,Bt.left!==void 0?`left=${Bt.left}`:"",Bt.top!==void 0?`top=${Bt.top}`:"","menubar=no,toolbar=no,location=no,status=no"].filter(Boolean).join(",");window.open(`/camera/${t.id}`,`camera-${t.id}`,Yt)}},disabled:!ke?.connected||!B("camera:view"),title:B("camera:view")?P(x==="embedded"?"printers.openCameraOverlay":"printers.openCameraWindow"):P("printers.permission.noCamera"),children:r.jsx(bN,{className:"w-4 h-4"})}),r.jsxs("div",{className:`inline-flex rounded-md ${t.plate_detection_enabled?"ring-1 ring-green-500":""}`,children:[r.jsx(Le,{variant:"secondary",size:"sm",onClick:kf,disabled:!ke?.connected||Lu.isPending||!B("printers:update"),title:B("printers:update")?t.plate_detection_enabled?P("printers.plateDetection.enabledClick"):P("printers.plateDetection.disabledClick"):P("printers.plateDetection.noPermission"),className:`!rounded-r-none !border-r-0 ${t.plate_detection_enabled?"!border-green-500 !text-green-400 hover:!bg-green-500/20":""}`,children:Lu.isPending?r.jsx(lt,{className:"w-4 h-4 animate-spin"}):r.jsx(fN,{className:"w-4 h-4"})}),r.jsx(Le,{variant:"secondary",size:"sm",onClick:Pb,disabled:!ke?.connected||Je||!B("printers:update"),title:B("printers:update")?P("printers.plateDetection.manageCalibration"):P("printers.plateDetection.noPermission"),className:`!rounded-l-none !px-1.5 ${t.plate_detection_enabled?"!border-green-500 !text-green-400 hover:!bg-green-500/20":""}`,children:Je?r.jsx(lt,{className:"w-3 h-3 animate-spin"}):r.jsx(za,{className:"w-3 h-3"})})]}),r.jsxs(Le,{variant:"secondary",size:"sm",onClick:()=>me(!0),disabled:!vr||!B("printers:files"),title:B("printers:files")?P("printers.browseFiles"):P("printers.permission.noFiles"),children:[r.jsx(hb,{className:"w-4 h-4"}),P("printers.files")]}),vr&&ke?.state!=="RUNNING"&&ke?.state!=="PAUSE"&&r.jsxs(Le,{size:"sm",onClick:()=>Ce(!0),disabled:!B("printers:control"),title:B("printers:control")?P("common.print"):P("printers.permission.noControl"),className:"!bg-bambu-green hover:!bg-bambu-green/80 !text-white",children:[r.jsx(xr,{className:"w-4 h-4"}),P("common.print")]})]})]}),ie&&r.jsx(QDe,{printerId:t.id,printerName:t.name,onClose:()=>me(!1)}),qe&&r.jsx(Ese,{folderId:null,onClose:()=>Ce(!1),onUploadComplete:()=>{},autoUpload:!0,accept:".gcode,.3mf",validateFile:dt=>{const Bt=dt.name.toLowerCase();if(!Bt.endsWith(".gcode")&&!Bt.includes(".gcode."))return P("printers.dropNotPrintable","Only .gcode and .gcode.3mf files can be printed")},onFileUploaded:dt=>{const Bt=dt.metadata?.sliced_for_model,Yt=bw(t.model);if(Bt&&Yt&&Bt.toLowerCase()!==Yt.toLowerCase())return ne.deleteLibraryFile(dt.id).catch(()=>{}),P("printers.incompatibleFile","This file was sliced for {{slicedFor}}, but this printer is a {{printerModel}}",{slicedFor:Bt,printerModel:Yt});tt({id:dt.id,filename:dt.filename})}}),Oe&&r.jsx(Cc,{mode:"reprint",libraryFileId:Oe.id,archiveName:Oe.filename,initialSelectedPrinterIds:[t.id],onClose:()=>tt(null),onSuccess:()=>tt(null),cleanupLibraryAfterDispatch:!0}),he&&r.jsx(r2e,{printerId:t.id,printerName:t.name,onClose:()=>xe(!1)}),Ue&&r.jsx(QI,{printerId:t.id,printerName:t.name,onClose:()=>ze(!1)}),Ie&&r.jsx(G9e,{printer:t,status:ke,totalPrintHours:a?.total_print_hours,onClose:nt}),We&&r.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",onClick:()=>$l(),children:r.jsxs("div",{className:"bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl max-w-lg w-full",onClick:dt=>dt.stopPropagation(),children:[r.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[We.needs_calibration?r.jsx(fN,{className:"w-5 h-5 text-blue-500"}):We.is_empty?r.jsx(fr,{className:"w-5 h-5 text-green-500"}):r.jsx(Fr,{className:"w-5 h-5 text-yellow-500"}),r.jsx("h2",{className:"text-lg font-semibold text-white",children:"Build Plate Check"}),We.reference_count!==void 0&&We.max_references&&r.jsxs("span",{className:"text-xs text-bambu-gray bg-bambu-dark-tertiary px-2 py-1 rounded",children:[We.reference_count,"/",We.max_references," refs"]})]}),r.jsx("button",{onClick:()=>$l(),className:"p-1 text-bambu-gray hover:text-white rounded transition-colors",children:r.jsx(Ht,{className:"w-5 h-5"})})]}),r.jsxs("div",{className:"p-4 space-y-4",children:[We.needs_calibration?r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"p-3 rounded-lg bg-blue-500/20 border border-blue-500/50",children:[r.jsx("p",{className:"font-medium text-blue-400",children:P("printers.plateDetection.calibrationRequired")}),r.jsx("p",{className:"text-sm text-bambu-gray mt-1",dangerouslySetInnerHTML:{__html:P("printers.plateDetection.calibrationInstructions")}})]}),r.jsxs("div",{className:"text-sm text-bambu-gray space-y-2",children:[r.jsx("p",{children:P("printers.plateDetection.calibrationDescription")}),r.jsx("p",{dangerouslySetInnerHTML:{__html:P("printers.plateDetection.calibrationTip")}})]})]}):r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:`p-3 rounded-lg ${We.is_empty?"bg-green-500/20 border border-green-500/50":"bg-yellow-500/20 border border-yellow-500/50"}`,children:[r.jsx("p",{className:`font-medium ${We.is_empty?"text-green-400":"text-yellow-400"}`,children:We.is_empty?P("printers.plateDetection.plateEmpty"):P("printers.plateDetection.objectsDetected")}),r.jsxs("p",{className:"text-sm text-bambu-gray mt-1",children:[P("printers.plateDetection.confidence"),": ",Math.round(We.confidence*100),"% | ",P("printers.plateDetection.difference"),": ",We.difference_percent.toFixed(1),"%"]})]}),We.debug_image_url&&r.jsxs("div",{children:[r.jsx("p",{className:"text-sm text-bambu-gray mb-2",children:P("printers.plateDetection.analysisPreview")}),r.jsx("img",{src:We.debug_image_url,alt:P("printers.plateDetection.analysisPreview"),className:"w-full rounded-lg border border-bambu-dark-tertiary"}),r.jsx("p",{className:"text-xs text-bambu-gray mt-2",children:P("printers.plateDetection.analysisLegend")})]}),r.jsx("p",{className:"text-xs text-bambu-gray",children:We.message})]}),dl&&dl.references.length>0&&r.jsxs("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary",children:[r.jsx("p",{className:"text-sm font-medium text-white mb-2",children:P("printers.plateDetection.savedReferences",{count:dl.references.length,max:dl.max_references})}),r.jsx("div",{className:"grid grid-cols-5 gap-2",children:dl.references.map(dt=>r.jsxs("div",{className:"relative group",children:[r.jsx("img",{src:ne.getPlateReferenceThumbnailUrl(t.id,dt.index),alt:dt.label||`Reference ${dt.index+1}`,className:"w-full aspect-video object-cover rounded border border-bambu-dark-tertiary"}),r.jsx("button",{onClick:()=>Cb(dt.index),className:"absolute top-1 right-1 p-0.5 bg-red-500/80 rounded opacity-0 group-hover:opacity-100 transition-opacity",title:P("printers.plateDetection.deleteReference"),children:r.jsx(Ht,{className:"w-3 h-3 text-white"})}),Vc?.index===dt.index?r.jsx("input",{type:"text",value:Vc.label,onChange:Bt=>jd({...Vc,label:Bt.target.value}),onBlur:()=>wp(dt.index,Vc.label),onKeyDown:Bt=>{Bt.key==="Enter"&&wp(dt.index,Vc.label),Bt.key==="Escape"&&jd(null)},className:"w-full mt-1 px-1 py-0.5 text-xs bg-bambu-dark-tertiary border border-bambu-green rounded text-white",autoFocus:!0,placeholder:P("printers.plateDetection.labelPlaceholder")}):r.jsx("p",{className:"text-xs text-bambu-gray mt-1 truncate cursor-pointer hover:text-white",onClick:()=>jd({index:dt.index,label:dt.label}),title:dt.label?P("printers.plateDetection.clickToEdit",{label:dt.label}):P("printers.plateDetection.clickToAddLabel"),children:dt.label||r.jsx("span",{className:"italic opacity-50",children:P("printers.noLabel")})}),r.jsx("p",{className:"text-[10px] text-bambu-gray/60",children:dt.timestamp?Ga(dt.timestamp)?.toLocaleDateString()??"":""})]},dt.index))})]}),!We.needs_calibration&&r.jsxs("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"flex items-center justify-between mb-2",children:[r.jsx("p",{className:"text-sm font-medium text-white",children:P("printers.roi.title")}),_t?r.jsxs("div",{className:"flex gap-1",children:[r.jsx(Le,{variant:"ghost",size:"sm",onClick:()=>St(null),disabled:qt,children:P("common.cancel")}),r.jsx(Le,{size:"sm",onClick:Cv,disabled:qt,children:qt?r.jsx(lt,{className:"w-3 h-3 animate-spin"}):P("common.save")})]}):r.jsxs(Le,{variant:"ghost",size:"sm",onClick:()=>St(We.roi||{x:.15,y:.35,w:.7,h:.55}),children:[r.jsx(ci,{className:"w-3 h-3 mr-1"}),P("common.edit")]})]}),_t?r.jsxs("div",{className:"space-y-3 bg-bambu-dark-tertiary/50 p-3 rounded-lg",children:[r.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[r.jsxs("div",{children:[r.jsx("label",{className:"text-xs text-bambu-gray",children:P("printers.roi.xStart")}),r.jsx("input",{type:"range",min:"0",max:"0.9",step:"0.01",value:_t.x,onChange:dt=>St({..._t,x:parseFloat(dt.target.value)}),className:"w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"}),r.jsxs("span",{className:"text-xs text-bambu-gray",children:[Math.round(_t.x*100),"%"]})]}),r.jsxs("div",{children:[r.jsx("label",{className:"text-xs text-bambu-gray",children:P("printers.roi.yStart")}),r.jsx("input",{type:"range",min:"0",max:"0.9",step:"0.01",value:_t.y,onChange:dt=>St({..._t,y:parseFloat(dt.target.value)}),className:"w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"}),r.jsxs("span",{className:"text-xs text-bambu-gray",children:[Math.round(_t.y*100),"%"]})]}),r.jsxs("div",{children:[r.jsx("label",{className:"text-xs text-bambu-gray",children:P("printers.width")}),r.jsx("input",{type:"range",min:"0.1",max:"1",step:"0.01",value:_t.w,onChange:dt=>St({..._t,w:parseFloat(dt.target.value)}),className:"w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"}),r.jsxs("span",{className:"text-xs text-bambu-gray",children:[Math.round(_t.w*100),"%"]})]}),r.jsxs("div",{children:[r.jsx("label",{className:"text-xs text-bambu-gray",children:P("printers.height")}),r.jsx("input",{type:"range",min:"0.1",max:"1",step:"0.01",value:_t.h,onChange:dt=>St({..._t,h:parseFloat(dt.target.value)}),className:"w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"}),r.jsxs("span",{className:"text-xs text-bambu-gray",children:[Math.round(_t.h*100),"%"]})]})]}),r.jsx("p",{className:"text-xs text-bambu-gray",children:P("printers.roi.instruction")})]}):r.jsxs("p",{className:"text-xs text-bambu-gray",children:["Current: X=",Math.round((We.roi?.x||.15)*100),"%, Y=",Math.round((We.roi?.y||.35)*100),"%, W=",Math.round((We.roi?.w||.7)*100),"%, H=",Math.round((We.roi?.h||.55)*100),"%"]})]})]}),r.jsx("div",{className:"flex justify-end gap-2 p-4 border-t border-bambu-dark-tertiary",children:We.needs_calibration?r.jsxs(r.Fragment,{children:[r.jsx(Le,{variant:"ghost",onClick:()=>$l(),children:P("common.cancel")}),r.jsx(Le,{onClick:()=>_f(),disabled:kt,children:kt?r.jsxs(r.Fragment,{children:[r.jsx(lt,{className:"w-4 h-4 mr-2 animate-spin"}),"Calibrating..."]}):"Calibrate Empty Plate"})]}):r.jsxs(r.Fragment,{children:[r.jsx(Le,{variant:"ghost",onClick:()=>_f(),disabled:kt,children:kt?"Adding...":`Add Reference (${dl?.references.length||0}/${dl?.max_references||5})`}),r.jsx(Le,{onClick:()=>$l(),children:"Close"})]})})]})}),V&&$t&&r.jsx(ka,{title:P("printers.confirm.powerOnTitle"),message:P("printers.confirm.powerOnMessage",{name:t.name}),confirmText:P("printers.confirm.powerOnButton"),variant:"default",onConfirm:()=>{Bl.mutate("on"),Q(!1)},onCancel:()=>Q(!1)}),A&&$t&&r.jsx(ka,{title:P("printers.confirm.powerOffTitle"),message:ke?.state==="RUNNING"?P("printers.confirm.powerOffWarning",{name:t.name}):P("printers.confirm.powerOffMessage",{name:t.name}),confirmText:P("printers.confirm.powerOffButton"),variant:"danger",onConfirm:()=>{Bl.mutate("off"),F(!1)},onCancel:()=>F(!1)}),U&&r.jsx(ka,{title:P("printers.confirm.haToggleTitle",{name:U.name}),message:ke?.state==="RUNNING"?P("printers.confirm.haToggleWarning",{name:t.name,entity:U.ha_entity_id||U.name}):P("printers.confirm.haToggleMessage",{entity:U.ha_entity_id||U.name}),confirmText:P("printers.confirm.haToggleButton"),variant:ke?.state==="RUNNING"?"danger":"default",onConfirm:()=>{Fu.mutate({id:U.id,action:"toggle"}),$(null)},onCancel:()=>$(null)}),O&&r.jsx(ka,{title:P("printers.confirm.stopTitle"),message:P("printers.confirm.stopMessage",{name:t.name}),confirmText:P("printers.confirm.stopButton"),variant:"danger",onConfirm:()=>{Ul.mutate(),q(!1)},onCancel:()=>q(!1)}),Z&&r.jsx(ka,{title:P("printers.confirm.pauseTitle"),message:P("printers.confirm.pauseMessage",{name:t.name}),confirmText:P("printers.confirm.pauseButton"),variant:"default",onConfirm:()=>{Hl.mutate(),ee(!1)},onCancel:()=>ee(!1)}),ve&&r.jsx(ka,{title:P("printers.confirm.resumeTitle"),message:P("printers.confirm.resumeMessage",{name:t.name}),confirmText:P("printers.confirm.resumeButton"),variant:"default",onConfirm:()=>{Hs.mutate(),De(!1)},onCancel:()=>De(!1)}),ge&&r.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/70 p-4",children:r.jsxs("div",{className:"bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl w-full max-w-sm p-5",children:[r.jsxs("div",{className:"flex items-start gap-3 mb-4",children:[r.jsx(xa,{className:"w-5 h-5 text-yellow-400 flex-shrink-0 mt-0.5"}),r.jsxs("div",{children:[r.jsx("h3",{className:"text-sm font-semibold text-white mb-1",children:P("printers.bedJog.notHomedTitle")}),r.jsx("p",{className:"text-xs text-bambu-gray leading-relaxed",children:P("printers.bedJog.notHomedMessage")})]})]}),r.jsxs("div",{className:"flex flex-col gap-2",children:[r.jsx("button",{onClick:()=>{Pv.mutate("all"),be(null)},className:"w-full px-3 py-2 rounded-lg text-xs font-medium bg-bambu-green/20 text-bambu-green hover:bg-bambu-green/30 transition-colors",children:P("printers.bedJog.homeZ")}),r.jsx("button",{onClick:()=>{const dt=ge.distance;try{sessionStorage.setItem(`bambuddy.bedJog.warned.${t.id}`,"1")}catch{}yp.mutate({distance:dt,force:!0}),be(null)},className:"w-full px-3 py-2 rounded-lg text-xs font-medium bg-yellow-500/20 text-yellow-400 hover:bg-yellow-500/30 transition-colors",children:P("printers.bedJog.moveAnyway")}),r.jsx("button",{onClick:()=>be(null),className:"w-full px-3 py-2 rounded-lg text-xs font-medium bg-bambu-dark text-bambu-gray hover:bg-bambu-dark-tertiary transition-colors",children:P("common.cancel")})]})]})}),r.jsx(CO,{printerId:t.id,isOpen:je,onClose:()=>Te(!1)}),H&&r.jsx(Z0e,{printerName:t.name,errors:ke?.hms_errors||[],onClose:()=>le(!1),printerId:t.id,hasPermission:B}),Ct&&r.jsx(m9e,{isOpen:!!Ct,onClose:()=>ea(null),printerId:t.id,printerName:t.name,amsId:Ct.amsId,amsLabel:Ct.amsLabel,initialMode:Ct.mode,thresholds:s}),aa&&r.jsx(xse,{isOpen:!!aa,onClose:()=>Pe(null),tagUid:aa.tagUid,trayUuid:aa.trayUuid,printerId:aa.printerId,amsId:aa.amsId,trayId:aa.trayId}),Ye&&r.jsx(yse,{isOpen:!!Ye,onClose:()=>it(null),printerId:Ye.printerId,amsId:Ye.amsId,trayId:Ye.trayId,trayInfo:Ye.trayInfo,spoolmanEnabled:!!o}),Ae&&r.jsx(Mse,{isOpen:!!Ae,onClose:()=>Se(null),printerId:t.id,slotInfo:Ae,printerModel:bw(t.model)||void 0,onSuccess:()=>{E.invalidateQueries({queryKey:["slotPresets",t.id]}),E.invalidateQueries({queryKey:["printerStatus",t.id]})}}),oe&&r.jsx(s7e,{printer:t,onClose:()=>Y(!1)}),ct&&xt&&r.jsx(i7e,{printer:t,firmwareInfo:xt,onClose:()=>Ne(!1)}),hi&&r.jsx("div",{className:"fixed inset-0 z-40",onClick:()=>qs(null)}),Fe!==null&&ht&&(()=>{const dt=Ve==="n3s"?85:65,Bt=35,Yt=dt+10;return r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"fixed inset-0 z-[100]",onClick:()=>Ke(null)}),r.jsxs("div",{className:"fixed z-[101] flex flex-col w-[240px] bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl overflow-hidden",style:{top:ht.top,left:ht.left,maxHeight:`calc(100dvh - ${ht.top}px - 8px)`},onClick:ut=>ut.stopPropagation(),children:[r.jsxs("div",{className:"shrink-0 flex items-center gap-2 px-3 py-2.5 border-b border-bambu-dark-tertiary",children:[r.jsx(ym,{className:"w-3.5 h-3.5 text-amber-400"}),r.jsx("span",{className:"text-xs text-white font-medium",children:P("printers.drying.start")})]}),r.jsxs("div",{className:"px-3 py-2.5 space-y-2.5 overflow-y-auto min-h-0",children:[r.jsxs("div",{children:[r.jsx("label",{className:"text-[10px] text-bambu-gray mb-1 block",children:P("printers.filaments")}),r.jsx("select",{value:Be,onChange:ut=>{const Da=ut.target.value;Qe(Da);const qr=C[Da];qr&&(Ee(qr[Ve==="n3s"?"n3s":"n3f"]),Xe(Ve==="n3s"?qr.n3s_hours:qr.n3f_hours))},className:"w-full px-2 py-1.5 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-xs focus:outline-none focus:border-amber-500/50",children:Object.keys(C).map(ut=>r.jsx("option",{value:ut,children:ut},ut))})]}),r.jsxs("div",{children:[r.jsxs("div",{className:"flex items-center justify-between mb-1",children:[r.jsx("label",{className:"text-[10px] text-bambu-gray",children:P("printers.drying.temperature")}),r.jsxs("div",{className:"flex items-center gap-1",children:[r.jsx("input",{type:"number",min:45,max:dt,value:Ge,onChange:ut=>Ee(Math.min(dt,Math.max(45,Number(ut.target.value)||45))),className:"w-12 px-1 py-0.5 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-[11px] text-center focus:outline-none focus:border-amber-500/50 [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"}),r.jsx("span",{className:"text-[10px] text-bambu-gray",children:"°C"})]})]}),r.jsx("input",{type:"range",min:Bt,max:Yt,value:Ge,onChange:ut=>Ee(Math.min(dt,Math.max(45,Number(ut.target.value)))),className:"w-full h-1 accent-amber-500 cursor-pointer"}),r.jsxs("div",{className:"flex justify-between text-[9px] text-bambu-gray/50 mt-0.5",children:[r.jsx("span",{children:"45°C"}),r.jsxs("span",{children:[dt,"°C"]})]})]}),r.jsxs("div",{children:[r.jsxs("div",{className:"flex items-center justify-between mb-1",children:[r.jsx("label",{className:"text-[10px] text-bambu-gray",children:P("printers.drying.duration")}),r.jsxs("div",{className:"flex items-center gap-1",children:[r.jsx("input",{type:"number",min:1,max:24,value:rt,onChange:ut=>Xe(Math.min(24,Math.max(1,Number(ut.target.value)||1))),className:"w-10 px-1 py-0.5 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-[11px] text-center focus:outline-none focus:border-amber-500/50 [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"}),r.jsx("span",{className:"text-[10px] text-bambu-gray",children:P("printers.drying.hours")})]})]}),r.jsx("input",{type:"range",min:1,max:24,value:rt,onChange:ut=>Xe(Number(ut.target.value)),className:"w-full h-1 accent-amber-500 cursor-pointer"}),r.jsxs("div",{className:"flex justify-between text-[9px] text-bambu-gray/50 mt-0.5",children:[r.jsx("span",{children:"1h"}),r.jsx("span",{children:"24h"})]})]}),r.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[r.jsx("input",{type:"checkbox",checked:Nt,onChange:ut=>Vt(ut.target.checked),className:"w-3.5 h-3.5 accent-amber-500 rounded cursor-pointer"}),r.jsx("span",{className:"text-[11px] text-bambu-gray",children:P("printers.drying.rotateTray")})]})]}),r.jsx("div",{className:"shrink-0 px-3 pt-2.5 pb-3",children:r.jsx("button",{onClick:()=>{Fe!==null&&ll.mutate({amsId:Fe,temp:Ge,duration:rt,filament:Be,rotateTray:Nt})},disabled:ll.isPending,className:"w-full py-1.5 bg-amber-500 hover:bg-amber-400 text-white text-xs font-medium rounded-lg transition-colors disabled:opacity-50",children:ll.isPending?P("printers.drying.startingDrying"):P("printers.drying.start")})})]})]})})()]})}function n7e({onClose:t,onAdd:e,existingSerials:a}){const{t:n}=wt(),[i,s]=y.useState({name:"",serial_number:"",ip_address:"",access_code:"",model:"",location:"",auto_archive:!0}),[o,l]=y.useState(!1),[c,d]=y.useState([]),[u,m]=y.useState(""),[p,f]=y.useState(!1),[g,v]=y.useState(!1),[b,x]=y.useState([]),[S,k]=y.useState(""),[C,N]=y.useState(""),[T,j]=y.useState(!1),[D,P]=y.useState({scanned:0,total:0}),[E,z]=y.useState(!1),[I,B]=y.useState(!1),[R,K]=y.useState(null);y.useEffect(()=>{zd.getInfo().then(oe=>{v(oe.is_docker),oe.subnets.length>0&&(x(oe.subnets),k(oe.subnets[0]))}).catch(()=>{});try{const oe=localStorage.getItem("bambuddy.discovery.customSubnet");oe&&N(oe)}catch{}},[]);const J=c.filter(oe=>!a.includes(oe.serial)),X=async oe=>{oe.preventDefault(),B(!0);try{const Y=await ne.diagnoseConnection({ip_address:i.ip_address.trim(),serial_number:i.serial_number.trim()||void 0,access_code:i.access_code||void 0});if(Y.checks.some(ie=>ie.status==="fail")){K(Y);return}}catch{}finally{B(!1)}e(i)},ce=async()=>{m(""),d([]),l(!0),f(!1),P({scanned:0,total:0});const oe=T?C.trim():S,Y=g||T;if(Y&&T)try{localStorage.setItem("bambuddy.discovery.customSubnet",oe)}catch{}try{if(Y){await zd.startSubnetScan(oe);const ie=setInterval(async()=>{try{const me=await zd.getScanStatus();P({scanned:me.scanned,total:me.total});const he=await zd.getDiscoveredPrinters();d(he),me.running||(clearInterval(ie),l(!1),f(!0))}catch(me){console.error("Failed to get scan status:",me)}},500)}else{await zd.startDiscovery(10);const ie=setInterval(async()=>{try{const me=await zd.getDiscoveredPrinters();d(me)}catch(me){console.error("Failed to get discovered printers:",me)}},1e3);setTimeout(async()=>{clearInterval(ie);try{await zd.stopDiscovery()}catch{}l(!1),f(!0);try{const me=await zd.getDiscoveredPrinters();d(me)}catch(me){console.error("Failed to get final discovered printers:",me)}},1e4)}}catch(ie){console.error("Failed to start discovery:",ie),m(ie instanceof Error?ie.message:n("printers.discovery.failedToStart")),l(!1),f(!0)}},de=oe=>{const Y=oe.serial.startsWith("unknown-")?"":oe.serial;s({...i,name:oe.name||"",serial_number:Y,ip_address:oe.ip_address,model:bw(oe.model)}),d([])};return y.useEffect(()=>()=>{zd.stopDiscovery().catch(()=>{}),zd.stopSubnetScan().catch(()=>{})},[]),y.useEffect(()=>{const oe=Y=>{Y.key==="Escape"&&t()};return window.addEventListener("keydown",oe),()=>window.removeEventListener("keydown",oe)},[t]),r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-start sm:items-center justify-center z-50 p-4 overflow-y-auto",onClick:t,children:r.jsx(Tt,{className:"w-full max-w-md my-auto max-h-[calc(100vh-2rem)] overflow-y-auto",onClick:oe=>oe.stopPropagation(),children:r.jsxs(jt,{children:[r.jsx("h2",{className:"text-xl font-semibold mb-4",children:n("printers.addPrinter")}),r.jsxs("div",{className:"mb-4 pb-4 border-b border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"mb-3",children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("printers.discovery.subnetToScan")}),b.length>0?r.jsxs("select",{className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none text-sm",value:T?"__custom__":S,onChange:oe=>{oe.target.value==="__custom__"?j(!0):(j(!1),k(oe.target.value))},disabled:o,children:[b.map(oe=>r.jsx("option",{value:oe,children:oe},oe)),r.jsx("option",{value:"__custom__",children:n("printers.discovery.customSubnetOption")})]}):r.jsx("input",{type:"text",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none text-sm",value:S,onChange:oe=>k(oe.target.value),placeholder:"192.168.1.0/24",disabled:o}),T&&r.jsx("input",{type:"text","aria-label":n("printers.discovery.customSubnetLabel"),className:"mt-2 w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none text-sm",value:C,onChange:oe=>N(oe.target.value),placeholder:"10.1.1.0/24",disabled:o}),r.jsx("p",{className:"mt-1 text-xs text-bambu-gray",children:n(g?"printers.discovery.dockerNote":"printers.discovery.customSubnetNote")})]}),r.jsx(Le,{type:"button",variant:"secondary",onClick:ce,disabled:o,className:"w-full",children:o?r.jsxs(r.Fragment,{children:[r.jsx(lt,{className:"w-4 h-4 animate-spin"}),(g||T)&&D.total>0?n("printers.discovery.scanProgress",{scanned:D.scanned,total:D.total}):n("printers.discovery.scanning")]}):r.jsxs(r.Fragment,{children:[r.jsx(br,{className:"w-4 h-4"}),n(g||T?"printers.discovery.scanSubnet":"printers.discovery.discoverNetwork")]})}),u&&r.jsx("div",{className:"mt-2 text-sm text-red-400",children:u}),J.length>0&&r.jsx("div",{className:"mt-3 space-y-2 max-h-40 overflow-y-auto",children:J.map(oe=>r.jsxs("div",{className:"flex items-center justify-between p-2 bg-bambu-dark rounded-lg hover:bg-bambu-dark-secondary cursor-pointer transition-colors",onClick:()=>de(oe),children:[r.jsxs("div",{className:"min-w-0 flex-1",children:[r.jsx("p",{className:"font-medium text-white text-sm truncate",children:oe.name||oe.serial}),r.jsxs("p",{className:"text-xs text-bambu-gray truncate",children:[bw(oe.model)||n("printers.discovery.unknown")," • ",oe.ip_address,oe.serial.startsWith("unknown-")&&r.jsxs("span",{className:"text-yellow-500",children:[" • ",n("printers.discovery.serialRequired")]})]})]}),r.jsx(za,{className:"w-4 h-4 text-bambu-gray -rotate-90 flex-shrink-0 ml-2"})]},oe.serial))}),o&&r.jsx("p",{className:"mt-2 text-sm text-bambu-gray text-center",children:n(g||T?"printers.discovery.scanningSubnet":"printers.discovery.scanningNetwork")}),p&&!o&&c.length===0&&r.jsx("p",{className:"mt-2 text-sm text-bambu-gray text-center",children:n(g||T?"printers.discovery.noPrintersFoundSubnet":"printers.discovery.noPrintersFoundNetwork")}),p&&!o&&c.length>0&&J.length===0&&r.jsx("p",{className:"mt-2 text-sm text-bambu-gray text-center",children:n("printers.discovery.allConfigured")})]}),r.jsxs("form",{onSubmit:X,className:"space-y-4",children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("printers.name")}),r.jsx("input",{type:"text",required:!0,className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:i.name,onChange:oe=>s({...i,name:oe.target.value}),placeholder:n("printers.modal.myPrinter")})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("printers.ipAddress")}),r.jsx("input",{type:"text",required:!0,pattern:"(\\d{1,3}(\\.\\d{1,3}){3}|[a-zA-Z0-9]([a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])?(\\.[a-zA-Z0-9]([a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])?)*)",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:i.ip_address,onChange:oe=>s({...i,ip_address:oe.target.value}),placeholder:"192.168.1.100 or printer.local"})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("printers.serialNumber")}),r.jsx("input",{type:"text",required:!0,className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:i.serial_number,onChange:oe=>s({...i,serial_number:oe.target.value}),placeholder:"01P00A000000000"})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("printers.accessCode")}),r.jsx("input",{type:"password",required:!0,className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:i.access_code,onChange:oe=>s({...i,access_code:oe.target.value}),placeholder:n("printers.modal.fromPrinterSettings")})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("printers.modal.modelOptional")}),r.jsxs("select",{className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:i.model||"",onChange:oe=>s({...i,model:oe.target.value}),children:[r.jsx("option",{value:"",children:n("printers.modal.selectModel")}),r.jsxs("optgroup",{label:"A1 Series",children:[r.jsx("option",{value:"A1",children:"A1"}),r.jsx("option",{value:"A1 Mini",children:"A1 Mini"})]}),r.jsx("optgroup",{label:"A2 Series",children:r.jsx("option",{value:"A2L",children:"A2L"})}),r.jsxs("optgroup",{label:"H2 Series",children:[r.jsx("option",{value:"H2C",children:"H2C"}),r.jsx("option",{value:"H2D",children:"H2D"}),r.jsx("option",{value:"H2D Pro",children:"H2D Pro"}),r.jsx("option",{value:"H2S",children:"H2S"})]}),r.jsxs("optgroup",{label:"P Series",children:[r.jsx("option",{value:"P1P",children:"P1P"}),r.jsx("option",{value:"P1S",children:"P1S"}),r.jsx("option",{value:"P2S",children:"P2S"})]}),r.jsxs("optgroup",{label:"X1 Series",children:[r.jsx("option",{value:"X1",children:"X1"}),r.jsx("option",{value:"X1C",children:"X1 Carbon"}),r.jsx("option",{value:"X1E",children:"X1E"})]}),r.jsx("optgroup",{label:"X2 Series",children:r.jsx("option",{value:"X2D",children:"X2D"})})]})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("printers.modal.locationGroup")}),r.jsx("input",{type:"text",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:i.location||"",onChange:oe=>s({...i,location:oe.target.value}),placeholder:n("printers.modal.locationPlaceholder")}),r.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:n("printers.locationHelp")})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("input",{type:"checkbox",id:"auto_archive",checked:i.auto_archive,onChange:oe=>s({...i,auto_archive:oe.target.checked}),className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),r.jsx("label",{htmlFor:"auto_archive",className:"text-sm text-bambu-gray",children:n("printers.modal.autoArchiveLabel")})]}),r.jsxs("button",{type:"button",onClick:()=>z(!0),disabled:!i.ip_address.trim(),className:"w-full flex items-center justify-center gap-2 px-3 py-2 text-sm text-bambu-gray hover:text-white disabled:opacity-40 disabled:cursor-not-allowed border border-bambu-dark-tertiary rounded-lg transition-colors",children:[r.jsx(Ll,{className:"w-4 h-4"}),n("diagnostic.runButton")]}),R?r.jsxs("div",{className:"rounded-lg bg-amber-500/10 border border-amber-500/30 p-3 space-y-3",children:[r.jsxs("div",{className:"flex items-start gap-2",children:[r.jsx(xa,{className:"w-4 h-4 mt-0.5 flex-shrink-0 text-amber-400"}),r.jsx("p",{className:"text-sm text-amber-300",children:n("printers.addPreflight.warning")})]}),r.jsx(U1,{result:R}),r.jsxs("div",{className:"flex gap-3",children:[r.jsx(Le,{type:"button",variant:"secondary",onClick:()=>K(null),className:"flex-1",children:n("printers.addPreflight.back")}),r.jsx(Le,{type:"button",onClick:()=>e(i),className:"flex-1",children:n("printers.addPreflight.saveAnyway")})]})]}):r.jsxs("div",{className:"flex gap-3 pt-2",children:[r.jsx(Le,{type:"button",variant:"secondary",onClick:t,className:"flex-1",children:n("common.cancel")}),r.jsx(Le,{type:"submit",disabled:I,className:"flex-1",children:n(I?"printers.addPreflight.checking":"printers.addPrinter")})]})]})]})})}),E&&r.jsx(QI,{connection:{ip_address:i.ip_address.trim(),serial_number:i.serial_number.trim()||void 0,access_code:i.access_code||void 0},printerName:i.name||null,onClose:()=>z(!1)})]})}function i7e({printer:t,firmwareInfo:e,onClose:a}){const{t:n}=wt(),i=na(),{showToast:s}=oa(),{hasPermission:o}=lr(),l=o("firmware:update"),[c,d]=y.useState(null),[u,m]=y.useState(!1),[p,f]=y.useState(null),[g,v]=y.useState(e.update_available?e.latest_version:null),{data:b,isLoading:x}=$e({queryKey:["firmwarePrepare",t.id,g],queryFn:()=>AC.prepareUpload(t.id,g??void 0),staleTime:3e4,enabled:!!g&&l&&!u}),S=at({mutationFn:()=>AC.startUpload(t.id,g??void 0),onSuccess:()=>{m(!0);const C=setInterval(async()=>{try{const N=await AC.getUploadStatus(t.id);d(N),(N.status==="complete"||N.status==="error")&&(clearInterval(C),f(null),m(!1),N.status==="complete"&&(s(n("printers.firmwareModal.uploadedToast"),"success"),i.invalidateQueries({queryKey:["firmwareUpdate",t.id]})))}catch{}},2e3);f(C)},onError:C=>{s(n("printers.firmwareModal.uploadFailed",{error:C.message}),"error"),m(!1)}});y.useEffect(()=>()=>{p&&clearInterval(p)},[p]);const k=()=>{d(null),S.mutate()};return r.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",children:r.jsx(Tt,{className:"w-full max-w-md mx-4",children:r.jsxs(jt,{children:[r.jsxs("div",{className:"flex items-start gap-3 mb-4",children:[r.jsx("div",{className:`p-2 rounded-full ${e.update_available?"bg-orange-500/20":"bg-status-ok/20"}`,children:e.update_available?r.jsx(Ur,{className:"w-5 h-5 text-orange-400"}):r.jsx(fr,{className:"w-5 h-5 text-status-ok"})}),r.jsxs("div",{className:"flex-1",children:[r.jsx("h3",{className:"text-lg font-semibold text-white",children:e.update_available?n("printers.firmwareModal.title"):n("printers.firmwareModal.titleUpToDate")}),r.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:t.name})]})]}),(()=>{const C=g?e.available_versions?.find(D=>D.version===g):null,N=g??e.latest_version,T=C?.release_notes??e.release_notes,j=!!N&&N!==e.current_version;return r.jsxs("div",{className:"bg-bambu-dark rounded-lg p-3 mb-4",children:[r.jsxs("div",{className:"flex justify-between items-center text-sm",children:[r.jsx("span",{className:"text-bambu-gray",children:n("printers.firmwareModal.currentVersion")}),r.jsx("span",{className:`font-mono ${j?"text-white":"text-status-ok"}`,children:e.current_version||n("common.unknown")})]}),j&&r.jsxs("div",{className:"flex justify-between items-center text-sm mt-1",children:[r.jsx("span",{className:"text-bambu-gray",children:n("printers.firmwareModal.latestVersion")}),r.jsx("span",{className:"text-orange-400 font-mono",children:N})]}),T&&r.jsxs("details",{className:"mt-3 text-sm",open:!j,children:[r.jsx("summary",{className:`cursor-pointer hover:underline ${j?"text-orange-400":"text-status-ok"}`,children:n("printers.firmwareModal.releaseNotes")}),r.jsx("div",{className:"mt-2 text-bambu-gray text-xs max-h-40 overflow-y-auto whitespace-pre-wrap",children:T})]},N??"none")]})})(),e.available_versions&&e.available_versions.length>0&&!u&&c?.status!=="complete"&&r.jsxs("div",{className:"mb-4",children:[r.jsx("div",{className:"text-xs text-bambu-gray mb-2",children:n("printers.firmwareModal.availableVersions")}),r.jsx("div",{className:"max-h-56 overflow-y-auto border border-bambu-dark-tertiary rounded-lg divide-y divide-bambu-dark-tertiary",children:e.available_versions.map(C=>{const N=e.current_version===C.version,T=g===C.version,j=e.current_version?Y0e(C.version,e.current_version):0,D=N?n("printers.firmwareModal.currentBadge"):j>0?n("printers.firmwareModal.newerBadge"):n("printers.firmwareModal.olderBadge"),P=N?"text-bambu-gray":j>0?"text-orange-400":"text-blue-400";return r.jsxs("button",{type:"button",disabled:!C.file_available||!l||N,onClick:()=>v(C.version),className:`w-full text-left px-3 py-2 text-sm flex items-center justify-between gap-2 transition-colors ${T?"bg-orange-500/10":"hover:bg-bambu-dark"} ${!C.file_available||!l||N?"opacity-60 cursor-not-allowed":"cursor-pointer"}`,children:[r.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[r.jsx("span",{className:"font-mono text-white",children:C.version}),r.jsx("span",{className:`text-xs ${P}`,children:D})]}),r.jsx("span",{className:`text-xs px-2 py-0.5 rounded-full ${N?"bg-blue-500/15 text-blue-400 border border-blue-500/30":C.file_available?"bg-bambu-green/15 text-bambu-green border border-bambu-green/30":"bg-bambu-gray/10 text-bambu-gray border border-bambu-gray/30"}`,children:N?n("printers.firmwareModal.installed"):C.file_available?n("printers.firmwareModal.usable"):n("printers.firmwareModal.unavailable")})]},C.version)})})]}),g?x?r.jsxs("div",{className:"flex items-center gap-2 text-bambu-gray text-sm mb-4",children:[r.jsx(lt,{className:"w-4 h-4 animate-spin"}),n("printers.firmwareModal.checkingPrereqs")]}):b&&!u&&!c?r.jsx("div",{className:"mb-4",children:b.can_proceed?r.jsxs("div",{className:"flex items-center gap-2 text-bambu-green text-sm",children:[r.jsx(Ei,{className:"w-4 h-4"}),n("printers.firmwareModal.sdCardReady")]}):r.jsx("div",{className:"space-y-1",children:b.errors.map((C,N)=>r.jsxs("div",{className:"flex items-center gap-2 text-red-400 text-sm",children:[r.jsx(Sn,{className:"w-4 h-4 flex-shrink-0"}),C]},N))})}):null:null,(u||c)&&c&&r.jsxs("div",{className:"mb-4",children:[r.jsxs("div",{className:"flex items-center justify-between text-sm mb-1",children:[r.jsx("span",{className:"text-bambu-gray capitalize",children:c.status}),r.jsxs("span",{className:"text-white",children:[c.progress,"%"]})]}),r.jsx("div",{className:"w-full bg-bambu-dark-tertiary rounded-full h-2",children:r.jsx("div",{className:`h-2 rounded-full transition-all ${c.status==="error"?"bg-status-error":c.status==="complete"?"bg-status-ok":"bg-orange-500"} ${c.status==="uploading"?"animate-pulse":""}`,style:{width:`${c.progress}%`}})}),r.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:c.message}),c.error&&r.jsx("p",{className:"text-xs text-red-400 mt-1",children:c.error})]}),c?.status==="complete"&&r.jsxs("div",{className:"bg-bambu-green/10 border border-bambu-green/30 rounded-lg p-3 mb-4",children:[r.jsx("p",{className:"text-sm text-bambu-green font-medium mb-2",children:n("printers.firmwareModal.uploadedSuccess")}),r.jsx("p",{className:"text-xs text-bambu-gray",children:n("printers.firmwareModal.applyInstructions")}),r.jsxs("ol",{className:"text-xs text-bambu-gray mt-1 list-decimal list-inside space-y-1",children:[r.jsx("li",{dangerouslySetInnerHTML:{__html:n("printers.firmwareModal.step1")}}),r.jsx("li",{dangerouslySetInnerHTML:{__html:n("printers.firmwareModal.step2")}}),r.jsx("li",{dangerouslySetInnerHTML:{__html:n("printers.firmwareModal.step3")}}),r.jsx("li",{children:n("printers.firmwareModal.step4")})]})]}),r.jsxs("div",{className:"flex gap-2 justify-end",children:[r.jsx(Le,{variant:"secondary",onClick:a,children:c?.status==="complete"?n("printers.firmwareModal.done"):n("common.cancel")}),b?.can_proceed&&!u&&c?.status!=="complete"&&l&&r.jsx(Le,{onClick:k,disabled:S.isPending,children:S.isPending?r.jsxs(r.Fragment,{children:[r.jsx(lt,{className:"w-4 h-4 animate-spin mr-2"}),n("printers.firmwareModal.starting")]}):r.jsxs(r.Fragment,{children:[r.jsx(Ur,{className:"w-4 h-4 mr-2"}),n("printers.firmwareModal.uploadFirmware")]})})]})]})})})}function s7e({printer:t,onClose:e}){const{t:a}=wt(),n=na(),{showToast:i}=oa(),[s,o]=y.useState({name:t.name,ip_address:t.ip_address,access_code:"",model:t.model||"",location:t.location||"",auto_archive:t.auto_archive}),[l,c]=y.useState(!1),[d,u]=y.useState(null),m=at({mutationFn:g=>ne.updatePrinter(t.id,g),onSuccess:()=>{n.invalidateQueries({queryKey:["printers"]}),n.invalidateQueries({queryKey:["printerStatus",t.id]}),e()},onError:g=>i(g.message||a("printers.toast.failedToUpdate"),"error")});y.useEffect(()=>{const g=v=>{v.key==="Escape"&&e()};return window.addEventListener("keydown",g),()=>window.removeEventListener("keydown",g)},[e]);const p=()=>{const g={name:s.name,ip_address:s.ip_address,model:s.model||void 0,location:s.location||void 0,auto_archive:s.auto_archive};s.access_code&&(g.access_code=s.access_code),m.mutate(g)},f=async g=>{g.preventDefault(),c(!0);try{const v=await ne.diagnoseConnection({ip_address:s.ip_address.trim(),serial_number:t.serial_number,access_code:s.access_code||void 0});if(v.checks.some(b=>b.status==="fail")){u(v);return}}catch{}finally{c(!1)}p()};return r.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-start sm:items-center justify-center z-50 p-4 overflow-y-auto",onClick:e,children:r.jsx(Tt,{className:"w-full max-w-md my-auto max-h-[calc(100vh-2rem)] overflow-y-auto",onClick:g=>g.stopPropagation(),children:r.jsxs(jt,{children:[r.jsx("h2",{className:"text-xl font-semibold mb-4",children:a("printers.editPrinter")}),r.jsxs("form",{onSubmit:f,className:"space-y-4",children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("printers.name")}),r.jsx("input",{type:"text",required:!0,className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:s.name,onChange:g=>o({...s,name:g.target.value}),placeholder:a("printers.modal.myPrinter")})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("printers.ipAddress")}),r.jsx("input",{type:"text",required:!0,pattern:"(\\d{1,3}(\\.\\d{1,3}){3}|[a-zA-Z0-9]([a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])?(\\.[a-zA-Z0-9]([a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])?)*)",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:s.ip_address,onChange:g=>o({...s,ip_address:g.target.value}),placeholder:"192.168.1.100 or printer.local"})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("printers.serialNumber")}),r.jsx("input",{type:"text",disabled:!0,className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-bambu-gray cursor-not-allowed",value:t.serial_number}),r.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:a("printers.serialCannotBeChanged")})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("printers.accessCode")}),r.jsx("input",{type:"password",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:s.access_code,onChange:g=>o({...s,access_code:g.target.value}),placeholder:a("printers.accessCodePlaceholder")})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("printers.model")}),r.jsxs("select",{className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:s.model,onChange:g=>o({...s,model:g.target.value}),children:[r.jsx("option",{value:"",children:a("printers.modal.selectModel")}),r.jsxs("optgroup",{label:"A1 Series",children:[r.jsx("option",{value:"A1",children:"A1"}),r.jsx("option",{value:"A1 Mini",children:"A1 Mini"})]}),r.jsx("optgroup",{label:"A2 Series",children:r.jsx("option",{value:"A2L",children:"A2L"})}),r.jsxs("optgroup",{label:"H2 Series",children:[r.jsx("option",{value:"H2C",children:"H2C"}),r.jsx("option",{value:"H2D",children:"H2D"}),r.jsx("option",{value:"H2D Pro",children:"H2D Pro"}),r.jsx("option",{value:"H2S",children:"H2S"})]}),r.jsxs("optgroup",{label:"P Series",children:[r.jsx("option",{value:"P1P",children:"P1P"}),r.jsx("option",{value:"P1S",children:"P1S"}),r.jsx("option",{value:"P2S",children:"P2S"})]}),r.jsxs("optgroup",{label:"X1 Series",children:[r.jsx("option",{value:"X1",children:"X1"}),r.jsx("option",{value:"X1C",children:"X1 Carbon"}),r.jsx("option",{value:"X1E",children:"X1E"})]}),r.jsx("optgroup",{label:"X2 Series",children:r.jsx("option",{value:"X2D",children:"X2D"})})]})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Location / Group"}),r.jsx("input",{type:"text",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:s.location,onChange:g=>o({...s,location:g.target.value}),placeholder:a("printers.modal.locationPlaceholder")}),r.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:a("printers.locationHelp")})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("input",{type:"checkbox",id:"edit_auto_archive",checked:s.auto_archive,onChange:g=>o({...s,auto_archive:g.target.checked}),className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),r.jsx("label",{htmlFor:"edit_auto_archive",className:"text-sm text-bambu-gray",children:a("printers.modal.autoArchiveLabel")})]}),d?r.jsxs("div",{className:"rounded-lg bg-amber-500/10 border border-amber-500/30 p-3 space-y-3",children:[r.jsxs("div",{className:"flex items-start gap-2",children:[r.jsx(xa,{className:"w-4 h-4 mt-0.5 flex-shrink-0 text-amber-400"}),r.jsx("p",{className:"text-sm text-amber-300",children:a("printers.addPreflight.warning")})]}),r.jsx(U1,{result:d}),r.jsxs("div",{className:"flex gap-3",children:[r.jsx(Le,{type:"button",variant:"secondary",onClick:()=>u(null),className:"flex-1",children:a("printers.addPreflight.back")}),r.jsx(Le,{type:"button",onClick:p,className:"flex-1",disabled:m.isPending,children:a("printers.addPreflight.saveAnyway")})]})]}):r.jsxs("div",{className:"flex gap-3 pt-4",children:[r.jsx(Le,{type:"button",variant:"secondary",onClick:e,className:"flex-1",children:a("common.cancel")}),r.jsx(Le,{type:"submit",className:"flex-1",disabled:m.isPending||l,children:l?a("printers.addPreflight.checking"):m.isPending?a("common.saving"):a("printers.modal.saveChanges")})]})]})]})})})}function o7e(t){const{data:e}=$e({queryKey:["printerStatus",t],queryFn:()=>ne.getPrinterStatus(t),refetchInterval:3e4});return!e?.connected}function l7e({printer:t,plug:e,onPowerOn:a,isPowering:n}){const i=o7e(t.id),{data:s}=$e({queryKey:["smartPlugStatus",e.id],queryFn:()=>ne.getSmartPlugStatus(e.id),refetchInterval:1e4});return i?r.jsxs("div",{className:"flex items-center justify-between px-3 py-2 hover:bg-gray-100 dark:hover:bg-bambu-dark-tertiary",children:[r.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[r.jsx("span",{className:"text-sm text-gray-900 dark:text-white truncate",children:t.name}),s&&r.jsx("span",{className:`text-xs px-1.5 py-0.5 rounded ${s.state==="ON"?"bg-bambu-green/20 text-bambu-green":"bg-red-500/20 text-red-400"}`,children:s.state||"?"})]}),r.jsxs("button",{onClick:()=>a(e.id),disabled:n||s?.state==="ON",className:`px-2 py-1 text-xs rounded transition-colors flex items-center gap-1 ${s?.state==="ON"?"bg-bambu-green/20 text-bambu-green cursor-default":"bg-bambu-green/20 text-bambu-green hover:bg-bambu-green hover:text-white"}`,children:[r.jsx(Tu,{className:"w-3 h-3"}),n?"...":"On"]})]}):null}function c7e(){const{t}=wt(),[e,a]=y.useState(!1),[n,i]=y.useState(()=>localStorage.getItem("hideDisconnectedPrinters")==="true"),[s,o]=y.useState(!1),[l,c]=y.useState(null),[d,u]=y.useState(()=>localStorage.getItem("printerSortBy")||"name"),[m,p]=y.useState(()=>localStorage.getItem("printerSortAsc")!=="false"),[f,g]=y.useState(()=>{const ot=localStorage.getItem("printerCardSize");return ot?parseInt(ot,10):2}),v=f===1?"compact":"expanded",[b,x]=y.useState(""),[S,k]=y.useState("all"),[C,N]=y.useState("all"),[T,j]=y.useState(0),[D,P]=y.useState(()=>{try{const ot=localStorage.getItem("printerCollapsedSections");return ot?JSON.parse(ot):{}}catch{return{}}}),E=na(),{showToast:z}=oa(),{hasPermission:I}=lr(),[B,R]=y.useState(()=>{const ot=localStorage.getItem("openEmbeddedCameras");if(ot)try{const vt=JSON.parse(ot);return new Map(vt.map(Ct=>[Ct.id,Ct]))}catch{return new Map}return new Map});y.useEffect(()=>{const ot=Array.from(B.values());ot.length>0?localStorage.setItem("openEmbeddedCameras",JSON.stringify(ot)):localStorage.removeItem("openEmbeddedCameras")},[B]);const{data:K,isLoading:J}=$e({queryKey:["printers"],queryFn:ne.getPrinters}),{data:X}=$e({queryKey:["ui-preferences"],queryFn:ne.getUiPreferences}),ce=y.useMemo(()=>{if(X?.drying_presets)try{const ot=JSON.parse(X.drying_presets);if(typeof ot=="object"&&ot!==null&&Object.keys(ot).length>0)return{...Nz,...ot}}catch{}return Nz},[X?.drying_presets]);y.useEffect(()=>{X?.camera_view_mode==="window"&&B.size>0&&R(new Map)},[X?.camera_view_mode,B.size]);const{data:de}=$e({queryKey:["smart-plugs"],queryFn:ne.getSmartPlugs}),{data:oe}=$e({queryKey:["maintenanceOverview"],queryFn:ne.getMaintenanceOverview,staleTime:60*1e3}),{data:Y}=$e({queryKey:["spoolman-status"],queryFn:ne.getSpoolmanStatus,staleTime:60*1e3}),ie=Y?.enabled&&Y?.connected,{data:me}=$e({queryKey:["spoolman-settings"],queryFn:ne.getSpoolmanSettings,enabled:!!ie,staleTime:60*1e3}),he=me?.spoolman_sync_mode,{data:xe}=$e({queryKey:["unlinked-spools"],queryFn:ne.getUnlinkedSpools,enabled:!!ie,staleTime:30*1e3}),V=xe&&xe.length>0,{data:Q}=$e({queryKey:["linked-spools"],queryFn:ne.getLinkedSpools,enabled:!!ie,staleTime:30*1e3}),A=Q?.linked,{data:F}=$e({queryKey:["spool-assignments"],queryFn:()=>ne.getAssignments(),enabled:I("inventory:view_assignments"),staleTime:30*1e3}),U=at({mutationFn:({printerId:ot,amsId:vt,trayId:Ct})=>ne.unassignSpool(ot,vt,Ct),onSuccess:()=>{E.invalidateQueries({queryKey:["spool-assignments"]})}}),{data:$,isLoading:H}=$e({queryKey:["spoolman-inventory-spools"],queryFn:()=>ne.getSpoolmanInventorySpools(!1),enabled:!!ie,staleTime:30*1e3}),{data:le,isLoading:O}=$e({queryKey:["spoolman-slot-assignments"],queryFn:()=>ne.getSpoolmanSlotAssignments(),enabled:!!ie,staleTime:30*1e3}),q=at({mutationFn:ot=>ne.unassignSpoolmanSlot(ot),onSuccess:()=>{E.invalidateQueries({queryKey:["spoolman-inventory-spools"]}),E.invalidateQueries({queryKey:["spoolman-slot-assignments"]})}}),Z=(ot,vt,Ct)=>F?.find(ea=>ea.printer_id===ot&&ea.ams_id===Number(vt)&&ea.tray_id===Number(Ct)),ee=oe?.reduce((ot,vt)=>(ot[vt.printer_id]={due_count:vt.due_count,warning_count:vt.warning_count,total_print_hours:vt.total_print_hours},ot),{})||{},re=de?.reduce((ot,vt)=>(vt.printer_id&&(ot[vt.printer_id]=vt),ot),{})||{},se=at({mutationFn:ne.createPrinter,onSuccess:()=>{E.invalidateQueries({queryKey:["printers"]}),E.invalidateQueries({queryKey:["maintenanceOverview"]}),a(!1)},onError:ot=>{if(ot instanceof Hi&&ot.code==="printer_connection_failed"){z(t("printers.toast.connectionFailedNotAdded"),"error");return}z(ot.message||t("printers.toast.failedToAdd"),"error")}}),fe=at({mutationFn:ot=>ne.controlSmartPlug(ot,"on"),onSuccess:()=>{E.invalidateQueries({queryKey:["smart-plugs"]}),c(null)},onError:()=>{c(null)}}),[ue,pe]=y.useState(new Set),[G,L]=y.useState(!1),[ae,ge]=y.useState(null),[be,ve]=y.useState(!1),De=G||ue.size>0,je=y.useCallback(ot=>{pe(vt=>{const Ct=new Set(vt);return Ct.has(ot)?Ct.delete(ot):Ct.add(ot),Ct})},[]),Te=y.useCallback(()=>{pe(new Set),L(!1)},[]);y.useEffect(()=>{const ot=vt=>{vt.key==="Escape"&&De&&Te()};return window.addEventListener("keydown",ot),()=>window.removeEventListener("keydown",ot)},[De,Te]);const qe=y.useCallback(async ot=>{ve(!0);const Ct=Array.from(ue).filter(it=>{const Ae=E.getQueryData(["printerStatus",it]);if(!Ae?.connected)return!1;switch(ot){case"stop":return Ae.state==="RUNNING"||Ae.state==="PAUSE";case"pause":return Ae.state==="RUNNING";case"resume":return Ae.state==="PAUSE";case"clearPlate":return!!Ae.awaiting_plate_clear;case"clearHMS":return Ae.hms_errors&&Bm(Ae.hms_errors).length>0;default:return!1}});if(Ct.length===0){z(t("printers.bulk.noneApplicable"),"error"),ve(!1),ge(null);return}const ea={stop:ne.stopPrint,pause:ne.pausePrint,resume:ne.resumePrint,clearPlate:ne.clearPlate,clearHMS:ne.clearHMSErrors}[ot],aa=await Promise.allSettled(Ct.map(it=>ea(it))),Pe=aa.filter(it=>it.status==="fulfilled").length,Ye=aa.filter(it=>it.status==="rejected").length;Ye===0?z(t("printers.bulk.success",{action:t(`printers.bulk.actions.${ot}`),count:Pe})):z(t("printers.bulk.partial",{succeeded:Pe,failed:Ye}),"error"),Ct.forEach(it=>{E.invalidateQueries({queryKey:["printerStatus",it]})}),ve(!1),ge(null)},[ue,E,z,t]),Ce=y.useCallback(ot=>{ot==="stop"||ot==="pause"||ot==="clearPlate"?ge(ot):qe(ot)},[qe]),Ie=()=>{const ot=!n;i(ot),localStorage.setItem("hideDisconnectedPrinters",String(ot))},Re=ot=>{u(ot),localStorage.setItem("printerSortBy",ot)},Ue=()=>{const ot=!m;p(ot),localStorage.setItem("printerSortAsc",String(ot))},ze=()=>{switch(f){case 1:return"grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5";case 2:return"grid-cols-1 md:grid-cols-2 xl:grid-cols-3";case 3:return"grid-cols-1 lg:grid-cols-2";case 4:return"grid-cols-1";default:return"grid-cols-1 md:grid-cols-2 xl:grid-cols-3"}},nt=["S","M","L","XL"];y.useEffect(()=>E.getQueryCache().subscribe(vt=>{vt.type==="updated"&&Array.isArray(vt.query.queryKey)&&vt.query.queryKey[0]==="printerStatus"&&j(Ct=>Ct+1)}),[E]);const Oe=y.useMemo(()=>{if(!K)return[];let ot=K;if(b.trim()){const vt=b.trim().toLowerCase();ot=ot.filter(Ct=>Ct.name.toLowerCase().includes(vt)||(Ct.model||"").toLowerCase().includes(vt)||(Ct.location||"").toLowerCase().includes(vt)||(Ct.serial_number||"").toLowerCase().includes(vt))}return C!=="all"&&(ot=ot.filter(vt=>(vt.location||"")===C)),S!=="all"&&(ot=ot.filter(vt=>{const Ct=E.getQueryData(["printerStatus",vt.id]);if(!Ct?.connected)return S==="offline";const ea=Ct.hms_errors?Bm(Ct.hms_errors):[];switch(S){case"printing":return Ct.state==="RUNNING";case"paused":return Ct.state==="PAUSE";case"finished":return Ct.state==="FINISH";case"error":return Ct.state==="FAILED"||ea.length>0;case"idle":return Ct.state!=="RUNNING"&&Ct.state!=="PAUSE"&&Ct.state!=="FINISH"&&Ct.state!=="FAILED"&&ea.length===0;case"offline":return!1;default:return!0}})),ot},[K,b,S,C,E,T]),tt=y.useMemo(()=>K?[...new Set(K.map(ot=>ot.location||"").filter(Boolean))].sort():[],[K]),Fe=y.useMemo(()=>{const ot=[...Oe];switch(d){case"name":ot.sort((vt,Ct)=>vt.name.localeCompare(Ct.name));break;case"model":ot.sort((vt,Ct)=>(vt.model||"").localeCompare(Ct.model||""));break;case"location":ot.sort((vt,Ct)=>{const ea=vt.location||"",aa=Ct.location||"";return!ea&&aa?1:ea&&!aa?-1:ea.localeCompare(aa)||vt.name.localeCompare(Ct.name)});break;case"status":ot.sort((vt,Ct)=>{const ea=E.getQueryData(["printerStatus",vt.id]),aa=E.getQueryData(["printerStatus",Ct.id]),Pe=Ye=>Ye?.connected?(Ye.hms_errors?Bm(Ye.hms_errors):[]).length>0?0:Ye.state==="RUNNING"?1:2:3;return Pe(ea)-Pe(aa)});break}return m||ot.reverse(),ot},[Oe,d,m,E]),Ke=y.useCallback(()=>{pe(new Set(Fe.map(ot=>ot.id))),L(!0)},[Fe]),Ve=y.useCallback(ot=>{pe(vt=>{const Ct=new Set(vt);return Fe.forEach(ea=>{const aa=E.getQueryData(["printerStatus",ea.id]);_Y(aa)===ot&&Ct.add(ea.id)}),Ct}),L(!0)},[Fe,E]),Me=y.useCallback(ot=>{pe(vt=>{const Ct=new Set(vt);return Fe.filter(ea=>(ea.location||"")===ot).forEach(ea=>Ct.add(ea.id)),Ct}),L(!0)},[Fe]),Be=y.useCallback(ot=>{pe(vt=>{const Ct=new Set(vt);return Fe.filter(ea=>(ea.model||"Unknown")===ot).forEach(ea=>Ct.add(ea.id)),Ct}),L(!0)},[Fe]),Qe=y.useCallback(ot=>{P(vt=>{const Ct={...vt,[ot]:!vt[ot]};try{localStorage.setItem("printerCollapsedSections",JSON.stringify(Ct))}catch{}return Ct})},[]),Ge=y.useMemo(()=>{if(d==="name")return null;const ot={};return d==="location"?Fe.forEach(vt=>{const Ct=vt.location||"Ungrouped";ot[Ct]||(ot[Ct]=[]),ot[Ct].push(vt)}):d==="model"?Fe.forEach(vt=>{const Ct=vt.model||"Unknown";ot[Ct]||(ot[Ct]=[]),ot[Ct].push(vt)}):d==="status"&&Fe.forEach(vt=>{const Ct=E.getQueryData(["printerStatus",vt.id]),ea=_Y(Ct);ot[ea]||(ot[ea]=[]),ot[ea].push(vt)}),ot},[d,Fe,E,T]),Ee=y.useRef(null),rt=y.useRef(null),Xe=y.useRef(0),[Nt,Vt]=y.useState(!1),ht=y.useCallback(()=>{const ot=Ee.current;if(!ot)return;const vt=rt.current?.offsetWidth;vt&&(Xe.current=vt);const aa=Xe.current>0&&ot.clientWidthPe===aa?Pe:aa)},[]),It=Object.keys(re).length;y.useLayoutEffect(()=>{ht();const ot=Ee.current;if(!ot)return;if(typeof ResizeObserver>"u")return window.addEventListener("resize",ht),()=>window.removeEventListener("resize",ht);const vt=new ResizeObserver(()=>ht());return vt.observe(ot),window.addEventListener("resize",ht),()=>{vt.disconnect(),window.removeEventListener("resize",ht)}},[ht,K?.length,tt.length,n,It]);const Xt=(ot=!1)=>r.jsxs(r.Fragment,{children:[K&&K.length>0&&r.jsx(FF,{value:S,onChange:k,fullWidth:ot,options:[{value:"all",label:t("printers.filter.allStatuses")},{value:"printing",label:t("printers.status.printing")},{value:"paused",label:t("printers.status.paused")},{value:"idle",label:t("printers.status.idle")},{value:"finished",label:t("printers.status.finished")},{value:"error",label:t("printers.status.error")},{value:"offline",label:t("printers.status.offline")}]}),K&&K.length>0&&tt.length>0&&r.jsx(FF,{value:C,onChange:N,fullWidth:ot,options:[{value:"all",label:t("printers.filter.allLocations")},...tt.map(vt=>({value:vt,label:vt}))]}),r.jsx("button",{type:"button",onClick:Ie,"aria-pressed":n,className:`h-8 px-2 rounded-lg border text-sm font-medium transition-colors ${ot?"w-full":""} ${n?"bg-bambu-green border-bambu-green text-white":"bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary"}`,children:t("printers.hideOffline")})]}),la=(ot=!1)=>r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:`flex items-center gap-1 ${ot?"w-full":""}`,children:[r.jsx(FF,{value:d,onChange:Re,fullWidth:ot,options:[{value:"name",label:t("printers.sort.name")},{value:"status",label:t("printers.sort.status")},{value:"model",label:t("printers.sort.model")},{value:"location",label:t("printers.sort.location")}]}),r.jsx("button",{onClick:Ue,className:"h-8 shrink-0 px-2 rounded-lg border bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary transition-colors flex items-center justify-center",title:t(m?"printers.sort.descending":"printers.sort.ascending"),children:m?r.jsx(Qm,{className:"w-4 h-4 text-white"}):r.jsx(Qh,{className:"w-4 h-4 text-white"})})]}),r.jsx("div",{className:`flex h-8 items-center bg-bambu-dark rounded-lg border border-bambu-dark-tertiary ${ot?"w-full":""}`,children:nt.map((vt,Ct)=>{const ea=Ct+1,aa=f===ea;return r.jsx("button",{onClick:()=>{g(ea),localStorage.setItem("printerCardSize",String(ea))},className:`h-full px-2 text-xs font-medium transition-colors ${ot?"flex-1":""} ${Ct===0?"rounded-l-lg":""} ${Ct===nt.length-1?"rounded-r-lg":""} ${aa?"bg-bambu-green text-white":"text-white hover:bg-bambu-dark-tertiary"}`,title:t(vt==="S"?"printers.cardSize.small":vt==="M"?"printers.cardSize.medium":vt==="L"?"printers.cardSize.large":"printers.cardSize.extraLarge"),children:vt},vt)})})]}),ca=(ot=!1)=>r.jsxs(r.Fragment,{children:[r.jsxs("button",{onClick:()=>{De?Te():L(!0)},className:`h-8 px-2 rounded-lg border transition-colors ${ot?"w-full justify-center gap-1.5 text-sm font-medium flex items-center":""} ${De?"bg-bambu-green border-bambu-green text-white":"bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary"}`,title:t("printers.bulk.select"),disabled:!I("printers:control"),children:[r.jsx(xs,{className:"w-4 h-4"}),ot&&r.jsx("span",{children:t("printers.bulk.select")})]}),n&&Object.keys(re).length>0&&r.jsxs("div",{className:`relative ${ot?"w-full":""}`,children:[r.jsxs("button",{onClick:()=>o(!s),className:`h-8 flex items-center gap-1.5 px-2 text-sm rounded-lg border transition-colors ${ot?"w-full justify-between bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary hover:text-white":"bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary"}`,children:[r.jsxs("span",{className:"flex items-center gap-1.5",children:[r.jsx(Tu,{className:"w-4 h-4"}),t("printers.powerOn")]}),r.jsx(za,{className:`w-3 h-3 transition-transform ${s?"rotate-180":""}`})]}),s&&r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>o(!1)}),r.jsxs("div",{className:"absolute right-0 mt-2 w-56 bg-white dark:bg-bambu-dark-secondary border border-gray-200 dark:border-bambu-dark-tertiary rounded-lg shadow-lg z-20 py-1",children:[r.jsx("div",{className:"px-3 py-2 text-xs text-gray-500 dark:text-bambu-gray border-b border-gray-200 dark:border-bambu-dark-tertiary",children:t("printers.offlinePrintersWithPlugs")}),K?.filter(vt=>re[vt.id]).map(vt=>r.jsx(l7e,{printer:vt,plug:re[vt.id],onPowerOn:Ct=>{c(Ct),fe.mutate(Ct)},isPowering:l===re[vt.id]?.id},vt.id)),K?.filter(vt=>re[vt.id]).length===0&&r.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:"No printers with smart plugs"})]})]})]}),r.jsxs(Le,{onClick:()=>a(!0),disabled:!I("printers:create"),title:I("printers:create")?void 0:t("printers.permission.noAdd"),className:`!h-8 !min-h-8 px-2 py-0 ${ot?"w-full":""}`,children:[r.jsx(or,{className:"w-4 h-4"}),t("printers.addPrinter")]})]});return r.jsxs("div",{className:"p-4 md:p-8",children:[r.jsxs("div",{className:"space-y-3 mb-6",children:[r.jsxs("div",{children:[r.jsxs("h1",{className:"text-2xl font-bold text-white flex items-center gap-3",children:[r.jsx(xr,{className:"w-7 h-7 text-bambu-green"}),t("printers.title")]}),r.jsx(a7e,{printers:K})]}),r.jsxs("div",{ref:Ee,className:"relative flex items-center gap-2",children:[K&&K.length>0&&r.jsxs("div",{className:"relative min-w-0 flex-1",children:[r.jsx(br,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50"}),r.jsx("input",{type:"search",name:"printer-search",autoComplete:"off","data-1p-ignore":!0,"data-lpignore":"true",value:b,onChange:ot=>x(ot.target.value),placeholder:t("printers.search"),"aria-label":t("printers.search"),className:"w-full h-8 pl-9 pr-8 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green"}),b&&r.jsx("button",{type:"button","aria-label":t("common.clear"),onClick:()=>x(""),className:"absolute right-3 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white",children:r.jsx(Ht,{className:"w-4 h-4"})})]}),r.jsxs("div",{ref:rt,"aria-hidden":Nt,inert:Nt,className:`${Nt?"absolute -left-[9999px] top-0 flex w-max pointer-events-none opacity-0":"flex"} ml-auto items-center justify-end gap-2 flex-nowrap [&>*]:shrink-0`,children:[r.jsx("div",{className:"h-6 w-px bg-bambu-dark-tertiary"}),r.jsx("div",{className:"flex items-center gap-2",children:Xt()}),r.jsx("div",{className:"h-6 w-px bg-bambu-dark-tertiary"}),r.jsx("div",{className:"flex items-center gap-2",children:la()}),r.jsx("div",{className:"h-6 w-px bg-bambu-dark-tertiary"}),r.jsx("div",{className:"flex items-center gap-2",children:ca()})]}),Nt&&r.jsxs("div",{className:"ml-auto flex items-center justify-end gap-1",children:[r.jsx(LF,{label:t("printers.toolbar.filters","Filters"),icon:r.jsx(av,{className:"w-4 h-4"}),children:r.jsx("div",{className:"flex w-48 flex-col gap-2",children:Xt(!0)})}),r.jsx(LF,{label:t("printers.toolbar.view","View"),icon:r.jsx(xve,{className:"w-4 h-4"}),children:r.jsx("div",{className:"flex w-48 flex-col gap-2",children:la(!0)})}),r.jsx(LF,{label:t("printers.toolbar.actions","Actions"),icon:r.jsx(Ibe,{className:"w-4 h-4"}),children:r.jsx("div",{className:"flex w-48 flex-col gap-2",children:ca(!0)})})]})]})]}),J?r.jsx("div",{className:"text-center py-12 text-bambu-gray",children:t("common.loading")}):K?.length===0?r.jsx(Tt,{children:r.jsxs(jt,{className:"text-center py-12",children:[r.jsx("p",{className:"text-bambu-gray mb-4",children:t("printers.noPrintersConfigured")}),r.jsxs(Le,{onClick:()=>a(!0),disabled:!I("printers:create"),title:I("printers:create")?void 0:t("printers.permission.noAdd"),children:[r.jsx(or,{className:"w-4 h-4"}),t("printers.addPrinter")]})]})}):Fe.length===0&&(b.trim()||S!=="all"||C!=="all")?r.jsx(Tt,{children:r.jsx(jt,{className:"text-center py-12",children:r.jsx("p",{className:"text-bambu-gray",children:t("printers.noSearchResults")})})}):Ge?r.jsx("div",{className:"space-y-6",children:(()=>{const ot=d==="status"?r7e.filter(vt=>Ge[vt]?.length>0):Object.keys(Ge);return m?ot:[...ot].reverse()})().map(ot=>{const vt=Ge[ot],Ct=`${d}:${ot}`,ea=!D[Ct],aa=d==="status"&&kY[ot]?.dot||"bg-bambu-green",Pe=d==="status"?t(kY[ot]?.labelKey||ot):ot;return r.jsx(H1,{open:ea,onToggle:()=>Qe(Ct),summaryClassName:"py-1",summary:r.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[r.jsx("span",{className:`w-2 h-2 rounded-full ${aa}`}),Pe,r.jsxs("span",{className:"text-sm font-normal text-bambu-gray",children:["(",vt.length,")"]}),De&&r.jsx("button",{onClick:Ye=>{Ye.stopPropagation(),d==="location"?Me(ot==="Ungrouped"?"":ot):d==="status"?Ve(ot):d==="model"&&Be(ot)},className:"text-xs text-bambu-green hover:text-bambu-green-light transition-colors ml-1",children:t("printers.bulk.selectAll")})]}),children:r.jsx("div",{className:`grid gap-4 ${f>=3?"gap-6":""} ${ze()}`,children:vt.map(Ye=>r.jsx(CY,{printer:Ye,hideIfDisconnected:n,maintenanceInfo:ee[Ye.id],viewMode:v,cardSize:f,amsThresholds: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,spoolmanEnabled:ie,hasUnlinkedSpools:V,linkedSpools:A,spoolmanUrl:Y?.url,spoolmanSyncMode:he,onGetAssignment:Z,onUnassignSpool:(it,Ae,Se)=>U.mutate({printerId:it,amsId:Ae,trayId:Se}),spoolmanSpools:$,spoolmanSlotAssignments:le,spoolmanLoading:H||O,onUnassignSpoolmanSpool:it=>q.mutate(it),timeFormat:X?.time_format||"system",cameraViewMode:X?.camera_view_mode||"window",onOpenEmbeddedCamera:(it,Ae)=>R(Se=>new Map(Se).set(it,{id:it,name:Ae})),checkPrinterFirmware:X?.check_printer_firmware!==!1,dryingPresets:ce,requirePlateClear:X?.require_plate_clear===!0,selectionMode:De,isSelected:ue.has(Ye.id),onToggleSelect:je},Ye.id))})},ot)})}):r.jsx("div",{className:`grid gap-4 ${f>=3?"gap-6":""} ${ze()}`,children:Fe.map(ot=>r.jsx(CY,{printer:ot,hideIfDisconnected:n,maintenanceInfo:ee[ot.id],viewMode:v,cardSize:f,spoolmanEnabled:ie,hasUnlinkedSpools:V,linkedSpools:A,spoolmanUrl:Y?.url,spoolmanSyncMode:he,onGetAssignment:Z,onUnassignSpool:(vt,Ct,ea)=>U.mutate({printerId:vt,amsId:Ct,trayId:ea}),spoolmanSpools:$,spoolmanSlotAssignments:le,spoolmanLoading:H||O,onUnassignSpoolmanSpool:vt=>q.mutate(vt),amsThresholds: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,timeFormat:X?.time_format||"system",cameraViewMode:X?.camera_view_mode||"window",onOpenEmbeddedCamera:(vt,Ct)=>R(ea=>new Map(ea).set(vt,{id:vt,name:Ct})),checkPrinterFirmware:X?.check_printer_firmware!==!1,dryingPresets:ce,requirePlateClear:X?.require_plate_clear===!0,selectionMode:De,isSelected:ue.has(ot.id),onToggleSelect:je},ot.id))}),e&&r.jsx(n7e,{onClose:()=>a(!1),onAdd:ot=>se.mutate(ot),existingSerials:K?.map(ot=>ot.serial_number)||[]}),De&&K&&r.jsx(ewe,{selectedIds:ue,printers:K,onClose:Te,onSelectAll:Ke,onSelectByLocation:Me,onSelectByState:Ve,onAction:Ce,actionPending:be}),ae==="stop"&&r.jsx(ka,{title:t("printers.bulk.confirm.stopTitle",{count:ue.size}),message:t("printers.bulk.confirm.stopMessage",{count:ue.size}),confirmText:t("printers.bulk.confirm.stopButton"),variant:"danger",isLoading:be,onConfirm:()=>qe("stop"),onCancel:()=>ge(null)}),ae==="pause"&&r.jsx(ka,{title:t("printers.bulk.confirm.pauseTitle",{count:ue.size}),message:t("printers.bulk.confirm.pauseMessage",{count:ue.size}),confirmText:t("printers.bulk.confirm.pauseButton"),isLoading:be,onConfirm:()=>qe("pause"),onCancel:()=>ge(null)}),ae==="clearPlate"&&r.jsx(ka,{title:t("printers.bulk.confirm.clearPlateTitle",{count:ue.size}),message:t("printers.bulk.confirm.clearPlateMessage",{count:ue.size}),confirmText:t("printers.bulk.confirm.clearPlateButton"),isLoading:be,onConfirm:()=>qe("clearPlate"),onCancel:()=>ge(null)}),Array.from(B.values()).map((ot,vt)=>r.jsx(a2e,{printerId:ot.id,printerName:ot.name,viewerIndex:vt,onClose:()=>R(Ct=>{const ea=new Map(Ct);return ea.delete(ot.id),ea})},ot.id))]})}function d7e({title:t,message:e,subtitle:a,closeText:n,variant:i="error",onClose:s}){const{t:o}=wt(),l=n??o("common.close");y.useEffect(()=>{const d=u=>{u.key==="Escape"&&s()};return window.addEventListener("keydown",d),()=>window.removeEventListener("keydown",d)},[s]);const c=i==="warning"?"text-yellow-400":"text-red-400";return r.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center p-4 z-[120]",onClick:s,children:r.jsx(Tt,{className:"w-full max-w-md",onClick:d=>d.stopPropagation(),children:r.jsxs(jt,{className:"p-6",children:[r.jsxs("div",{className:"flex items-start gap-4",children:[r.jsx("div",{className:`p-2 rounded-full bg-bambu-dark ${c}`,children:r.jsx(xa,{className:"w-6 h-6"})}),r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsx("h3",{className:"text-lg font-semibold text-white mb-1",children:t}),a&&r.jsx("p",{className:"text-xs text-bambu-gray mb-2 truncate",children:a}),r.jsx("p",{className:"text-bambu-gray text-sm whitespace-pre-line break-words",children:e})]})]}),r.jsx("div",{className:"flex mt-6",children:r.jsx(Le,{onClick:s,className:"flex-1",children:l})})]})})})}const Bse=y.createContext(null),u7e=1500,m7e=1e3,zF=t=>`slice-job-${t}`;function aC(t){try{return decodeURIComponent(t)}catch{return t}}function p7e(t){const e=Math.max(0,Math.floor(t));if(e<60)return`${e}s`;const a=Math.floor(e/60),n=e%60;if(a<60)return`${a}m ${n}s`;const i=Math.floor(a/60),s=a%60;return`${i}h ${s}m`}function h7e({children:t}){const{t:e}=wt(),{showToast:a,showPersistentToast:n,dismissToast:i}=oa(),s=na(),[o,l]=y.useState([]),[c,d]=y.useState(null),u=y.useRef([]);u.current=o;const m=y.useRef(new Map),p=y.useRef(new Map),f=y.useRef(new Map),g=y.useCallback(x=>{const S=m.current.get(x.id);if(S==null)return;const k=(Date.now()-S)/1e3,C=p.current.get(x.id)??"pending",N=p7e(k),T=f.current.get(x.id)??null,j=T&&T.stage&&T.total_percent>0;if(C==="running"&&j){const E=aC(x.sourceName),z=T.stage,I=Math.min(100,Math.max(0,Math.round(T.total_percent))),R=typeof T.multi_plate_index=="number"&&typeof T.multi_plate_count=="number"&&T.multi_plate_count>1?e("slice.runningWithProgressMultiPlate","Plate {{plateIndex}} of {{plateCount}} • {{name}} — {{stage}} ({{percent}}%) — {{elapsed}}",{plateIndex:T.multi_plate_index,plateCount:T.multi_plate_count,name:E,stage:z,percent:I,elapsed:N}):e("slice.runningWithProgress","{{name}} — {{stage}} ({{percent}}%) — {{elapsed}}",{name:E,stage:z,percent:I,elapsed:N});n(zF(x.id),R,"loading");return}const D=C==="pending"?"slice.queuedToast":"slice.runningToast",P=C==="pending"?"Queued: {{name}} — {{elapsed}}":"Slicing {{name}} — {{elapsed}}";n(zF(x.id),e(D,P,{name:aC(x.sourceName),elapsed:N}),"loading")},[n,e]),v=y.useCallback((x,S,k)=>{l(C=>C.some(N=>N.id===x)?C:[...C,{id:x,kind:S,sourceName:k}]),m.current.set(x,Date.now()),p.current.set(x,"pending"),f.current.set(x,null),g({id:x,kind:S,sourceName:k})},[g]),b=y.useCallback((x,S)=>{l(k=>k.filter(C=>C.id!==x.id)),m.current.delete(x.id),p.current.delete(x.id),f.current.delete(x.id),i(zF(x.id)),S.status==="completed"?a(e("slice.completedToast","Sliced {{name}}",{name:aC(x.sourceName)}),"success"):S.status==="failed"&&d({name:aC(x.sourceName),detail:S.error_detail||e("slice.failed")}),s.invalidateQueries({queryKey:["library-files"]}),s.invalidateQueries({queryKey:["archives"]})},[i,s,a,e]);return y.useEffect(()=>{if(o.length===0)return;let x=!1;const S=setInterval(async()=>{if(x)return;const k=[...u.current];for(const C of k)try{const N=await ne.getSliceJob(C.id);p.current.set(C.id,N.status),N.progress&&f.current.set(C.id,N.progress),(N.status==="completed"||N.status==="failed")&&b(C,N)}catch{}},u7e);return()=>{x=!0,clearInterval(S)}},[o.length,b]),y.useEffect(()=>{if(o.length===0)return;const x=setInterval(()=>{for(const S of u.current)g(S)},m7e);return()=>clearInterval(x)},[o.length,g]),r.jsxs(Bse.Provider,{value:{trackJob:v,activeJobs:o},children:[t,c&&r.jsx(d7e,{title:e("slice.failedTitle"),subtitle:c.name,message:c.detail,onClose:()=>d(null)})]})}function f7e(){const t=y.useContext(Bse);if(!t)throw new Error("useSliceJobTracker must be used inside SliceJobTrackerProvider");return t}function MB({plates:t,onSelect:e,onClose:a}){const{t:n}=wt();return r.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4",onClick:a,children:r.jsxs("div",{className:"w-full max-w-3xl max-h-[85vh] flex flex-col rounded-lg bg-bambu-dark-secondary border border-bambu-dark-tertiary/60",onClick:i=>i.stopPropagation(),children:[r.jsxs("div",{className:"flex-shrink-0 flex items-start justify-between gap-3 px-4 pt-4 pb-3 border-b border-bambu-dark-tertiary/40",children:[r.jsxs("div",{className:"min-w-0",children:[r.jsx("h3",{className:"text-white font-medium",children:n("archives.platePicker.title")}),r.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:n("archives.platePicker.hint")})]}),r.jsx("button",{onClick:a,className:"flex-shrink-0 text-bambu-gray hover:text-white transition-colors","aria-label":n("common.close","Close"),children:r.jsx(Ht,{className:"w-5 h-5"})})]}),r.jsx("div",{className:"flex-1 overflow-y-auto p-4",children:r.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2",children:t.map(i=>r.jsxs("button",{type:"button",onClick:()=>e(i.index),className:"flex items-center gap-2 p-2 rounded-lg border border-bambu-dark-tertiary bg-bambu-dark hover:border-bambu-gray transition-colors text-left",children:[i.has_thumbnail&&i.thumbnail_url!=null?r.jsx("img",{src:zn(i.thumbnail_url),alt:`Plate ${i.index}`,className:"w-12 h-12 rounded object-cover bg-bambu-dark-tertiary flex-shrink-0"}):r.jsx("div",{className:"w-12 h-12 rounded bg-bambu-dark-tertiary flex items-center justify-center flex-shrink-0",children:r.jsx(tn,{className:"w-5 h-5 text-bambu-gray"})}),r.jsxs("div",{className:"min-w-0 flex-1",children:[r.jsx("p",{className:"text-sm text-white font-medium truncate",children:i.name?`${n("archives.platePicker.plateLabel",{index:i.index})} — ${i.name}`:n("archives.platePicker.plateLabel",{index:i.index})}),r.jsxs("p",{className:"text-xs text-bambu-gray truncate",children:[i.objects.length>0?i.objects.slice(0,3).join(", ")+(i.objects.length>3?"…":""):i.object_count!=null&&i.object_count>0?n("archives.platePicker.objectCount",{count:i.object_count}):`${i.filaments.length} filament${i.filaments.length!==1?"s":""}`,i.print_time_seconds!=null?` • ${ds(i.print_time_seconds)}`:""]})]})]},i.index))})})]})})}const YA=["orca_cloud","local","cloud","standard"];function EB(t,e){for(const a of YA){const n=t[a][e];if(n.length>0)return{source:n[0].source,id:n[0].id}}return null}function $C(t,e,a){return e?t[e.source][a].find(n=>n.id===e.id)??null:null}function Use(t,e,a){if(!a)return null;for(const n of YA){const i=t[n][e].find(s=>s.name===a);if(i)return{source:i.source,id:i.id}}return null}function g7e(t,e,a,n){const i=Use(t,"process",n);if(i){const s=$C(t,i,"process");if(s&&Uy(s,"process",e,a)!=="mismatch")return i}for(const s of["match","unknown"])for(const o of YA)for(const l of t[o].process)if(Uy(l,"process",e,a)===s)return{source:l.source,id:l.id};return EB(t,"process")}const b7e={orca_cloud:1.75,local:1.5,cloud:1,standard:.5};function x7e(t,e,a,n){const i=e.type.trim().toUpperCase(),s=On(e.color);let o=null;for(const l of YA)for(const c of t[l].filament){let d=0;const u=(c.filament_type??"").trim().toUpperCase(),m=On(c.filament_colour??"");i&&u&&i===u&&(d+=10),s&&m&&(m===s?d+=5:fd(c.filament_colour??"",e.color)&&(d+=2)),d+=b7e[l],Uy(c,"filament",a,n)==="mismatch"&&(d-=100),(o==null||d>o.score)&&(o={ref:{source:c.source,id:c.id},score:d})}return o==null?EB(t,"filament"):o.ref}function y7e(t){return t?`${t.source}:${t.id}`:""}function v7e(t){if(!t)return null;const e=t.indexOf(":");if(e<0)return null;const a=t.slice(0,e),n=t.slice(e+1);return a!=="orca_cloud"&&a!=="cloud"&&a!=="local"&&a!=="standard"?null:{source:a,id:n}}function w7e({requestId:t,sourceName:e}){const{t:a}=wt(),{showPersistentToast:n,dismissToast:i}=oa(),[s,o]=y.useState(0),[l,c]=y.useState(null);let d=e;try{d=decodeURIComponent(e)}catch{}y.useEffect(()=>{const g=Date.now(),v=setInterval(()=>o(Math.floor((Date.now()-g)/1e3)),1e3);return()=>clearInterval(v)},[]),y.useEffect(()=>{let g=!1;const v=setInterval(async()=>{if(g)return;const b=await ne.getPreviewSliceProgress(t);!g&&b&&c(b)},1e3);return()=>{g=!0,clearInterval(v)}},[t]);const u=`slice-preview-${t}`;y.useEffect(()=>{const g=l&&l.stage&&l.total_percent>0,v=S7e(s);return g?n(u,a("slice.previewWithProgress","Analyzing {{name}} — {{stage}} ({{percent}}%) — {{elapsed}}",{name:d,stage:l.stage,percent:Math.min(100,Math.max(0,Math.round(l.total_percent))),elapsed:v}),"loading"):n(u,a("slice.previewToast",{name:d,elapsed:v}),"loading"),()=>{i(u)}},[s,l,d,n,i,a,u]);const m=l?.stage,p=l?.total_percent,f=m&&typeof p=="number"&&p>0?`${m} (${Math.min(100,Math.max(0,Math.round(p)))}%)`:a("slice.analyzingPlateFilaments");return r.jsxs("div",{className:"flex flex-col gap-1 text-bambu-gray text-sm py-2",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(lt,{className:"w-4 h-4 animate-spin"}),f,r.jsxs("span",{className:"text-xs tabular-nums",children:[s,"s"]})]}),s>=5&&r.jsx("div",{className:"text-xs text-bambu-gray/70 pl-6",children:a("slice.analyzingPlateFilamentsHint","Running a preview slice to discover which AMS slots this plate uses. Cached after — re-opening is instant.")})]})}function S7e(t){const e=Math.max(0,Math.floor(t));if(e<60)return`${e}s`;const a=Math.floor(e/60),n=e%60;if(a<60)return`${a}m ${n}s`;const i=Math.floor(a/60),s=a%60;return`${i}h ${s}m`}function QA({source:t,onClose:e}){const{t:a}=wt(),{trackJob:n}=f7e(),i=na(),[s,o]=y.useState(null),[l,c]=y.useState(null),[d,u]=y.useState([]),[m,p]=y.useState(null),[f,g]=y.useState(null),[v,b]=y.useState([]),[x,S]=y.useState(null),[k,C]=y.useState(null),[N,T]=y.useState(!1),[j,D]=y.useState(null),P=$e({queryKey:["slicePlates",t.kind,t.id],queryFn:async()=>t.kind==="libraryFile"?ne.getLibraryFilePlates(t.id):ne.getArchivePlates(t.id),staleTime:6e4}),E=!!P.data?.is_multi_plate&&(P.data?.plates?.length??0)>1,z=E&&k==null,I=k??1,B=y.useMemo(()=>{const O=typeof crypto<"u"&&"randomUUID"in crypto?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2)}`;return`${t.kind}-${t.id}-p${I}-${O}`},[t.kind,t.id,I]),R=$e({queryKey:["sliceFilamentReqs",t.kind,t.id,I],queryFn:async()=>t.kind==="libraryFile"?ne.getLibraryFileFilamentRequirements(t.id,I,B):ne.getArchiveFilamentRequirements(t.id,I,B),enabled:!z,staleTime:6e4}),K=y.useMemo(()=>{const O=R.data?.filaments??[],q=O.length>0?O:[{slot_id:1,type:"",color:"",used_grams:0,used_meters:0}];return N?q.map(Z=>({...Z,used_in_plate:!0})):q},[N,R.data]),J=$e({queryKey:["slicerPresets"],queryFn:()=>ne.getSlicerPresets(),staleTime:6e4,enabled:!P.isLoading&&!z}),[X,ce]=y.useState(!1),de=async()=>{if(!X){ce(!0);try{const O=await ne.getSlicerPresets({refresh:!0});i.setQueryData(["slicerPresets"],O)}catch{i.invalidateQueries({queryKey:["slicerPresets"]})}finally{ce(!1)}}},oe=$e({queryKey:["slicerBundles"],queryFn:ne.listSlicerBundles,staleTime:6e4,enabled:!P.isLoading&&!z,retry:!1}),Y=$e({queryKey:["slicerPrinterModels"],queryFn:ne.getSlicerPrinterModels,staleTime:1/0}),ie=y.useMemo(()=>!m||!oe.data?null:oe.data.find(O=>O.id===m)??null,[m,oe.data]),me=ie!=null,he=y.useMemo(()=>!J.data||!s?null:$C(J.data,s,"printer")?.name??null,[J.data,s]),xe=y.useMemo(()=>g9e(oe.data??[],Y.data??{}),[oe.data,Y.data]),V=P.data?.embedded_printer??null,Q=P.data?.embedded_process??null;y.useEffect(()=>{const O=J.data;O&&s==null&&o(Use(O,"printer",V)??EB(O,"printer"))},[J.data,V]),y.useEffect(()=>{const O=J.data;O&&c(q=>{if(q){const Z=$C(O,q,"process");if(Z&&Uy(Z,"process",he,xe)!=="mismatch")return q}return g7e(O,he,xe,Q)})},[J.data,he,xe,Q]),y.useEffect(()=>{const O=J.data;O&&u(q=>K.map((Z,ee)=>{const re=q[ee]??null;if(re){const se=$C(O,re,"filament");if(se&&Uy(se,"filament",he,xe)!=="mismatch")return re}return x7e(O,{type:Z.type,color:Z.color},he,xe)}))},[J.data,K,he,xe]),y.useEffect(()=>{if(!ie){g(null),b([]);return}g(O=>O&&ie.process.includes(O)?O:ie.process[0]??null),b(O=>{if(O.length===K.length&&O.every(Z=>Z!=null))return O;const q=ie.filament[0]??null;return K.map((Z,ee)=>O[ee]??q)})},[ie,K]);const A=at({mutationFn:async O=>{const q=F(O);return t.kind==="libraryFile"?ne.sliceLibraryFile(t.id,q):ne.sliceArchive(t.id,q)},onSuccess:O=>{n(O.job_id,t.kind,t.filename),e()},onError:O=>{const q=O instanceof Error?O.message:String(O);S(q)}});function F(O){if(me){if(!ie||!f||v.length===0||v.some(Z=>Z==null))throw new Error(a("slice.bundleAllRequired"));return{bundle:{bundle_id:ie.id,printer_name:ie.printer[0]??ie.printer_preset_name,process_name:f,filament_names:v},...O!=null?{plate:O}:{},...j!=null?{bed_type:j}:{}}}if(!s||!l||d.length===0||d.some(q=>q==null))throw new Error(a("slice.allPresetsRequired"));return{printer_preset:s,process_preset:l,filament_preset:d[0],filament_presets:d,...O!=null?{plate:O}:{},...j!=null?{bed_type:j}:{}}}const U=me?ie!=null&&f!=null&&R.isSuccess&&v.length>0&&v.every(O=>O!=null):s!=null&&l!=null&&R.isSuccess&&d.length>0&&d.every(O=>O!=null),$=A.isPending,H=P.data?.plates?.length??0,le=E&&H>1&&!z;return z&&P.data?r.jsx(MB,{plates:P.data.plates,onSelect:O=>C(O),onClose:e}):r.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4",onClick:()=>{$||e()},children:r.jsxs("div",{className:"w-full max-w-xl max-h-[85vh] flex flex-col rounded-lg bg-bambu-dark-secondary border border-bambu-dark-tertiary/60",onClick:O=>O.stopPropagation(),children:[r.jsxs("div",{className:"flex-shrink-0 flex items-start justify-between gap-3 px-4 pt-4 pb-3 border-b border-bambu-dark-tertiary/40",children:[r.jsxs("div",{className:"min-w-0",children:[r.jsxs("h3",{className:"text-white font-medium flex items-center gap-2",children:[r.jsx(bd,{className:"w-4 h-4"}),a("slice.title")]}),r.jsxs("p",{className:"text-xs text-bambu-gray mt-1 truncate",title:t.filename,children:[t.filename,k!=null?` • ${a("archives.platePicker.plateLabel",{index:k})}`:""]})]}),r.jsx("button",{onClick:e,disabled:$,className:"flex-shrink-0 text-bambu-gray hover:text-white transition-colors disabled:opacity-50","aria-label":a("common.close"),children:r.jsx(Ht,{className:"w-5 h-5"})})]}),r.jsxs("div",{className:"flex-1 overflow-y-auto p-4 space-y-4",children:[(P.isLoading||J.isLoading)&&r.jsxs("div",{className:"flex items-center gap-2 text-bambu-gray text-sm",children:[r.jsx(lt,{className:"w-4 h-4 animate-spin"}),a("slice.loadingPresets")]}),J.isError&&r.jsx("div",{className:"text-sm text-red-400",role:"alert",children:a("slice.presetsLoadFailed","Failed to load presets. Open Settings → Profiles to import them, or sign in to Bambu Cloud.")}),J.data&&r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"flex items-start justify-between gap-2",children:[r.jsxs("div",{className:"flex-1 space-y-2",children:[r.jsx(NY,{status:J.data.cloud_status,cloudName:"bambu"}),r.jsx(NY,{status:J.data.orca_cloud_status,cloudName:"orca"})]}),r.jsxs("button",{type:"button",onClick:de,disabled:X||$,className:"flex-shrink-0 inline-flex items-center gap-1 px-2 py-1 rounded-md text-xs text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary/40 disabled:opacity-50 disabled:cursor-not-allowed transition-colors",title:a("slice.refreshPresetsTitle"),"aria-label":a("slice.refreshPresets"),children:[r.jsx(tr,{className:`w-3.5 h-3.5 ${X?"animate-spin":""}`}),a("slice.refreshPresets")]})]}),oe.data&&oe.data.length>0&&r.jsx(P7e,{bundles:oe.data,selectedId:m,onChange:p,disabled:$}),!me&&r.jsxs(r.Fragment,{children:[r.jsx(IF,{label:a("slice.printer"),slot:"printer",data:J.data,value:s,onChange:o,disabled:$}),r.jsx(IF,{label:a("slice.process"),slot:"process",data:J.data,value:l,onChange:c,disabled:$,selectedPrinterName:he,compatIndex:xe})]}),me&&ie&&r.jsxs(r.Fragment,{children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("slice.printer")}),r.jsx("div",{className:"px-3 py-2 rounded-md bg-bambu-dark/40 border border-bambu-dark-tertiary text-white text-sm",children:ie.printer_preset_name})]}),r.jsx(TY,{label:a("slice.process"),options:ie.process,value:f,onChange:g,disabled:$})]}),r.jsx(_7e,{value:j,onChange:D,disabled:$}),R.isLoading?r.jsx(w7e,{requestId:B,sourceName:t.filename}):me&&ie?K.map((O,q)=>{const Z=O.used_in_plate!==!1,ee=K.length>1?a("slice.filamentSlot",{index:q+1,type:O.type}):a("slice.filament"),re=Z?ee:`${ee} ${a("slice.notUsedByPlate")}`;return r.jsx(TY,{label:re,options:ie.filament,value:v[q]??null,onChange:se=>b(fe=>{const ue=fe.length===K.length?[...fe]:K.map((pe,G)=>fe[G]??null);return ue[q]=se,ue}),disabled:$||!Z,swatchColor:K.length>1?O.color:void 0},`bundle-filament-${q}`)}):K.map((O,q)=>{const Z=O.used_in_plate!==!1,ee=K.length>1?a("slice.filamentSlot",{index:q+1,type:O.type}):a("slice.filament"),re=Z?ee:`${ee} ${a("slice.notUsedByPlate")}`;return r.jsx(IF,{label:re,slot:"filament",data:J.data,value:d[q]??null,onChange:se=>u(fe=>{const ue=fe.length===K.length?[...fe]:K.map((pe,G)=>fe[G]??null);return ue[q]=se,ue}),disabled:$||!Z,swatchColor:K.length>1?O.color:void 0,selectedPrinterName:he,compatIndex:xe},`filament-${q}`)})]}),x&&r.jsx("div",{className:"text-sm text-red-400 bg-red-900/20 border border-red-900/40 rounded p-2",role:"alert",children:x})]}),r.jsxs("div",{className:"flex-shrink-0 flex justify-end gap-2 px-4 py-3 border-t border-bambu-dark-tertiary/40",children:[r.jsx("button",{type:"button",onClick:e,disabled:$,className:"px-3 py-1.5 text-sm rounded-md border border-bambu-dark-tertiary text-bambu-gray hover:text-white hover:border-bambu-gray transition-colors disabled:opacity-50",children:a("common.cancel")}),le&&r.jsxs("label",{className:"flex items-center gap-2 mr-auto text-sm text-bambu-gray cursor-pointer select-none",title:a("slice.actionAllTitle",{count:H}),children:[r.jsx("input",{type:"checkbox",checked:N,onChange:O=>T(O.target.checked),disabled:$,className:"cursor-pointer"}),a("slice.allPlatesToggle",{count:H})]}),r.jsx("button",{type:"button",onClick:()=>{S(null);const O=N?0:k;A.mutate(O)},disabled:!U||$,className:"px-3 py-1.5 text-sm rounded-md bg-bambu-green hover:bg-bambu-green/90 text-bambu-dark font-medium transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-2",children:$?r.jsxs(r.Fragment,{children:[r.jsx(lt,{className:"w-4 h-4 animate-spin"}),a("slice.enqueuing")]}):N?a("slice.actionAll",{count:H}):a("slice.action")})]})]})})}function NY({status:t,cloudName:e="bambu"}){const{t:a}=wt();if(t==="ok")return null;const n=e==="orca"?{not_authenticated:{key:"slice.orcaCloud.notAuthenticated",fallback:"Sign in to Orca Cloud (Profiles → Orca Cloud) to see your Orca presets."},expired:{key:"slice.orcaCloud.expired",fallback:"Orca Cloud session expired — sign in again to refresh your Orca presets."},unreachable:{key:"slice.orcaCloud.unreachable",fallback:"Orca Cloud is unreachable right now. Other presets still work."}}:{not_authenticated:{key:"slice.cloud.notAuthenticated",fallback:"Sign in to Bambu Cloud (Settings → Profiles → Cloud) to see your cloud presets."},expired:{key:"slice.cloud.expired",fallback:"Bambu Cloud session expired — sign in again to refresh your cloud presets."},unreachable:{key:"slice.cloud.unreachable",fallback:"Bambu Cloud is unreachable right now. Local and standard presets still work."}},i={not_authenticated:{tone:"border-bambu-dark-tertiary/40 bg-bambu-dark text-bambu-gray",icon:mu},expired:{tone:"border-amber-700/40 bg-amber-900/20 text-amber-200",icon:s3},unreachable:{tone:"border-bambu-dark-tertiary/40 bg-bambu-dark text-bambu-gray",icon:s3}},{tone:s,icon:o}=i[t],{key:l,fallback:c}=n[t];return r.jsxs("div",{className:`flex items-start gap-2 text-xs rounded-md border p-2 ${s}`,role:"status",children:[r.jsx(o,{className:"w-4 h-4 flex-shrink-0 mt-0.5"}),r.jsx("span",{children:a(l,c)})]})}const k7e=[{value:"Cool Plate",labelKey:"slice.bedType.coolPlate",fallback:"Cool Plate"},{value:"Cool Plate (SuperTack)",labelKey:"slice.bedType.coolPlateSuperTack",fallback:"Cool Plate SuperTack"},{value:"Engineering Plate",labelKey:"slice.bedType.engineering",fallback:"Engineering Plate"},{value:"High Temp Plate",labelKey:"slice.bedType.highTemp",fallback:"High Temp Plate"},{value:"Textured PEI Plate",labelKey:"slice.bedType.texturedPEI",fallback:"Textured PEI Plate"},{value:"Smooth PEI Plate",labelKey:"slice.bedType.smoothPEI",fallback:"Smooth PEI Plate"}];function _7e({value:t,onChange:e,disabled:a}){const{t:n}=wt();return r.jsxs("label",{className:"block",children:[r.jsx("span",{className:"block text-xs text-bambu-gray mb-1",children:n("slice.bedType.label")}),r.jsxs("select",{value:t??"",onChange:i=>e(i.target.value===""?null:i.target.value),disabled:a,className:"w-full px-3 py-2 rounded-md bg-bambu-dark border border-bambu-dark-tertiary text-white text-sm focus:outline-none focus:border-bambu-gray disabled:opacity-50",children:[r.jsx("option",{value:"",children:n("slice.bedType.auto")}),k7e.map(i=>r.jsx("option",{value:i.value,children:n(i.labelKey,i.fallback)},i.value))]})]})}function IF({label:t,slot:e,data:a,value:n,onChange:i,disabled:s,swatchColor:o,selectedPrinterName:l,compatIndex:c}){const{t:d}=wt(),{sections:u,otherEntries:m}=y.useMemo(()=>{const f=[{key:"orca_cloud",label:"slice.tier.orcaCloud",fallback:"Orca Cloud"},{key:"local",label:"slice.tier.local",fallback:"Imported"},{key:"cloud",label:"slice.tier.cloud",fallback:"Bambu Cloud"},{key:"standard",label:"slice.tier.standard",fallback:"Standard"}],g=e!=="printer",v=[],b=[];for(const{key:x,label:S,fallback:k}of f){const C=a[x][e];if(!g){C.length>0&&v.push({tierLabel:d(S,k),entries:C});continue}const N=[];for(const T of C)Uy(T,e,l??null,c??h9e)==="mismatch"?b.push(T):N.push(T);N.length>0&&v.push({tierLabel:d(S,k),entries:N})}return{sections:v,otherEntries:b}},[a,e,d,l,c]),p=u.reduce((f,g)=>f+g.entries.length,0)+m.length;return r.jsxs("label",{className:"block",children:[r.jsxs("span",{className:"flex items-center gap-2 text-xs text-bambu-gray mb-1",children:[o&&r.jsx("span",{className:"inline-block w-3 h-3 rounded-full border border-bambu-dark-tertiary",style:{backgroundColor:o||"transparent"},"aria-hidden":!0}),r.jsx("span",{children:t})]}),r.jsxs("select",{value:y7e(n),onChange:f=>i(v7e(f.target.value)),disabled:s||p===0,className:"w-full px-3 py-2 rounded-md bg-bambu-dark border border-bambu-dark-tertiary text-white text-sm focus:outline-none focus:border-bambu-gray disabled:opacity-50",children:[r.jsx("option",{value:"",children:d(p===0?"slice.noPresetsForSlot":"slice.selectPreset")}),u.map(f=>r.jsx("optgroup",{label:f.tierLabel,children:f.entries.map(g=>r.jsx("option",{value:`${g.source}:${g.id}`,children:g.name},`${g.source}:${g.id}`))},f.tierLabel)),m.length>0&&r.jsx("optgroup",{label:d("slice.otherPrinters"),children:m.map(f=>r.jsx("option",{value:`${f.source}:${f.id}`,children:f.name},`${f.source}:${f.id}`))})]})]})}function P7e({bundles:t,selectedId:e,onChange:a,disabled:n}){const{t:i}=wt();return r.jsxs("label",{className:"block",children:[r.jsxs("span",{className:"block text-sm text-bambu-gray mb-1 inline-flex items-center gap-1.5",children:[r.jsx(Kr,{className:"w-3.5 h-3.5"}),i("slice.bundle")]}),r.jsxs("select",{value:e??"",onChange:s=>a(s.target.value||null),disabled:n,className:"w-full px-3 py-2 rounded-md bg-bambu-dark border border-bambu-dark-tertiary text-white text-sm focus:outline-none focus:border-bambu-gray disabled:opacity-50",children:[r.jsx("option",{value:"",children:i("slice.bundleNone")}),t.map(s=>r.jsx("option",{value:s.id,children:s.printer_preset_name},s.id))]})]})}function TY({label:t,options:e,value:a,onChange:n,disabled:i,swatchColor:s}){const{t:o}=wt();return r.jsxs("label",{className:"block",children:[r.jsxs("span",{className:"block text-sm text-bambu-gray mb-1 inline-flex items-center gap-1.5",children:[s&&r.jsx("span",{className:"inline-block w-3 h-3 rounded-sm border border-black/20",style:{backgroundColor:s||"transparent"},"aria-hidden":!0}),r.jsx("span",{children:t})]}),r.jsxs("select",{value:a??"",onChange:l=>n(l.target.value||null),disabled:i||e.length===0,className:"w-full px-3 py-2 rounded-md bg-bambu-dark border border-bambu-dark-tertiary text-white text-sm focus:outline-none focus:border-bambu-gray disabled:opacity-50",children:[r.jsx("option",{value:"",children:e.length===0?o("slice.noPresetsForSlot"):o("slice.selectPreset")}),e.map(l=>r.jsx("option",{value:l,children:l},l))]})]})}function C7e(){const t=navigator.userAgent.toLowerCase(),e=navigator.platform?.toLowerCase()||"";return t.includes("win")||e.includes("win")?"windows":t.includes("mac")||e.includes("mac")?"macos":t.includes("linux")||e.includes("linux")?"linux":"unknown"}function Rm(t,e="bambu_studio"){let a;const n=encodeURIComponent(t);e==="orcaslicer"?a=`orcaslicer://open?file=${n}`:C7e()==="macos"?a=`bambustudioopen://${n}`:a=`bambustudio://open?file=${n}`;const i=document.createElement("a");i.href=a,i.style.display="none",document.body.appendChild(i),i.click(),document.body.removeChild(i)}const AY=768;function Hse(){const[t,e]=y.useState(()=>typeof window<"u"?window.innerWidth{const a=window.matchMedia(`(max-width: ${AY-1}px)`),n=i=>{e(i.matches)};return e(a.matches),a.addEventListener("change",n),()=>a.removeEventListener("change",n)},[]),t}function N7e({onClose:t,initialFiles:e}){const{t:a}=wt(),n=na(),{showToast:i}=oa(),s=y.useRef(null),[o,l]=y.useState(()=>e?.filter(N=>N.name.endsWith(".3mf")).map(N=>({file:N,status:"pending"}))||[]),[c,d]=y.useState(!1),[u,m]=y.useState(null);y.useEffect(()=>{const N=T=>{T.key==="Escape"&&t()};return window.addEventListener("keydown",N),()=>window.removeEventListener("keydown",N)},[t]);const p=at({mutationFn:N=>ne.uploadArchivesBulk(N),onSuccess:N=>{m(N),n.invalidateQueries({queryKey:["archives"]}),n.invalidateQueries({queryKey:["archiveStats"]}),l(T=>T.map(j=>{const D=N.results.find(E=>E.filename===j.file.name),P=N.errors.find(E=>E.filename===j.file.name);return D?{...j,status:"success",archiveId:D.id}:P?{...j,status:"error",error:P.error}:j})),N.failed===0?i(`${N.uploaded} file${N.uploaded!==1?"s":""} uploaded`):N.uploaded===0?i(`Failed to upload ${N.failed} file${N.failed!==1?"s":""}`,"error"):i(`${N.uploaded} uploaded, ${N.failed} failed`,"warning")},onError:()=>{l(N=>N.map(T=>({...T,status:"error",error:"Upload failed"}))),i("Upload failed","error")}}),f=y.useCallback(N=>{N.preventDefault(),d(!0)},[]),g=y.useCallback(N=>{N.preventDefault(),d(!1)},[]),v=y.useCallback(N=>{N.preventDefault(),d(!1);const T=Array.from(N.dataTransfer.files).filter(j=>j.name.endsWith(".3mf"));T.length>0&&l(j=>[...j,...T.map(D=>({file:D,status:"pending"}))])},[]),b=y.useCallback(N=>{const T=Array.from(N.target.files||[]).filter(j=>j.name.endsWith(".3mf"));T.length>0&&l(j=>[...j,...T.map(D=>({file:D,status:"pending"}))]),s.current&&(s.current.value="")},[]),x=y.useCallback(N=>{l(T=>T.filter((j,D)=>D!==N))},[]),S=()=>{if(o.length===0)return;const N=o.filter(T=>T.status==="pending");N.length!==0&&(l(T=>T.map(j=>j.status==="pending"?{...j,status:"uploading"}:j)),p.mutate(N.map(T=>T.file)))},k=o.filter(N=>N.status==="pending").length,C=p.isPending;return r.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:r.jsx(Tt,{className:"w-full max-w-2xl max-h-[90vh] flex flex-col",children:r.jsxs(jt,{className:"p-0 flex flex-col h-full",children:[r.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[r.jsx("h2",{className:"text-xl font-semibold text-white",children:a("uploadModal.title")}),r.jsx("button",{onClick:t,className:"text-bambu-gray hover:text-white transition-colors",children:r.jsx(Ht,{className:"w-5 h-5"})})]}),r.jsx("div",{className:"p-4",children:r.jsxs("div",{className:`border-2 border-dashed rounded-lg p-8 text-center transition-colors ${c?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary hover:border-bambu-gray"}`,onDragOver:f,onDragLeave:g,onDrop:v,children:[r.jsx(fn,{className:"w-12 h-12 mx-auto mb-4 text-bambu-gray"}),r.jsx("p",{className:"text-white mb-2",children:a("uploadModal.dragDrop")}),r.jsx("p",{className:"text-bambu-gray text-sm mb-4",children:a("uploadModal.or")}),r.jsx(Le,{variant:"secondary",onClick:()=>s.current?.click(),disabled:C,children:a("uploadModal.browseFiles")}),r.jsx("input",{ref:s,type:"file",accept:".3mf",multiple:!0,className:"hidden",onChange:b})]})}),r.jsx("div",{className:"px-4 pb-4",children:r.jsx("p",{className:"text-xs text-bambu-gray",children:a("uploadModal.extractionInfo")})}),o.length>0&&r.jsx("div",{className:"px-4 pb-4 max-h-60 overflow-y-auto",children:r.jsx("div",{className:"space-y-2",children:o.map((N,T)=>r.jsxs("div",{className:"flex items-center gap-3 p-3 bg-bambu-dark rounded-lg",children:[r.jsx(F1,{className:"w-5 h-5 text-bambu-gray flex-shrink-0"}),r.jsx("span",{className:"flex-1 text-white text-sm truncate",children:N.file.name}),r.jsxs("span",{className:"text-xs text-bambu-gray",children:[(N.file.size/(1024*1024)).toFixed(1)," MB"]}),N.status==="pending"&&r.jsx("button",{onClick:()=>x(T),className:"text-bambu-gray hover:text-red-400 transition-colors",disabled:C,children:r.jsx(Ht,{className:"w-4 h-4"})}),N.status==="uploading"&&r.jsx(lt,{className:"w-4 h-4 text-bambu-green animate-spin"}),N.status==="success"&&r.jsx(fr,{className:"w-4 h-4 text-bambu-green"}),N.status==="error"&&r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("span",{className:"text-xs text-red-400",children:N.error}),r.jsx(Sn,{className:"w-4 h-4 text-red-400"})]})]},`${N.file.name}-${T}`))})}),u&&r.jsx("div",{className:"px-4 pb-4",children:r.jsx("div",{className:"p-3 bg-bambu-dark rounded-lg",children:r.jsxs("p",{className:"text-sm text-white",children:[r.jsx("span",{className:"text-bambu-green",children:u.uploaded})," ",a("uploadModal.uploaded"),u.failed>0&&r.jsxs(r.Fragment,{children:[", ",r.jsx("span",{className:"text-red-400",children:u.failed})," ",a("uploadModal.failed")]})]})})}),r.jsxs("div",{className:"flex gap-3 p-4 border-t border-bambu-dark-tertiary",children:[r.jsx(Le,{variant:"secondary",onClick:t,className:"flex-1",children:a(u?"common.close":"common.cancel")}),!u&&r.jsx(Le,{onClick:S,disabled:k===0||C,className:"flex-1",children:C?r.jsxs(r.Fragment,{children:[r.jsx(lt,{className:"w-4 h-4 animate-spin"}),a("uploadModal.uploading")]}):r.jsxs(r.Fragment,{children:[r.jsx(fn,{className:"w-4 h-4"}),a("uploadModal.upload")," ",k>0&&`(${k})`]})})]})]})})})}const T7e=365;function A7e({onClose:t,initialDays:e}){const{t:a}=wt(),n=na(),{showToast:i}=oa(),[s,o]=y.useState(e??T7e),[l,c]=y.useState(!1),[d,u]=y.useState(s);y.useEffect(()=>{const x=window.setTimeout(()=>u(s),300);return()=>window.clearTimeout(x)},[s]);const m=$e({queryKey:["archive-purge-preview",d,l],queryFn:()=>ne.previewArchivePurge(d,l),enabled:d>=1}),p=at({mutationFn:()=>ne.executeArchivePurge(s,l),onSuccess:x=>{i(a("archivePurge.toast.success",{count:x.deleted}),"success"),n.invalidateQueries({queryKey:["archives"]}),n.invalidateQueries({queryKey:["archive-stats"]}),t()},onError:x=>i(x.message||a("archivePurge.toast.failed"),"error")});y.useEffect(()=>{const x=S=>{S.key==="Escape"&&!p.isPending&&t()};return window.addEventListener("keydown",x),()=>window.removeEventListener("keydown",x)},[t,p.isPending]);const f=m.data,g=f?.count??0,v=f?.total_bytes??0,b=g>0&&!p.isPending;return r.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4",children:r.jsxs("div",{className:"bg-white dark:bg-gray-900 rounded-lg shadow-xl max-w-lg w-full",children:[r.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-gray-200 dark:border-gray-700",children:[r.jsxs("h2",{className:"text-lg font-semibold text-gray-900 dark:text-gray-100 flex items-center gap-2",children:[r.jsx(ra,{className:"w-5 h-5"}),a("archivePurge.title")]}),r.jsx("button",{onClick:t,className:"text-gray-400 hover:text-gray-600 dark:hover:text-gray-200","aria-label":a("common.close"),disabled:p.isPending,children:r.jsx(Ht,{className:"w-5 h-5"})})]}),r.jsxs("div",{className:"p-4 space-y-4",children:[r.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-400",children:a("archivePurge.description")}),r.jsxs("div",{children:[r.jsx("label",{htmlFor:"archive-purge-days",className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1",children:a("archivePurge.ageLabel")}),r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("input",{id:"archive-purge-days",type:"number",min:1,max:3650,value:s,onChange:x=>o(Math.max(1,Math.min(3650,parseInt(x.target.value||"0",10)||0))),className:"w-24 rounded border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-sm px-2 py-1 text-gray-900 dark:text-gray-100"}),r.jsx("span",{className:"text-sm text-gray-600 dark:text-gray-400",children:a("archivePurge.days")})]})]}),r.jsxs("div",{className:"rounded border border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-800/30 p-3",children:[r.jsx("div",{className:"text-xs font-semibold uppercase tracking-wide text-gray-600 dark:text-gray-300 mb-2",children:a("archivePurge.effectsTitle")}),r.jsxs("ul",{className:"text-xs text-gray-700 dark:text-gray-300 space-y-1 list-disc pl-4",children:[r.jsx("li",{children:a("archivePurge.effect1")}),r.jsx("li",{children:a("archivePurge.effect2")}),r.jsx("li",{children:a("archivePurge.effect3")}),r.jsx("li",{children:a("archivePurge.effect4")})]})]}),r.jsx("div",{className:"rounded border border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-800/50 p-3",children:m.isLoading||m.isFetching?r.jsxs("div",{className:"flex items-center gap-2 text-sm text-gray-500 dark:text-gray-400",children:[r.jsx(lt,{className:"w-4 h-4 animate-spin"})," ",a("archivePurge.previewLoading")]}):m.isError?r.jsx("div",{className:"text-sm text-red-600 dark:text-red-400",children:m.error?.message??a("archivePurge.previewFailed")}):r.jsxs("div",{className:"text-sm text-gray-900 dark:text-gray-100",children:[r.jsx("div",{className:"font-medium",children:a("archivePurge.previewSummary",{count:g,size:cs(v)})}),f?.sample_filenames&&f.sample_filenames.length>0&&r.jsxs("ul",{className:"mt-2 text-xs text-gray-600 dark:text-gray-400 space-y-0.5 list-disc pl-4",children:[f.sample_filenames.map(x=>r.jsx("li",{className:"truncate",children:x},x)),g>f.sample_filenames.length&&r.jsx("li",{className:"list-none italic text-gray-500",children:a("archivePurge.andMore",{count:g-f.sample_filenames.length})})]})]})}),r.jsxs("label",{className:"flex gap-2 items-start rounded border border-gray-200 dark:border-gray-700 px-3 py-2 cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-800/50",children:[r.jsx("input",{type:"checkbox",checked:l,onChange:x=>c(x.target.checked),disabled:p.isPending,className:"mt-0.5 shrink-0"}),r.jsxs("span",{className:"text-xs text-gray-700 dark:text-gray-300",children:[r.jsx("span",{className:"font-medium block mb-0.5",children:a("archivePurge.purgeStatsLabel")}),r.jsx("span",{className:"text-gray-500 dark:text-gray-400",children:a("archivePurge.purgeStatsHint")})]})]}),r.jsxs("div",{className:"flex gap-2 items-start text-xs text-amber-700 dark:text-amber-400 bg-amber-50 dark:bg-amber-900/20 rounded px-3 py-2",children:[r.jsx(xa,{className:"w-4 h-4 mt-0.5 shrink-0"}),r.jsx("span",{children:a("archivePurge.warning")})]})]}),r.jsxs("div",{className:"flex justify-end gap-2 p-4 border-t border-gray-200 dark:border-gray-700",children:[r.jsx(Le,{variant:"secondary",onClick:t,disabled:p.isPending,children:a("common.cancel")}),r.jsx(Le,{variant:"danger",disabled:!b,onClick:()=>p.mutate(),children:p.isPending?r.jsxs(r.Fragment,{children:[r.jsx(lt,{className:"w-4 h-4 animate-spin mr-1"}),a("archivePurge.purging")]}):a("archivePurge.confirmCta",{count:g})})]})]})})}function j7e(t){if(!t||t<=0)return"—";const e=Math.floor(t/3600),a=Math.floor(t%3600/60);return e>0?`${e}h ${a}m`:`${a}m`}function M7e(t){if(!t)return"—";const e=Ga(t);return e?e.toLocaleString():"—"}function qse({archiveId:t}){const{t:e}=wt(),{data:a,isLoading:n}=$e({queryKey:["archive-runs",t],queryFn:()=>ne.getArchiveRuns(t)});if(n)return r.jsx("div",{className:"flex justify-center py-4",children:r.jsx(lt,{className:"w-5 h-5 text-bambu-gray animate-spin"})});const i=a?.items||[];return i.length===0?r.jsx("p",{className:"text-sm text-bambu-gray italic py-2",children:e("archives.runLog.empty")}):r.jsx("div",{className:"overflow-x-auto",children:r.jsxs("table",{className:"w-full text-xs",children:[r.jsx("thead",{children:r.jsxs("tr",{className:"text-bambu-gray border-b border-bambu-dark-tertiary",children:[r.jsx("th",{className:"text-left py-1.5 pr-2 font-medium",children:e("archives.runLog.col.date")}),r.jsx("th",{className:"text-left py-1.5 pr-2 font-medium",children:e("archives.runLog.col.status")}),r.jsx("th",{className:"text-right py-1.5 pr-2 font-medium",children:e("archives.runLog.col.duration")}),r.jsx("th",{className:"text-right py-1.5 pr-2 font-medium",children:e("archives.runLog.col.filament")}),r.jsx("th",{className:"text-right py-1.5 font-medium",children:e("archives.runLog.col.cost")})]})}),r.jsx("tbody",{children:i.map(s=>{const o=s.status==="completed"?"text-bambu-green":s.status==="failed"?"text-red-400":"text-bambu-gray";return r.jsxs("tr",{className:"border-b border-bambu-dark-tertiary/40 last:border-0",children:[r.jsx("td",{className:"py-1.5 pr-2 text-bambu-gray-light",children:M7e(s.started_at||s.created_at)}),r.jsxs("td",{className:`py-1.5 pr-2 font-medium ${o}`,children:[e(`archives.runLog.status.${s.status}`,{defaultValue:s.status}),s.failure_reason&&r.jsx("span",{className:"block text-[10px] text-bambu-gray font-normal",children:e(`editArchive.failureReasons.${s.failure_reason}`,{defaultValue:s.failure_reason})})]}),r.jsx("td",{className:"py-1.5 pr-2 text-right text-bambu-gray-light",children:j7e(s.duration_seconds)}),r.jsx("td",{className:"py-1.5 pr-2 text-right text-bambu-gray-light",children:s.filament_used_grams!=null?`${s.filament_used_grams.toFixed(1)} g`:"—"}),r.jsx("td",{className:"py-1.5 text-right text-bambu-gray-light",children:s.cost!=null?s.cost.toFixed(2):"—"})]},s.id)})})]})})}const WC=["adhesionFailure","spaghettiDetached","layerShift","cloggedNozzle","filamentRunout","warping","stringing","underExtrusion","powerFailure","userCancelled","other"],E7e=["completed","failed","aborted","printing"];function Vse({archive:t,onClose:e,existingTags:a=[]}){const{t:n}=wt();y.useEffect(()=>{const F=U=>{U.key==="Escape"&&e()};return window.addEventListener("keydown",F),()=>window.removeEventListener("keydown",F)},[e]);const i=na(),[s,o]=y.useState(t.print_name||""),[l,c]=y.useState(t.printer_id),[d,u]=y.useState(t.project_id??null),[m,p]=y.useState(t.notes||""),[f,g]=y.useState(t.tags||""),[v,b]=y.useState(()=>{const F=t.failure_reason||"";return F?WC.includes(F)?F:WC.find($=>n(`editArchive.failureReasons.${$}`)===F)||"":""}),[x,S]=y.useState(t.status),[k,C]=y.useState(t.quantity??1),[N,T]=y.useState(t.photos||[]),[j,D]=y.useState(t.external_url||""),[P,E]=y.useState(!1),[z,I]=y.useState(!1),B=y.useRef(null),R=y.useRef(null),K=y.useRef(null),{data:J}=$e({queryKey:["printers"],queryFn:ne.getPrinters}),{data:X}=$e({queryKey:["projects"],queryFn:()=>ne.getProjects(),select:F=>[...F].sort((U,$)=>U.name.localeCompare($.name))}),{data:ce}=$e({queryKey:["tags"],queryFn:ne.getTags,enabled:a.length===0}),de=a.length>0?a:ce?.map(F=>F.name)||[],oe=f.split(",").map(F=>F.trim()).filter(Boolean),Y=f.includes(",")?f.substring(f.lastIndexOf(",")+1).trim().toLowerCase():f.trim().toLowerCase(),ie=de.filter(F=>!oe.includes(F)&&(Y===""||F.toLowerCase().includes(Y))),me=F=>{let U;if(Y&&!de.includes(Y)?U=f.includes(",")?f.substring(0,f.lastIndexOf(",")).split(",").map($=>$.trim()).filter(Boolean):[]:U=oe,!U.includes(F)){const $=[...U,F].join(", ");g($)}K.current!==null&&clearTimeout(K.current),B.current?.focus()},he=F=>{const U=oe.filter($=>$!==F).join(", ");g(U)},xe=at({mutationFn:F=>ne.updateArchive(t.id,F),onSuccess:()=>{i.invalidateQueries({queryKey:["archives"]}),i.invalidateQueries({queryKey:["projects"]}),e()}}),V=async F=>{const U=F.target.files?.[0];if(U){E(!0);try{const $=await ne.uploadArchivePhoto(t.id,U);T($.photos),i.invalidateQueries({queryKey:["archives"]})}catch($){console.error("Failed to upload photo:",$)}finally{E(!1),R.current&&(R.current.value="")}}},Q=async F=>{try{const U=await ne.deleteArchivePhoto(t.id,F);T(U.photos||[]),i.invalidateQueries({queryKey:["archives"]})}catch(U){console.error("Failed to delete photo:",U)}},A=F=>{F.preventDefault();const U={print_name:s||void 0,printer_id:l,project_id:d,notes:m||void 0,tags:f||void 0,quantity:k,external_url:j||null};x!==t.status&&(U.status=x),x==="failed"||x==="aborted"?U.failure_reason=v||void 0:(t.status==="failed"||t.status==="aborted")&&(U.failure_reason=null),xe.mutate(U)};return r.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:e,children:r.jsxs("div",{className:"bg-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary w-full max-w-md max-h-[90vh] flex flex-col",onClick:F=>F.stopPropagation(),children:[r.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary",children:[r.jsx("h2",{className:"text-lg font-semibold text-white",children:n("editArchive.title")}),r.jsx("button",{onClick:e,className:"text-bambu-gray hover:text-white transition-colors",children:r.jsx(Ht,{className:"w-5 h-5"})})]}),r.jsxs("form",{onSubmit:A,className:"p-6 space-y-4 overflow-y-auto flex-1",children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("archives.runLog.title")}),r.jsx(qse,{archiveId:t.id})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("editArchive.name")}),r.jsx("input",{type:"text",value:s,onChange:F=>o(F.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",placeholder:n("editArchive.namePlaceholder")})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("editArchive.printer")}),r.jsxs("select",{value:l??"",onChange:F=>c(F.target.value?Number(F.target.value):null),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[r.jsx("option",{value:"",children:n("editArchive.noPrinter")}),J?.map(F=>r.jsx("option",{value:F.id,children:F.name},F.id))]})]}),r.jsxs("div",{children:[r.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[r.jsx(no,{className:"w-4 h-4 inline mr-1"}),n("editArchive.project")]}),r.jsxs("select",{value:d??"",onChange:F=>u(F.target.value?Number(F.target.value):null),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[r.jsx("option",{value:"",children:n("editArchive.noProject")}),X?.map(F=>r.jsx("option",{value:F.id,children:F.name},F.id))]})]}),r.jsxs("div",{children:[r.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[r.jsx(Cxe,{className:"w-4 h-4 inline mr-1"}),n("editArchive.itemsPrinted")]}),r.jsx("input",{type:"number",min:1,value:k,onChange:F=>C(Math.max(1,parseInt(F.target.value)||1)),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",placeholder:"1"}),r.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:n("editArchive.itemsPrintedHelp")})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("editArchive.notes")}),r.jsx("textarea",{value:m,onChange:F=>p(F.target.value),rows:3,className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none resize-none",placeholder:n("editArchive.notesPlaceholder")})]}),r.jsxs("div",{children:[r.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[r.jsx(rv,{className:"w-4 h-4 inline mr-1"}),n("editArchive.externalLink")]}),r.jsx("input",{type:"url",value:j,onChange:F=>D(F.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",placeholder:"https://printables.com/model/..."}),r.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:n("editArchive.externalLinkHelp")})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("editArchive.tags")}),oe.length>0&&r.jsx("div",{className:"flex flex-wrap gap-1.5 mb-2",children:oe.map(F=>r.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 bg-bambu-dark-tertiary rounded text-sm text-white",children:[r.jsx(Xm,{className:"w-3 h-3"}),F,r.jsx("button",{type:"button",onClick:()=>he(F),className:"ml-0.5 text-bambu-gray hover:text-white",children:r.jsx(Ht,{className:"w-3 h-3"})})]},F))}),r.jsxs("div",{className:"relative",children:[r.jsx("input",{ref:B,type:"text",value:f,onChange:F=>g(F.target.value),onFocus:()=>{K.current!==null&&clearTimeout(K.current),I(!0)},onBlur:()=>{K.current=window.setTimeout(()=>I(!1),200)},className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",placeholder:oe.length>0?n("editArchive.addMoreTags"):n("editArchive.tagsPlaceholder")}),z&&ie.length>0&&r.jsxs("div",{className:"absolute top-full left-0 right-0 mt-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-lg z-10 max-h-40 overflow-y-auto",children:[r.jsxs("div",{className:"p-2 text-xs text-bambu-gray border-b border-bambu-dark-tertiary",children:[Y?n("editArchive.matchingTags",{query:Y}):n("editArchive.existingTags")," ",n("editArchive.clickToAdd")]}),r.jsx("div",{className:"p-2 flex flex-wrap gap-1.5",children:ie.map(F=>r.jsx("button",{type:"button",onClick:()=>me(F),className:"px-2 py-0.5 bg-bambu-dark-tertiary hover:bg-bambu-green/20 rounded text-sm text-bambu-gray hover:text-white transition-colors",children:F},F))})]})]})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("editArchive.status")}),r.jsx("select",{value:x,onChange:F=>{S(F.target.value),F.target.value==="completed"&&b("")},className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:E7e.map(F=>r.jsx("option",{value:F,children:n(`editArchive.statuses.${F}`)},F))})]}),(x==="failed"||x==="aborted")&&r.jsxs("div",{children:[r.jsx("label",{htmlFor:"failure-reason-select",className:"block text-sm text-bambu-gray mb-1",children:n("editArchive.failureReason")}),r.jsxs("select",{id:"failure-reason-select",value:v,onChange:F=>b(F.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[r.jsx("option",{value:"",children:n("editArchive.selectReason")}),WC.map(F=>r.jsx("option",{value:F,children:n(`editArchive.failureReasons.${F}`)},F))]})]}),r.jsxs("div",{children:[r.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[r.jsx(wy,{className:"w-4 h-4 inline mr-1"}),n("editArchive.photos")]}),r.jsxs("div",{className:"flex flex-wrap gap-2 mb-2",children:[N.map(F=>r.jsxs("div",{className:"relative group",children:[r.jsx("img",{src:ne.getArchivePhotoUrl(t.id,F),alt:n("editArchive.printResult"),className:"w-20 h-20 object-cover rounded-lg border border-bambu-dark-tertiary"}),r.jsx("button",{type:"button",onClick:()=>Q(F),className:"absolute -top-1 -right-1 p-1 bg-red-500 rounded-full opacity-0 group-hover:opacity-100 transition-opacity",children:r.jsx(ra,{className:"w-3 h-3 text-white"})})]},F)),r.jsxs("label",{className:"w-20 h-20 flex items-center justify-center border-2 border-dashed border-bambu-dark-tertiary rounded-lg cursor-pointer hover:border-bambu-green transition-colors",children:[r.jsx("input",{ref:R,type:"file",accept:"image/jpeg,image/png,image/webp",onChange:V,className:"hidden",disabled:P}),P?r.jsx(lt,{className:"w-6 h-6 text-bambu-gray animate-spin"}):r.jsx(or,{className:"w-6 h-6 text-bambu-gray"})]})]}),r.jsx("p",{className:"text-xs text-bambu-gray",children:n("editArchive.photosHelp")})]}),r.jsxs("div",{className:"flex gap-3 pt-2",children:[r.jsx(Le,{type:"button",variant:"secondary",onClick:e,className:"flex-1",children:n("common.cancel")}),r.jsxs(Le,{type:"submit",disabled:xe.isPending,className:"flex-1",children:[r.jsx(ms,{className:"w-4 h-4"}),xe.isPending?n("common.saving"):n("common.save")]})]})]})]})})}function Gse({archiveId:t,archiveName:e,onClose:a}){const{t:n}=wt();return y.useEffect(()=>{const i=s=>{s.key==="Escape"&&a()};return window.addEventListener("keydown",i),()=>window.removeEventListener("keydown",i)},[a]),r.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:a,children:r.jsxs("div",{className:"bg-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary w-full max-w-2xl max-h-[85vh] flex flex-col",onClick:i=>i.stopPropagation(),children:[r.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[r.jsx(Zh,{className:"w-5 h-5 text-bambu-green flex-shrink-0"}),r.jsx("h2",{className:"text-lg font-semibold text-white truncate",title:e||"",children:n("archives.runLog.modalTitle",{name:e||n("archives.runLog.modalTitleFallback")})})]}),r.jsx("button",{onClick:a,className:"text-bambu-gray hover:text-white transition-colors",title:n("common.close"),children:r.jsx(Ht,{className:"w-5 h-5"})})]}),r.jsx("div",{className:"p-6 overflow-y-auto flex-1",children:r.jsx(qse,{archiveId:t})})]})})}function D7e({items:t,searchPlaceholder:e,onClose:a,className:n,onMouseEnter:i,onMouseLeave:s}){const[o,l]=y.useState(""),c=y.useRef(null);y.useEffect(()=>{if(e){const m=window.setTimeout(()=>c.current?.focus(),0);return()=>window.clearTimeout(m)}},[e]);const d=o.trim().toLowerCase(),u=e&&d?t.filter(m=>m.label.toLowerCase().includes(d)):t;return r.jsxs("div",{className:n,onMouseEnter:i,onMouseLeave:s,children:[e&&r.jsx("div",{className:"sticky top-0 z-[1] px-2 py-1.5 bg-bambu-dark-secondary border-b border-bambu-dark-tertiary",children:r.jsxs("div",{className:"relative",children:[r.jsx(br,{className:"absolute left-2 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-bambu-gray pointer-events-none"}),r.jsx("input",{ref:c,type:"text",value:o,onChange:m=>l(m.target.value),onKeyDown:m=>{if(m.key==="Enter"){const p=u.find(f=>!f.disabled);p&&(p.onClick(),a())}},placeholder:e,className:"w-full pl-7 pr-2 py-1 text-sm bg-bambu-dark border border-bambu-dark-tertiary rounded text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]})}),u.map((m,p)=>r.jsxs("button",{onClick:()=>{m.disabled||(m.onClick(),a())},disabled:m.disabled,className:`w-full flex items-center gap-2 px-3 py-2 text-sm text-left transition-colors ${m.disabled?"text-bambu-gray cursor-not-allowed":m.danger?"text-red-400 hover:bg-red-400/10":"text-white hover:bg-bambu-dark-tertiary"}`,children:[m.icon&&r.jsx("span",{className:"w-4 h-4 flex-shrink-0 flex items-center justify-center",children:m.icon}),r.jsx("span",{className:"flex-1 truncate",children:m.label})]},p)),e&&u.length===0&&r.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray text-center italic",children:"—"})]})}function $se({x:t,y:e,items:a,onClose:n}){const i=y.useRef(null),[s,o]=y.useState(null),l=y.useRef(null),[c,d]=y.useState({x:t,y:e,visible:!1}),[u,m]=y.useState(!1),[p,f]=y.useState({});y.useEffect(()=>{const b=k=>{i.current&&!i.current.contains(k.target)&&n()},x=k=>{k.key==="Escape"&&n()},S=k=>{i.current&&i.current.contains(k.target)||n()};return document.addEventListener("mousedown",b),document.addEventListener("keydown",x),document.addEventListener("scroll",S,!0),()=>{document.removeEventListener("mousedown",b),document.removeEventListener("keydown",x),document.removeEventListener("scroll",S,!0),l.current&&clearTimeout(l.current)}},[n]),y.useLayoutEffect(()=>{if(i.current){i.current.style.visibility="hidden",i.current.style.display="block";const b=i.current.getBoundingClientRect(),x=window.innerWidth,S=window.innerHeight,k=8;let C=t,N=e;t+b.width>x-k&&(C=Math.max(k,x-b.width-k)),CS-k&&(N=Math.max(k,S-b.height-k)),NT),d({x:C,y:N,visible:!0})}},[t,e]);const g=(b,x)=>{l.current&&(clearTimeout(l.current),l.current=null);const S=x.getBoundingClientRect(),k=window.innerHeight,C=300,j=k-S.top-8C;f(D=>({...D,[b]:j?"bottom":"top"})),o(b)},v=()=>{l.current=window.setTimeout(()=>{o(null)},150)};return r.jsx("div",{ref:i,className:"fixed z-50 min-w-[180px] max-w-[280px] bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl py-1",style:{left:c.x,top:c.y,visibility:c.visible?"visible":"hidden"},children:a.map((b,x)=>{if(b.divider)return r.jsx("div",{className:"my-1 border-t border-bambu-dark-tertiary"},x);const S=b.submenu&&b.submenu.length>0;return r.jsxs("div",{className:"relative",onMouseEnter:k=>S&&g(x,k.currentTarget),onMouseLeave:()=>S&&v(),children:[r.jsxs("button",{onMouseEnter:k=>S&&g(x,k.currentTarget.parentElement),onClick:()=>{S?o(s===x?null:x):b.disabled||(b.onClick(),n())},disabled:b.disabled,title:b.title,className:`w-full flex items-center gap-2 px-3 py-2 text-sm text-left transition-colors ${b.disabled?"text-bambu-gray cursor-not-allowed":b.danger?"text-red-400 hover:bg-red-400/10":"text-white hover:bg-bambu-dark-tertiary"} ${S&&s===x?"bg-bambu-dark-tertiary":""}`,children:[b.icon&&r.jsx("span",{className:"w-4 h-4 flex-shrink-0 flex items-center justify-center",children:b.icon}),r.jsx("span",{className:"flex-1",children:b.label}),S&&r.jsx(Vn,{className:"w-4 h-4 text-bambu-gray"})]}),S&&s===x&&r.jsx(D7e,{items:b.submenu,searchPlaceholder:b.submenuSearchPlaceholder,onClose:n,className:`absolute min-w-[200px] bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl py-1 overflow-hidden max-h-[300px] overflow-y-auto z-[60] ${u?"right-full mr-1":"left-full ml-1"} ${p[x]==="bottom"?"bottom-0":"top-0"}`,onMouseEnter:()=>{l.current&&(clearTimeout(l.current),l.current=null)},onMouseLeave:()=>v()})]},x)})})}function F7e({selectedIds:t,existingTags:e,onClose:a}){const n=na(),{showToast:i}=oa(),[s,o]=y.useState(""),[l,c]=y.useState(new Set),[d,u]=y.useState("add");y.useEffect(()=>{const v=b=>{b.key==="Escape"&&a()};return window.addEventListener("keydown",v),()=>window.removeEventListener("keydown",v)},[a]);const m=at({mutationFn:async()=>{const v=Array.from(l);let b=0;for(const x of t)try{const S=await ne.getArchive(x),k=S.tags?S.tags.split(",").map(N=>N.trim()).filter(Boolean):[];let C;d==="add"?C=[...new Set([...k,...v])]:C=k.filter(N=>!l.has(N)),await ne.updateArchive(x,{tags:C.join(", ")}),b++}catch(S){throw console.error(`Failed to update archive ${x}:`,S),new Error(`Failed on archive ${x}: ${S instanceof Error?S.message:"Unknown error"}`)}return{count:b,mode:d,tags:v}},onSuccess:({count:v,mode:b,tags:x})=>{n.invalidateQueries({queryKey:["archives"]}),i(`${b==="add"?"Added":"Removed"} ${x.length} tag${x.length!==1?"s":""} ${b==="add"?"to":"from"} ${v} archive${v!==1?"s":""}`),a()},onError:v=>{i(v.message||"Failed to update tags","error")}}),p=v=>{c(b=>{const x=new Set(b);return x.has(v)?x.delete(v):x.add(v),x})},f=()=>{s.trim()&&!l.has(s.trim())&&(c(v=>new Set([...v,s.trim()])),o(""))},g=v=>{v.key==="Enter"&&(v.preventDefault(),f())};return r.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:r.jsx(Tt,{className:"w-full max-w-md",children:r.jsxs(jt,{className:"p-0",children:[r.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(Xm,{className:"w-5 h-5 text-bambu-green"}),r.jsx("h2",{className:"text-xl font-semibold text-white",children:d==="add"?"Add Tags":"Remove Tags"})]}),r.jsx("button",{onClick:a,className:"text-bambu-gray hover:text-white transition-colors",children:r.jsx(Ht,{className:"w-5 h-5"})})]}),r.jsxs("div",{className:"p-4 space-y-4",children:[r.jsxs("p",{className:"text-sm text-bambu-gray",children:[d==="add"?"Add":"Remove"," tags for ",t.length," selected archive",t.length!==1?"s":""]}),r.jsxs("div",{className:"flex gap-2",children:[r.jsx(Le,{size:"sm",variant:d==="add"?"primary":"secondary",onClick:()=>u("add"),children:"Add Tags"}),r.jsx(Le,{size:"sm",variant:d==="remove"?"primary":"secondary",onClick:()=>u("remove"),children:"Remove Tags"})]}),d==="add"&&r.jsxs("div",{className:"flex gap-2",children:[r.jsx("input",{type:"text",placeholder:"Enter new tag...",className:"flex-1 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",value:s,onChange:v=>o(v.target.value),onKeyDown:g}),r.jsx(Le,{size:"sm",variant:"secondary",onClick:f,disabled:!s.trim(),children:r.jsx(or,{className:"w-4 h-4"})})]}),e.length>0&&r.jsxs("div",{children:[r.jsx("p",{className:"text-xs text-bambu-gray mb-2",children:"Existing tags:"}),r.jsx("div",{className:"flex flex-wrap gap-2",children:e.map(v=>r.jsx("button",{onClick:()=>p(v),className:`px-2 py-1 rounded text-sm transition-colors ${l.has(v)?"bg-bambu-green text-white":"bg-bambu-dark-tertiary text-bambu-gray-light hover:bg-bambu-dark"}`,children:v},v))})]}),l.size>0&&r.jsxs("div",{children:[r.jsxs("p",{className:"text-xs text-bambu-gray mb-2",children:["Tags to ",d==="add"?"add":"remove",":"]}),r.jsx("div",{className:"flex flex-wrap gap-2",children:Array.from(l).map(v=>r.jsxs("span",{className:`px-2 py-1 rounded text-sm flex items-center gap-1 ${d==="add"?"bg-green-500/20 text-green-400":"bg-red-500/20 text-red-400"}`,children:[v,r.jsx("button",{onClick:()=>p(v),className:"hover:opacity-70",children:r.jsx(Ht,{className:"w-3 h-3"})})]},v))})]})]}),r.jsxs("div",{className:"flex gap-3 p-4 border-t border-bambu-dark-tertiary",children:[r.jsx(Le,{variant:"secondary",onClick:a,className:"flex-1",children:"Cancel"}),r.jsx(Le,{onClick:()=>m.mutate(),disabled:l.size===0||m.isPending,className:"flex-1",children:m.isPending?r.jsxs(r.Fragment,{children:[r.jsx(lt,{className:"w-4 h-4 animate-spin"}),"Processing..."]}):r.jsxs(r.Fragment,{children:[r.jsx(Xm,{className:"w-4 h-4"}),d==="add"?"Add Tags":"Remove Tags"]})})]})]})})})}function L7e({selectedIds:t,onClose:e}){const{t:a}=wt(),n=na(),{showToast:i}=oa(),[s,o]=y.useState(""),{data:l,isLoading:c}=$e({queryKey:["projects"],queryFn:()=>ne.getProjects()}),d=y.useMemo(()=>l?[...l].sort((x,S)=>x.name.localeCompare(S.name)):void 0,[l]),u=s.trim().toLowerCase(),m=u?d?.filter(x=>x.name.toLowerCase().includes(u)):d,p=(d?.length??0)>5;y.useEffect(()=>{const x=S=>{S.key==="Escape"&&e()};return window.addEventListener("keydown",x),()=>window.removeEventListener("keydown",x)},[e]);const f=()=>{n.invalidateQueries({queryKey:["archives"]}),n.invalidateQueries({queryKey:["projects"]}),n.invalidateQueries({queryKey:["project"]}),n.invalidateQueries({queryKey:["project-archives"]})},g=at({mutationFn:async x=>(await ne.addArchivesToProject(x,t),x),onSuccess:x=>{const S=l?.find(k=>k.id===x);f(),i(`Added ${t.length} archive${t.length!==1?"s":""} to "${S?.name}"`),e()},onError:()=>{i("Failed to assign project","error")}}),v=at({mutationFn:async()=>{for(const x of t)await ne.updateArchive(x,{project_id:null});return t.length},onSuccess:x=>{f(),i(`Removed ${x} archive${x!==1?"s":""} from project`),e()},onError:()=>{i("Failed to remove from project","error")}}),b=g.isPending||v.isPending;return r.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:r.jsx(Tt,{className:"w-full max-w-md max-h-[80vh] flex flex-col",children:r.jsxs(jt,{className:"p-0 flex flex-col min-h-0",children:[r.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary shrink-0",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(no,{className:"w-5 h-5 text-bambu-green"}),r.jsx("h2",{className:"text-xl font-semibold text-white",children:"Assign to Project"})]}),r.jsx("button",{onClick:e,className:"text-bambu-gray hover:text-white transition-colors",disabled:b,children:r.jsx(Ht,{className:"w-5 h-5"})})]}),r.jsxs("div",{className:"p-4 space-y-3 overflow-y-auto min-h-0",children:[r.jsxs("p",{className:"text-sm text-bambu-gray",children:["Assign ",t.length," selected archive",t.length!==1?"s":""," to a project"]}),c?r.jsx("div",{className:"flex items-center justify-center py-8",children:r.jsx(lt,{className:"w-6 h-6 animate-spin text-bambu-gray"})}):r.jsxs("div",{className:"space-y-2",children:[r.jsxs("button",{onClick:()=>v.mutate(),disabled:b,className:"w-full flex items-center gap-3 p-3 rounded-lg bg-bambu-dark hover:bg-bambu-dark-tertiary border border-bambu-dark-tertiary transition-colors text-left disabled:opacity-50",children:[r.jsx("div",{className:"w-8 h-8 rounded-full bg-red-500/20 flex items-center justify-center shrink-0",children:r.jsx(Fr,{className:"w-4 h-4 text-red-400"})}),r.jsxs("div",{className:"min-w-0 flex-1",children:[r.jsx("p",{className:"text-white font-medium",children:"Remove from project"}),r.jsx("p",{className:"text-sm text-bambu-gray truncate",children:"Clear project assignment"})]}),v.isPending&&r.jsx(lt,{className:"w-4 h-4 animate-spin text-bambu-gray shrink-0"})]}),d&&d.length>0&&r.jsxs("div",{className:"flex items-center gap-2 py-2",children:[r.jsx("div",{className:"flex-1 h-px bg-bambu-dark-tertiary"}),r.jsx("span",{className:"text-xs text-bambu-gray",children:"or assign to"}),r.jsx("div",{className:"flex-1 h-px bg-bambu-dark-tertiary"})]}),p&&r.jsxs("div",{className:"relative",children:[r.jsx(br,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"}),r.jsx("input",{type:"text",value:s,onChange:x=>o(x.target.value),placeholder:a("archives.menu.searchProjects"),className:"w-full pl-9 pr-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray text-sm focus:border-bambu-green focus:outline-none"})]}),m?.map(x=>r.jsxs("button",{onClick:()=>g.mutate(x.id),disabled:b,className:"w-full flex items-center gap-3 p-3 rounded-lg bg-bambu-dark hover:bg-bambu-dark-tertiary border border-bambu-dark-tertiary transition-colors text-left disabled:opacity-50",children:[r.jsx("div",{className:"w-8 h-8 rounded-full flex items-center justify-center shrink-0",style:{backgroundColor:x.color?`${x.color}20`:"rgb(var(--bambu-green) / 0.2)"},children:r.jsx(no,{className:"w-4 h-4",style:{color:x.color||"rgb(var(--bambu-green))"}})}),r.jsxs("div",{className:"min-w-0 flex-1",children:[r.jsx("p",{className:"text-white font-medium truncate",children:x.name}),r.jsxs("p",{className:"text-sm text-bambu-gray truncate",children:[x.archive_count," archive",x.archive_count!==1?"s":"",x.status&&` • ${x.status}`]})]}),g.isPending&&g.variables===x.id&&r.jsx(lt,{className:"w-4 h-4 animate-spin text-bambu-gray shrink-0"})]},x.id)),(!d||d.length===0)&&r.jsx("p",{className:"text-center text-bambu-gray py-4",children:"No projects yet. Create one from the Projects page."}),d&&d.length>0&&m?.length===0&&r.jsx("p",{className:"text-center text-bambu-gray text-sm py-4",children:"—"})]})]}),r.jsx("div",{className:"flex gap-3 p-4 border-t border-bambu-dark-tertiary shrink-0",children:r.jsx(Le,{variant:"secondary",onClick:e,className:"flex-1",disabled:b,children:"Cancel"})})]})})})}function R7e(t,e){return new Date(t,e+1,0).getDate()}function z7e(t,e){return new Date(t,e,1).getDay()}const I7e=["January","February","March","April","May","June","July","August","September","October","November","December"],O7e=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];function B7e({archives:t,onArchiveClick:e,highlightedArchiveId:a}){const n=new Date,[i,s]=y.useState(n.getMonth()),[o,l]=y.useState(n.getFullYear()),[c,d]=y.useState(null),[u,m]=y.useState(null),p=y.useMemo(()=>{const N=new Map;return t.forEach(T=>{const j=Ga(T.completed_at||T.created_at)||new Date,D=`${j.getFullYear()}-${String(j.getMonth()+1).padStart(2,"0")}-${String(j.getDate()).padStart(2,"0")}`,P=N.get(D)||[];P.push(T),N.set(D,P)}),N},[t]),f=R7e(o,i),g=z7e(o,i),v=()=>{i===0?(s(11),l(o-1)):s(i-1)},b=()=>{i===11?(s(0),l(o+1)):s(i+1)},x=()=>{s(n.getMonth()),l(n.getFullYear())},S=[];for(let N=0;N{N!==c&&m(null),d(N)};return r.jsxs("div",{className:"flex flex-col lg:flex-row gap-6",children:[r.jsxs("div",{className:"flex-1",children:[r.jsxs("div",{className:"flex items-center justify-between mb-4",children:[r.jsx("button",{onClick:v,className:"p-2 hover:bg-bambu-dark-tertiary rounded-lg transition-colors",children:r.jsx(Jo,{className:"w-5 h-5 text-bambu-gray"})}),r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsxs("h2",{className:"text-lg font-semibold text-white",children:[I7e[i]," ",o]}),r.jsx("button",{onClick:x,className:"px-2 py-1 text-xs bg-bambu-dark-tertiary hover:bg-bambu-green/20 text-bambu-gray hover:text-white rounded transition-colors",children:"Today"})]}),r.jsx("button",{onClick:b,className:"p-2 hover:bg-bambu-dark-tertiary rounded-lg transition-colors",children:r.jsx(Vn,{className:"w-5 h-5 text-bambu-gray"})})]}),r.jsx("div",{className:"grid grid-cols-7 gap-1 mb-1",children:O7e.map(N=>r.jsx("div",{className:"text-center text-xs text-bambu-gray py-2",children:N},N))}),r.jsx("div",{className:"grid grid-cols-7 gap-1",children:S.map((N,T)=>{if(N===null)return r.jsx("div",{className:"aspect-square"},`empty-${T}`);const j=`${o}-${String(i+1).padStart(2,"0")}-${String(N).padStart(2,"0")}`,D=p.get(j)||[],P=D.length>0,E=N===n.getDate()&&i===n.getMonth()&&o===n.getFullYear(),z=j===c,I=D.filter(R=>R.status==="completed").length,B=D.filter(R=>R.status==="failed").length;return r.jsxs("button",{onClick:()=>C(z?null:j),className:`aspect-square rounded-lg p-1 flex flex-col items-center justify-center transition-colors relative ${z?"bg-bambu-green text-white":E?"bg-bambu-green/20 text-white ring-2 ring-bambu-green":P?"bg-bambu-dark-tertiary hover:bg-bambu-dark-tertiary/70 text-white":"hover:bg-bambu-dark-tertiary/50 text-bambu-gray"}`,children:[r.jsx("span",{className:`text-sm font-medium ${E&&!z?"text-bambu-green":""}`,children:N}),P&&r.jsxs("div",{className:"absolute bottom-1 left-1/2 -translate-x-1/2 flex items-center gap-1",children:[r.jsx("div",{className:`w-2 h-2 rounded-full ${B>0&&I===0?"bg-red-400":B>0?"bg-yellow-400":"bg-green-400"}`}),r.jsx("span",{className:"text-xs font-medium",children:D.length})]})]},N)})}),r.jsx("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary",children:r.jsxs("div",{className:"grid grid-cols-3 gap-4 text-center",children:[r.jsxs("div",{children:[r.jsx("div",{className:"text-2xl font-bold text-white",children:t.filter(N=>{const T=Ga(N.completed_at||N.created_at)||new Date;return T.getMonth()===i&&T.getFullYear()===o}).length}),r.jsx("div",{className:"text-xs text-bambu-gray",children:"Prints this month"})]}),r.jsxs("div",{children:[r.jsx("div",{className:"text-2xl font-bold text-green-400",children:t.filter(N=>{const T=Ga(N.completed_at||N.created_at)||new Date;return T.getMonth()===i&&T.getFullYear()===o&&N.status==="completed"}).length}),r.jsx("div",{className:"text-xs text-bambu-gray",children:"Successful"})]}),r.jsxs("div",{children:[r.jsx("div",{className:"text-2xl font-bold text-red-400",children:t.filter(N=>{const T=Ga(N.completed_at||N.created_at)||new Date;return T.getMonth()===i&&T.getFullYear()===o&&N.status==="failed"}).length}),r.jsx("div",{className:"text-xs text-bambu-gray",children:"Failed"})]})]})})]}),r.jsx("div",{className:"lg:w-80 bg-bambu-dark rounded-xl p-4",children:c?r.jsxs(r.Fragment,{children:[r.jsx("h3",{className:"text-sm font-medium text-bambu-gray mb-3",children:new Date(c+"T12:00:00").toLocaleDateString("en-US",{weekday:"long",month:"long",day:"numeric",year:"numeric"})}),k.length>0?r.jsx("div",{className:"calendar-scroll space-y-2 max-h-96 overflow-y-auto",children:k.map(N=>{const T=N.id===u||N.id===a;return r.jsxs("button",{onClick:()=>{m(N.id),e?.(N)},className:`w-full flex items-center gap-3 p-2 rounded-lg transition-colors text-left ${T?"":"hover:bg-bambu-dark-tertiary"}`,style:T?{outline:"4px solid #facc15",outlineOffset:"2px"}:void 0,children:[N.thumbnail_path?r.jsx("img",{src:ne.getArchiveThumbnail(N.id),alt:"",className:"w-12 h-12 rounded object-cover"}):r.jsx("div",{className:"w-12 h-12 rounded bg-bambu-dark-tertiary flex items-center justify-center",children:r.jsx("span",{className:"text-xs text-bambu-gray",children:"3MF"})}),r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsx("p",{className:"text-sm text-white truncate",children:N.print_name||N.filename}),r.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[r.jsx("span",{className:N.status==="failed"?"text-red-400":"text-green-400",children:N.status==="failed"?"Failed":"Completed"}),N.filament_color&&r.jsx("div",{className:"flex gap-0.5",children:N.filament_color.split(",").map((j,D)=>r.jsx("div",{className:"w-3 h-3 rounded-full border border-black/20",style:{backgroundColor:j}},D))})]})]})]},N.id)})}):r.jsx("p",{className:"text-sm text-bambu-gray",children:"No prints on this day"})]}):r.jsx("div",{className:"text-center py-8",children:r.jsx("p",{className:"text-sm text-bambu-gray",children:"Select a day to see prints"})})})]})}function Wse({archiveId:t,archiveName:e,onClose:a}){const n=ne.getArchiveQRCodeUrl(t,300);y.useEffect(()=>{const s=o=>{o.key==="Escape"&&a()};return window.addEventListener("keydown",s),()=>window.removeEventListener("keydown",s)},[a]);const i=()=>{const s=document.createElement("a");s.href=n,s.download=`${e}_qrcode.png`,s.click()};return r.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:a,children:r.jsxs("div",{className:"bg-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary w-full max-w-sm",onClick:s=>s.stopPropagation(),children:[r.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary",children:[r.jsx("h2",{className:"text-lg font-semibold text-white",children:"QR Code"}),r.jsx("button",{onClick:a,className:"text-bambu-gray hover:text-white transition-colors",children:r.jsx(Ht,{className:"w-5 h-5"})})]}),r.jsxs("div",{className:"p-6 flex flex-col items-center",children:[r.jsx("p",{className:"text-sm text-bambu-gray mb-4 text-center truncate max-w-full",children:e}),r.jsx("div",{className:"bg-white p-4 rounded-lg mb-4",children:r.jsx("img",{src:n,alt:"QR Code",className:"w-64 h-64"})}),r.jsx("p",{className:"text-xs text-bambu-gray mb-4 text-center",children:"Scan to open this archive"}),r.jsxs(Le,{onClick:i,className:"w-full",children:[r.jsx(Ur,{className:"w-4 h-4"}),"Download QR Code"]})]})]})})}function Kse({archiveId:t,archiveName:e,photos:a,onClose:n,onDelete:i}){const[s,o]=y.useState(0),[l,c]=y.useState(!1);if(y.useEffect(()=>{const f=g=>{g.key==="Escape"&&n(),g.key==="ArrowLeft"&&o(v=>Math.max(0,v-1)),g.key==="ArrowRight"&&o(v=>Math.min(a.length-1,v+1))};return window.addEventListener("keydown",f),()=>window.removeEventListener("keydown",f)},[n,a.length]),y.useEffect(()=>{s>=a.length&&o(Math.max(0,a.length-1))},[a.length,s]),a.length===0)return n(),null;const d=a[s],u=ne.getArchivePhotoUrl(t,d),m=()=>{const f=document.createElement("a");f.href=u,f.download=`${e}_photo_${s+1}.jpg`,f.click()},p=()=>{i&&c(!0)};return r.jsxs("div",{className:"fixed inset-0 bg-black/90 flex items-center justify-center z-50",onClick:n,children:[r.jsxs("div",{className:"relative w-full h-full flex flex-col",onClick:f=>f.stopPropagation(),children:[r.jsxs("div",{className:"flex items-center justify-between px-6 py-4 bg-black/50",children:[r.jsxs("div",{children:[r.jsx("h2",{className:"text-lg font-semibold text-white",children:e}),r.jsxs("p",{className:"text-sm text-bambu-gray",children:["Photo ",s+1," of ",a.length]})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsxs(Le,{variant:"secondary",size:"sm",onClick:m,children:[r.jsx(Ur,{className:"w-4 h-4"}),"Download"]}),i&&r.jsx(Le,{variant:"secondary",size:"sm",onClick:p,className:"text-red-400 hover:text-red-300",children:r.jsx(ra,{className:"w-4 h-4"})}),r.jsx("button",{onClick:n,className:"p-2 text-bambu-gray hover:text-white transition-colors",children:r.jsx(Ht,{className:"w-6 h-6"})})]})]}),r.jsxs("div",{className:"flex-1 min-h-0 flex items-center justify-center p-4 relative overflow-hidden",children:[s>0&&r.jsx("button",{onClick:()=>o(f=>f-1),className:"absolute left-4 z-10 p-3 bg-black/50 hover:bg-black/70 rounded-full transition-colors",children:r.jsx(Jo,{className:"w-8 h-8 text-white"})}),r.jsx("img",{src:u,alt:`Photo ${s+1}`,className:"max-w-full max-h-full object-contain rounded-lg",style:{maxHeight:"calc(100vh - 200px)"}}),so(f=>f+1),className:"absolute right-4 z-10 p-3 bg-black/50 hover:bg-black/70 rounded-full transition-colors",children:r.jsx(Vn,{className:"w-8 h-8 text-white"})})]}),a.length>1&&r.jsx("div",{className:"flex justify-center gap-2 p-4 bg-black/50",children:a.map((f,g)=>r.jsx("button",{onClick:()=>o(g),className:`w-16 h-16 rounded-lg overflow-hidden border-2 transition-colors ${g===s?"border-bambu-green":"border-transparent hover:border-bambu-gray"}`,children:r.jsx("img",{src:ne.getArchivePhotoUrl(t,f),alt:`Thumbnail ${g+1}`,className:"w-full h-full object-cover"})},f))})]}),l&&r.jsx(ka,{title:"Delete Photo",message:"Delete this photo? This cannot be undone.",confirmText:"Delete",variant:"danger",onConfirm:()=>{i?.(d),c(!1)},onCancel:()=>c(!1)})]})}const{entries:Yse,setPrototypeOf:jY,isFrozen:U7e,getPrototypeOf:H7e,getOwnPropertyDescriptor:q7e}=Object;let{freeze:Co,seal:Rc,create:Q0}=Object,{apply:Tz,construct:Az}=typeof Reflect<"u"&&Reflect;Co||(Co=function(e){return e});Rc||(Rc=function(e){return e});Tz||(Tz=function(e,a){for(var n=arguments.length,i=new Array(n>2?n-2:0),s=2;s1?a-1:0),i=1;i1?a-1:0),i=1;i2&&arguments[2]!==void 0?arguments[2]:KC;jY&&jY(t,null);let n=e.length;for(;n--;){let i=e[n];if(typeof i=="string"){const s=a(i);s!==i&&(U7e(e)||(e[n]=s),i=s)}t[i]=!0}return t}function Y7e(t){for(let e=0;e/gm),eKe=Rc(/\$\{[\w\W]*/gm),tKe=Rc(/^data-[\-\w.\u00B7-\uFFFF]+$/),aKe=Rc(/^aria-[\-\w]+$/),Qse=Rc(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),rKe=Rc(/^(?:\w+script|data):/i),nKe=Rc(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),Xse=Rc(/^html$/i),iKe=Rc(/^[a-z][.\w]*(-[.\w]+)+$/i);var RY=Object.freeze({__proto__:null,ARIA_ATTR:aKe,ATTR_WHITESPACE:nKe,CUSTOM_ELEMENT:iKe,DATA_ATTR:tKe,DOCTYPE_NAME:Xse,ERB_EXPR:J7e,IS_ALLOWED_URI:Qse,IS_SCRIPT_OR_DATA:rKe,MUSTACHE_EXPR:Z7e,TMPLIT_EXPR:eKe});const R0={element:1,text:3,progressingInstruction:7,comment:8,document:9},sKe=function(){return typeof window>"u"?null:window},oKe=function(e,a){if(typeof e!="object"||typeof e.createPolicy!="function")return null;let n=null;const i="data-tt-policy-suffix";a&&a.hasAttribute(i)&&(n=a.getAttribute(i));const s="dompurify"+(n?"#"+n:"");try{return e.createPolicy(s,{createHTML(o){return o},createScriptURL(o){return o}})}catch{return console.warn("TrustedTypes policy "+s+" could not be created."),null}},zY=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}};function Zse(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:sKe();const e=Ae=>Zse(Ae);if(e.version="3.4.0",e.removed=[],!t||!t.document||t.document.nodeType!==R0.document||!t.Element)return e.isSupported=!1,e;let{document:a}=t;const n=a,i=n.currentScript,{DocumentFragment:s,HTMLTemplateElement:o,Node:l,Element:c,NodeFilter:d,NamedNodeMap:u=t.NamedNodeMap||t.MozNamedAttrMap,HTMLFormElement:m,DOMParser:p,trustedTypes:f}=t,g=c.prototype,v=L0(g,"cloneNode"),b=L0(g,"remove"),x=L0(g,"nextSibling"),S=L0(g,"childNodes"),k=L0(g,"parentNode");if(typeof o=="function"){const Ae=a.createElement("template");Ae.content&&Ae.content.ownerDocument&&(a=Ae.content.ownerDocument)}let C,N="";const{implementation:T,createNodeIterator:j,createDocumentFragment:D,getElementsByTagName:P}=a,{importNode:E}=n;let z=zY();e.isSupported=typeof Yse=="function"&&typeof k=="function"&&T&&T.createHTMLDocument!==void 0;const{MUSTACHE_EXPR:I,ERB_EXPR:B,TMPLIT_EXPR:R,DATA_ATTR:K,ARIA_ATTR:J,IS_SCRIPT_OR_DATA:X,ATTR_WHITESPACE:ce,CUSTOM_ELEMENT:de}=RY;let{IS_ALLOWED_URI:oe}=RY,Y=null;const ie=Sr({},[...EY,...UF,...HF,...qF,...DY]);let me=null;const he=Sr({},[...FY,...VF,...LY,...rC]);let xe=Object.seal(Q0(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),V=null,Q=null;const A=Object.seal(Q0(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}}));let F=!0,U=!0,$=!1,H=!0,le=!1,O=!0,q=!1,Z=!1,ee=!1,re=!1,se=!1,fe=!1,ue=!0,pe=!1;const G="user-content-";let L=!0,ae=!1,ge={},be=null;const ve=Sr({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","style","svg","template","thead","title","video","xmp"]);let De=null;const je=Sr({},["audio","video","img","source","image","track"]);let Te=null;const qe=Sr({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),Ce="http://www.w3.org/1998/Math/MathML",Ie="http://www.w3.org/2000/svg",Re="http://www.w3.org/1999/xhtml";let Ue=Re,ze=!1,nt=null;const Oe=Sr({},[Ce,Ie,Re],OF);let tt=Sr({},["mi","mo","mn","ms","mtext"]),Fe=Sr({},["annotation-xml"]);const Ke=Sr({},["title","style","font","a","script"]);let Ve=null;const Me=["application/xhtml+xml","text/html"],Be="text/html";let Qe=null,Ge=null;const Ee=a.createElement("form"),rt=function(Se){return Se instanceof RegExp||Se instanceof Function},Xe=function(){let Se=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!(Ge&&Ge===Se)){if((!Se||typeof Se!="object")&&(Se={}),Se=Kd(Se),Ve=Me.indexOf(Se.PARSER_MEDIA_TYPE)===-1?Be:Se.PARSER_MEDIA_TYPE,Qe=Ve==="application/xhtml+xml"?OF:KC,Y=rd(Se,"ALLOWED_TAGS")?Sr({},Se.ALLOWED_TAGS,Qe):ie,me=rd(Se,"ALLOWED_ATTR")?Sr({},Se.ALLOWED_ATTR,Qe):he,nt=rd(Se,"ALLOWED_NAMESPACES")?Sr({},Se.ALLOWED_NAMESPACES,OF):Oe,Te=rd(Se,"ADD_URI_SAFE_ATTR")?Sr(Kd(qe),Se.ADD_URI_SAFE_ATTR,Qe):qe,De=rd(Se,"ADD_DATA_URI_TAGS")?Sr(Kd(je),Se.ADD_DATA_URI_TAGS,Qe):je,be=rd(Se,"FORBID_CONTENTS")?Sr({},Se.FORBID_CONTENTS,Qe):ve,V=rd(Se,"FORBID_TAGS")?Sr({},Se.FORBID_TAGS,Qe):Kd({}),Q=rd(Se,"FORBID_ATTR")?Sr({},Se.FORBID_ATTR,Qe):Kd({}),ge=rd(Se,"USE_PROFILES")?Se.USE_PROFILES:!1,F=Se.ALLOW_ARIA_ATTR!==!1,U=Se.ALLOW_DATA_ATTR!==!1,$=Se.ALLOW_UNKNOWN_PROTOCOLS||!1,H=Se.ALLOW_SELF_CLOSE_IN_ATTR!==!1,le=Se.SAFE_FOR_TEMPLATES||!1,O=Se.SAFE_FOR_XML!==!1,q=Se.WHOLE_DOCUMENT||!1,re=Se.RETURN_DOM||!1,se=Se.RETURN_DOM_FRAGMENT||!1,fe=Se.RETURN_TRUSTED_TYPE||!1,ee=Se.FORCE_BODY||!1,ue=Se.SANITIZE_DOM!==!1,pe=Se.SANITIZE_NAMED_PROPS||!1,L=Se.KEEP_CONTENT!==!1,ae=Se.IN_PLACE||!1,oe=Se.ALLOWED_URI_REGEXP||Qse,Ue=Se.NAMESPACE||Re,tt=Se.MATHML_TEXT_INTEGRATION_POINTS||tt,Fe=Se.HTML_INTEGRATION_POINTS||Fe,xe=Se.CUSTOM_ELEMENT_HANDLING||Q0(null),Se.CUSTOM_ELEMENT_HANDLING&&rt(Se.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(xe.tagNameCheck=Se.CUSTOM_ELEMENT_HANDLING.tagNameCheck),Se.CUSTOM_ELEMENT_HANDLING&&rt(Se.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(xe.attributeNameCheck=Se.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),Se.CUSTOM_ELEMENT_HANDLING&&typeof Se.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements=="boolean"&&(xe.allowCustomizedBuiltInElements=Se.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),le&&(U=!1),se&&(re=!0),ge&&(Y=Sr({},DY),me=Q0(null),ge.html===!0&&(Sr(Y,EY),Sr(me,FY)),ge.svg===!0&&(Sr(Y,UF),Sr(me,VF),Sr(me,rC)),ge.svgFilters===!0&&(Sr(Y,HF),Sr(me,VF),Sr(me,rC)),ge.mathMl===!0&&(Sr(Y,qF),Sr(me,LY),Sr(me,rC))),A.tagCheck=null,A.attributeCheck=null,Se.ADD_TAGS&&(typeof Se.ADD_TAGS=="function"?A.tagCheck=Se.ADD_TAGS:(Y===ie&&(Y=Kd(Y)),Sr(Y,Se.ADD_TAGS,Qe))),Se.ADD_ATTR&&(typeof Se.ADD_ATTR=="function"?A.attributeCheck=Se.ADD_ATTR:(me===he&&(me=Kd(me)),Sr(me,Se.ADD_ATTR,Qe))),Se.ADD_URI_SAFE_ATTR&&Sr(Te,Se.ADD_URI_SAFE_ATTR,Qe),Se.FORBID_CONTENTS&&(be===ve&&(be=Kd(be)),Sr(be,Se.FORBID_CONTENTS,Qe)),Se.ADD_FORBID_CONTENTS&&(be===ve&&(be=Kd(be)),Sr(be,Se.ADD_FORBID_CONTENTS,Qe)),L&&(Y["#text"]=!0),q&&Sr(Y,["html","head","body"]),Y.table&&(Sr(Y,["tbody"]),delete V.tbody),Se.TRUSTED_TYPES_POLICY){if(typeof Se.TRUSTED_TYPES_POLICY.createHTML!="function")throw F0('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof Se.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw F0('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');C=Se.TRUSTED_TYPES_POLICY,N=C.createHTML("")}else C===void 0&&(C=oKe(f,i)),C!==null&&typeof N=="string"&&(N=C.createHTML(""));Co&&Co(Se),Ge=Se}},Nt=Sr({},[...UF,...HF,...Q7e]),Vt=Sr({},[...qF,...X7e]),ht=function(Se){let ct=k(Se);(!ct||!ct.tagName)&&(ct={namespaceURI:Ue,tagName:"template"});const Ne=KC(Se.tagName),We=KC(ct.tagName);return nt[Se.namespaceURI]?Se.namespaceURI===Ie?ct.namespaceURI===Re?Ne==="svg":ct.namespaceURI===Ce?Ne==="svg"&&(We==="annotation-xml"||tt[We]):!!Nt[Ne]:Se.namespaceURI===Ce?ct.namespaceURI===Re?Ne==="math":ct.namespaceURI===Ie?Ne==="math"&&Fe[We]:!!Vt[Ne]:Se.namespaceURI===Re?ct.namespaceURI===Ie&&!Fe[We]||ct.namespaceURI===Ce&&!tt[We]?!1:!Vt[Ne]&&(Ke[Ne]||!Nt[Ne]):!!(Ve==="application/xhtml+xml"&&nt[Se.namespaceURI]):!1},It=function(Se){D0(e.removed,{element:Se});try{k(Se).removeChild(Se)}catch{b(Se)}},Xt=function(Se,ct){try{D0(e.removed,{attribute:ct.getAttributeNode(Se),from:ct})}catch{D0(e.removed,{attribute:null,from:ct})}if(ct.removeAttribute(Se),Se==="is")if(re||se)try{It(ct)}catch{}else try{ct.setAttribute(Se,"")}catch{}},la=function(Se){let ct=null,Ne=null;if(ee)Se=""+Se;else{const Je=BF(Se,/^[\r\n\t ]+/);Ne=Je&&Je[0]}Ve==="application/xhtml+xml"&&Ue===Re&&(Se=''+Se+"");const We=C?C.createHTML(Se):Se;if(Ue===Re)try{ct=new p().parseFromString(We,Ve)}catch{}if(!ct||!ct.documentElement){ct=T.createDocument(Ue,"template",null);try{ct.documentElement.innerHTML=ze?N:We}catch{}}const st=ct.body||ct.documentElement;return Se&&Ne&&st.insertBefore(a.createTextNode(Ne),st.childNodes[0]||null),Ue===Re?P.call(ct,q?"html":"body")[0]:q?ct.documentElement:st},ca=function(Se){return j.call(Se.ownerDocument||Se,Se,d.SHOW_ELEMENT|d.SHOW_COMMENT|d.SHOW_TEXT|d.SHOW_PROCESSING_INSTRUCTION|d.SHOW_CDATA_SECTION,null)},ot=function(Se){return Se instanceof m&&(typeof Se.nodeName!="string"||typeof Se.textContent!="string"||typeof Se.removeChild!="function"||!(Se.attributes instanceof u)||typeof Se.removeAttribute!="function"||typeof Se.setAttribute!="function"||typeof Se.namespaceURI!="string"||typeof Se.insertBefore!="function"||typeof Se.hasChildNodes!="function")},vt=function(Se){return typeof l=="function"&&Se instanceof l};function Ct(Ae,Se,ct){E0(Ae,Ne=>{Ne.call(e,Se,ct,Ge)})}const ea=function(Se){let ct=null;if(Ct(z.beforeSanitizeElements,Se,null),ot(Se))return It(Se),!0;const Ne=Qe(Se.nodeName);if(Ct(z.uponSanitizeElement,Se,{tagName:Ne,allowedTags:Y}),O&&Se.hasChildNodes()&&!vt(Se.firstElementChild)&&fo(/<[/\w!]/g,Se.innerHTML)&&fo(/<[/\w!]/g,Se.textContent)||O&&Se.namespaceURI===Re&&Ne==="style"&&vt(Se.firstElementChild)||Se.nodeType===R0.progressingInstruction||O&&Se.nodeType===R0.comment&&fo(/<[/\w]/g,Se.data))return It(Se),!0;if(V[Ne]||!(A.tagCheck instanceof Function&&A.tagCheck(Ne))&&!Y[Ne]){if(!V[Ne]&&Pe(Ne)&&(xe.tagNameCheck instanceof RegExp&&fo(xe.tagNameCheck,Ne)||xe.tagNameCheck instanceof Function&&xe.tagNameCheck(Ne)))return!1;if(L&&!be[Ne]){const We=k(Se)||Se.parentNode,st=S(Se)||Se.childNodes;if(st&&We){const Je=st.length;for(let Ze=Je-1;Ze>=0;--Ze){const kt=v(st[Ze],!0);kt.__removalCount=(Se.__removalCount||0)+1,We.insertBefore(kt,x(Se))}}}return It(Se),!0}return Se instanceof c&&!ht(Se)||(Ne==="noscript"||Ne==="noembed"||Ne==="noframes")&&fo(/<\/no(script|embed|frames)/i,Se.innerHTML)?(It(Se),!0):(le&&Se.nodeType===R0.text&&(ct=Se.textContent,E0([I,B,R],We=>{ct=Bx(ct,We," ")}),Se.textContent!==ct&&(D0(e.removed,{element:Se.cloneNode()}),Se.textContent=ct)),Ct(z.afterSanitizeElements,Se,null),!1)},aa=function(Se,ct,Ne){if(Q[ct]||ue&&(ct==="id"||ct==="name")&&(Ne in a||Ne in Ee))return!1;if(!(U&&!Q[ct]&&fo(K,ct))){if(!(F&&fo(J,ct))){if(!(A.attributeCheck instanceof Function&&A.attributeCheck(ct,Se))){if(!me[ct]||Q[ct]){if(!(Pe(Se)&&(xe.tagNameCheck instanceof RegExp&&fo(xe.tagNameCheck,Se)||xe.tagNameCheck instanceof Function&&xe.tagNameCheck(Se))&&(xe.attributeNameCheck instanceof RegExp&&fo(xe.attributeNameCheck,ct)||xe.attributeNameCheck instanceof Function&&xe.attributeNameCheck(ct,Se))||ct==="is"&&xe.allowCustomizedBuiltInElements&&(xe.tagNameCheck instanceof RegExp&&fo(xe.tagNameCheck,Ne)||xe.tagNameCheck instanceof Function&&xe.tagNameCheck(Ne))))return!1}else if(!Te[ct]){if(!fo(oe,Bx(Ne,ce,""))){if(!((ct==="src"||ct==="xlink:href"||ct==="href")&&Se!=="script"&&$7e(Ne,"data:")===0&&De[Se])){if(!($&&!fo(X,Bx(Ne,ce,"")))){if(Ne)return!1}}}}}}}return!0},Pe=function(Se){return Se!=="annotation-xml"&&BF(Se,de)},Ye=function(Se){Ct(z.beforeSanitizeAttributes,Se,null);const{attributes:ct}=Se;if(!ct||ot(Se))return;const Ne={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:me,forceKeepAttr:void 0};let We=ct.length;for(;We--;){const st=ct[We],{name:Je,namespaceURI:Ze,value:kt}=st,ft=Qe(Je),_t=kt;let St=Je==="value"?_t:W7e(_t);if(Ne.attrName=ft,Ne.attrValue=St,Ne.keepAttr=!0,Ne.forceKeepAttr=void 0,Ct(z.uponSanitizeAttribute,Se,Ne),St=Ne.attrValue,pe&&(ft==="id"||ft==="name")&&(Xt(Je,Se),St=G+St),O&&fo(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,St)){Xt(Je,Se);continue}if(ft==="attributename"&&BF(St,"href")){Xt(Je,Se);continue}if(Ne.forceKeepAttr)continue;if(!Ne.keepAttr){Xt(Je,Se);continue}if(!H&&fo(/\/>/i,St)){Xt(Je,Se);continue}le&&E0([I,B,R],yt=>{St=Bx(St,yt," ")});const qt=Qe(Se.nodeName);if(!aa(qt,ft,St)){Xt(Je,Se);continue}if(C&&typeof f=="object"&&typeof f.getAttributeType=="function"&&!Ze)switch(f.getAttributeType(qt,ft)){case"TrustedHTML":{St=C.createHTML(St);break}case"TrustedScriptURL":{St=C.createScriptURL(St);break}}if(St!==_t)try{Ze?Se.setAttributeNS(Ze,Je,St):Se.setAttribute(Je,St),ot(Se)?It(Se):MY(e.removed)}catch{Xt(Je,Se)}}Ct(z.afterSanitizeAttributes,Se,null)},it=function(Se){let ct=null;const Ne=ca(Se);for(Ct(z.beforeSanitizeShadowDOM,Se,null);ct=Ne.nextNode();)Ct(z.uponSanitizeShadowNode,ct,null),ea(ct),Ye(ct),ct.content instanceof s&&it(ct.content);Ct(z.afterSanitizeShadowDOM,Se,null)};return e.sanitize=function(Ae){let Se=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},ct=null,Ne=null,We=null,st=null;if(ze=!Ae,ze&&(Ae=""),typeof Ae!="string"&&!vt(Ae))if(typeof Ae.toString=="function"){if(Ae=Ae.toString(),typeof Ae!="string")throw F0("dirty is not a string, aborting")}else throw F0("toString is not a function");if(!e.isSupported)return Ae;if(Z||Xe(Se),e.removed=[],typeof Ae=="string"&&(ae=!1),ae){if(Ae.nodeName){const kt=Qe(Ae.nodeName);if(!Y[kt]||V[kt])throw F0("root node is forbidden and cannot be sanitized in-place")}}else if(Ae instanceof l)ct=la(""),Ne=ct.ownerDocument.importNode(Ae,!0),Ne.nodeType===R0.element&&Ne.nodeName==="BODY"||Ne.nodeName==="HTML"?ct=Ne:ct.appendChild(Ne);else{if(!re&&!le&&!q&&Ae.indexOf("<")===-1)return C&&fe?C.createHTML(Ae):Ae;if(ct=la(Ae),!ct)return re?null:fe?N:""}ct&&ee&&It(ct.firstChild);const Je=ca(ae?Ae:ct);for(;We=Je.nextNode();)ea(We),Ye(We),We.content instanceof s&&it(We.content);if(ae)return Ae;if(re){if(le){ct.normalize();let kt=ct.innerHTML;E0([I,B,R],ft=>{kt=Bx(kt,ft," ")}),ct.innerHTML=kt}if(se)for(st=D.call(ct.ownerDocument);ct.firstChild;)st.appendChild(ct.firstChild);else st=ct;return(me.shadowroot||me.shadowrootmode)&&(st=E.call(n,st,!0)),st}let Ze=q?ct.outerHTML:ct.innerHTML;return q&&Y["!doctype"]&&ct.ownerDocument&&ct.ownerDocument.doctype&&ct.ownerDocument.doctype.name&&fo(Xse,ct.ownerDocument.doctype.name)&&(Ze=" `+Ze),le&&E0([I,B,R],kt=>{Ze=Bx(Ze,kt," ")}),C&&fe?C.createHTML(Ze):Ze},e.setConfig=function(){let Ae=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};Xe(Ae),Z=!0},e.clearConfig=function(){Ge=null,Z=!1},e.isValidAttribute=function(Ae,Se,ct){Ge||Xe({});const Ne=Qe(Ae),We=Qe(Se);return aa(Ne,We,ct)},e.addHook=function(Ae,Se){typeof Se=="function"&&D0(z[Ae],Se)},e.removeHook=function(Ae,Se){if(Se!==void 0){const ct=V7e(z[Ae],Se);return ct===-1?void 0:G7e(z[Ae],ct,1)[0]}return MY(z[Ae])},e.removeHooks=function(Ae){z[Ae]=[]},e.removeAllHooks=function(){z=zY()},e}var DB=Zse();function Ms(t){this.content=t}Ms.prototype={constructor:Ms,find:function(t){for(var e=0;e>1}};Ms.from=function(t){if(t instanceof Ms)return t;var e=[];if(t)for(var a in t)e.push(a,t[a]);return new Ms(e)};function Jse(t,e,a){for(let n=0;;n++){if(n==t.childCount||n==e.childCount)return t.childCount==e.childCount?null:a;let i=t.child(n),s=e.child(n);if(i==s){a+=i.nodeSize;continue}if(!i.sameMarkup(s))return a;if(i.isText&&i.text!=s.text){for(let o=0;i.text[o]==s.text[o];o++)a++;return a}if(i.content.size||s.content.size){let o=Jse(i.content,s.content,a+1);if(o!=null)return o}a+=i.nodeSize}}function eoe(t,e,a,n){for(let i=t.childCount,s=e.childCount;;){if(i==0||s==0)return i==s?null:{a,b:n};let o=t.child(--i),l=e.child(--s),c=o.nodeSize;if(o==l){a-=c,n-=c;continue}if(!o.sameMarkup(l))return{a,b:n};if(o.isText&&o.text!=l.text){let d=0,u=Math.min(o.text.length,l.text.length);for(;de&&n(c,i+l,s||null,o)!==!1&&c.content.size){let u=l+1;c.nodesBetween(Math.max(0,e-u),Math.min(c.content.size,a-u),n,i+u)}l=d}}descendants(e){this.nodesBetween(0,this.size,e)}textBetween(e,a,n,i){let s="",o=!0;return this.nodesBetween(e,a,(l,c)=>{let d=l.isText?l.text.slice(Math.max(e,c)-c,a-c):l.isLeaf?i?typeof i=="function"?i(l):i:l.type.spec.leafText?l.type.spec.leafText(l):"":"";l.isBlock&&(l.isLeaf&&d||l.isTextblock)&&n&&(o?o=!1:s+=n),s+=d},0),s}append(e){if(!e.size)return this;if(!this.size)return e;let a=this.lastChild,n=e.firstChild,i=this.content.slice(),s=0;for(a.isText&&a.sameMarkup(n)&&(i[i.length-1]=a.withText(a.text+n.text),s=1);se)for(let s=0,o=0;oe&&((oa)&&(l.isText?l=l.cut(Math.max(0,e-o),Math.min(l.text.length,a-o)):l=l.cut(Math.max(0,e-o-1),Math.min(l.content.size,a-o-1))),n.push(l),i+=l.nodeSize),o=c}return new Qt(n,i)}cutByIndex(e,a){return e==a?Qt.empty:e==0&&a==this.content.length?this:new Qt(this.content.slice(e,a))}replaceChild(e,a){let n=this.content[e];if(n==a)return this;let i=this.content.slice(),s=this.size+a.nodeSize-n.nodeSize;return i[e]=a,new Qt(i,s)}addToStart(e){return new Qt([e].concat(this.content),this.size+e.nodeSize)}addToEnd(e){return new Qt(this.content.concat(e),this.size+e.nodeSize)}eq(e){if(this.content.length!=e.content.length)return!1;for(let a=0;athis.size||e<0)throw new RangeError(`Position ${e} outside of fragment (${this})`);for(let a=0,n=0;;a++){let i=this.child(a),s=n+i.nodeSize;if(s>=e)return s==e?nC(a+1,s):nC(a,n);n=s}}toString(){return"<"+this.toStringInner()+">"}toStringInner(){return this.content.join(", ")}toJSON(){return this.content.length?this.content.map(e=>e.toJSON()):null}static fromJSON(e,a){if(!a)return Qt.empty;if(!Array.isArray(a))throw new RangeError("Invalid input for Fragment.fromJSON");return new Qt(a.map(e.nodeFromJSON))}static fromArray(e){if(!e.length)return Qt.empty;let a,n=0;for(let i=0;ithis.type.rank&&(a||(a=e.slice(0,i)),a.push(this),n=!0),a&&a.push(s)}}return a||(a=e.slice()),n||a.push(this),a}removeFromSet(e){for(let a=0;an.type.rank-i.type.rank),a}};vn.none=[];class DT extends Error{}class va{constructor(e,a,n){this.content=e,this.openStart=a,this.openEnd=n}get size(){return this.content.size-this.openStart-this.openEnd}insertAt(e,a){let n=aoe(this.content,e+this.openStart,a);return n&&new va(n,this.openStart,this.openEnd)}removeBetween(e,a){return new va(toe(this.content,e+this.openStart,a+this.openStart),this.openStart,this.openEnd)}eq(e){return this.content.eq(e.content)&&this.openStart==e.openStart&&this.openEnd==e.openEnd}toString(){return this.content+"("+this.openStart+","+this.openEnd+")"}toJSON(){if(!this.content.size)return null;let e={content:this.content.toJSON()};return this.openStart>0&&(e.openStart=this.openStart),this.openEnd>0&&(e.openEnd=this.openEnd),e}static fromJSON(e,a){if(!a)return va.empty;let n=a.openStart||0,i=a.openEnd||0;if(typeof n!="number"||typeof i!="number")throw new RangeError("Invalid input for Slice.fromJSON");return new va(Qt.fromJSON(e,a.content),n,i)}static maxOpen(e,a=!0){let n=0,i=0;for(let s=e.firstChild;s&&!s.isLeaf&&(a||!s.type.spec.isolating);s=s.firstChild)n++;for(let s=e.lastChild;s&&!s.isLeaf&&(a||!s.type.spec.isolating);s=s.lastChild)i++;return new va(e,n,i)}}va.empty=new va(Qt.empty,0,0);function toe(t,e,a){let{index:n,offset:i}=t.findIndex(e),s=t.maybeChild(n),{index:o,offset:l}=t.findIndex(a);if(i==e||s.isText){if(l!=a&&!t.child(o).isText)throw new RangeError("Removing non-flat range");return t.cut(0,e).append(t.cut(a))}if(n!=o)throw new RangeError("Removing non-flat range");return t.replaceChild(n,s.copy(toe(s.content,e-i-1,a-i-1)))}function aoe(t,e,a,n){let{index:i,offset:s}=t.findIndex(e),o=t.maybeChild(i);if(s==e||o.isText)return n&&!n.canReplace(i,i,a)?null:t.cut(0,e).append(a).append(t.cut(e));let l=aoe(o.content,e-s-1,a,o);return l&&t.replaceChild(i,o.copy(l))}function lKe(t,e,a){if(a.openStart>t.depth)throw new DT("Inserted content deeper than insertion position");if(t.depth-a.openStart!=e.depth-a.openEnd)throw new DT("Inconsistent open depths");return roe(t,e,a,0)}function roe(t,e,a,n){let i=t.index(n),s=t.node(n);if(i==e.index(n)&&n=0&&t.isText&&t.sameMarkup(e[a])?e[a]=t.withText(e[a].text+t.text):e.push(t)}function xw(t,e,a,n){let i=(e||t).node(a),s=0,o=e?e.index(a):i.childCount;t&&(s=t.index(a),t.depth>a?s++:t.textOffset&&(Mg(t.nodeAfter,n),s++));for(let l=s;li&&Mz(t,e,i+1),o=n.depth>i&&Mz(a,n,i+1),l=[];return xw(null,t,i,l),s&&o&&e.index(i)==a.index(i)?(noe(s,o),Mg(Eg(s,ioe(t,e,a,n,i+1)),l)):(s&&Mg(Eg(s,FT(t,e,i+1)),l),xw(e,a,i,l),o&&Mg(Eg(o,FT(a,n,i+1)),l)),xw(n,null,i,l),new Qt(l)}function FT(t,e,a){let n=[];if(xw(null,t,a,n),t.depth>a){let i=Mz(t,e,a+1);Mg(Eg(i,FT(t,e,a+1)),n)}return xw(e,null,a,n),new Qt(n)}function cKe(t,e){let a=e.depth-t.openStart,i=e.node(a).copy(t.content);for(let s=a-1;s>=0;s--)i=e.node(s).copy(Qt.from(i));return{start:i.resolveNoCache(t.openStart+a),end:i.resolveNoCache(i.content.size-t.openEnd-a)}}class gS{constructor(e,a,n){this.pos=e,this.path=a,this.parentOffset=n,this.depth=a.length/3-1}resolveDepth(e){return e==null?this.depth:e<0?this.depth+e:e}get parent(){return this.node(this.depth)}get doc(){return this.node(0)}node(e){return this.path[this.resolveDepth(e)*3]}index(e){return this.path[this.resolveDepth(e)*3+1]}indexAfter(e){return e=this.resolveDepth(e),this.index(e)+(e==this.depth&&!this.textOffset?0:1)}start(e){return e=this.resolveDepth(e),e==0?0:this.path[e*3-1]+1}end(e){return e=this.resolveDepth(e),this.start(e)+this.node(e).content.size}before(e){if(e=this.resolveDepth(e),!e)throw new RangeError("There is no position before the top-level node");return e==this.depth+1?this.pos:this.path[e*3-1]}after(e){if(e=this.resolveDepth(e),!e)throw new RangeError("There is no position after the top-level node");return e==this.depth+1?this.pos:this.path[e*3-1]+this.path[e*3].nodeSize}get textOffset(){return this.pos-this.path[this.path.length-1]}get nodeAfter(){let e=this.parent,a=this.index(this.depth);if(a==e.childCount)return null;let n=this.pos-this.path[this.path.length-1],i=e.child(a);return n?e.child(a).cut(n):i}get nodeBefore(){let e=this.index(this.depth),a=this.pos-this.path[this.path.length-1];return a?this.parent.child(e).cut(0,a):e==0?null:this.parent.child(e-1)}posAtIndex(e,a){a=this.resolveDepth(a);let n=this.path[a*3],i=a==0?0:this.path[a*3-1]+1;for(let s=0;s0;a--)if(this.start(a)<=e&&this.end(a)>=e)return a;return 0}blockRange(e=this,a){if(e.pos=0;n--)if(e.pos<=this.end(n)&&(!a||a(this.node(n))))return new LT(this,e,n);return null}sameParent(e){return this.pos-this.parentOffset==e.pos-e.parentOffset}max(e){return e.pos>this.pos?e:this}min(e){return e.pos=0&&a<=e.content.size))throw new RangeError("Position "+a+" out of range");let n=[],i=0,s=a;for(let o=e;;){let{index:l,offset:c}=o.content.findIndex(s),d=s-c;if(n.push(o,l,i+c),!d||(o=o.child(l),o.isText))break;s=d-1,i+=c+1}return new gS(a,n,s)}static resolveCached(e,a){let n=IY.get(e);if(n)for(let s=0;se&&this.nodesBetween(e,a,s=>(n.isInSet(s.marks)&&(i=!0),!i)),i}get isBlock(){return this.type.isBlock}get isTextblock(){return this.type.isTextblock}get inlineContent(){return this.type.inlineContent}get isInline(){return this.type.isInline}get isText(){return this.type.isText}get isLeaf(){return this.type.isLeaf}get isAtom(){return this.type.isAtom}toString(){if(this.type.spec.toDebugString)return this.type.spec.toDebugString(this);let e=this.type.name;return this.content.size&&(e+="("+this.content.toStringInner()+")"),soe(this.marks,e)}contentMatchAt(e){let a=this.type.contentMatch.matchFragment(this.content,0,e);if(!a)throw new Error("Called contentMatchAt on a node with invalid content");return a}canReplace(e,a,n=Qt.empty,i=0,s=n.childCount){let o=this.contentMatchAt(e).matchFragment(n,i,s),l=o&&o.matchFragment(this.content,a);if(!l||!l.validEnd)return!1;for(let c=i;ca.type.name)}`);this.content.forEach(a=>a.check())}toJSON(){let e={type:this.type.name};for(let a in this.attrs){e.attrs=this.attrs;break}return this.content.size&&(e.content=this.content.toJSON()),this.marks.length&&(e.marks=this.marks.map(a=>a.toJSON())),e}static fromJSON(e,a){if(!a)throw new RangeError("Invalid input for Node.fromJSON");let n;if(a.marks){if(!Array.isArray(a.marks))throw new RangeError("Invalid mark data for Node.fromJSON");n=a.marks.map(e.markFromJSON)}if(a.type=="text"){if(typeof a.text!="string")throw new RangeError("Invalid text node in JSON");return e.text(a.text,n)}let i=Qt.fromJSON(e,a.content),s=e.nodeType(a.type).create(a.attrs,i,n);return s.type.checkAttrs(s.attrs),s}}gd.prototype.text=void 0;class RT extends gd{constructor(e,a,n,i){if(super(e,a,null,i),!n)throw new RangeError("Empty text nodes are not allowed");this.text=n}toString(){return this.type.spec.toDebugString?this.type.spec.toDebugString(this):soe(this.marks,JSON.stringify(this.text))}get textContent(){return this.text}textBetween(e,a){return this.text.slice(e,a)}get nodeSize(){return this.text.length}mark(e){return e==this.marks?this:new RT(this.type,this.attrs,this.text,e)}withText(e){return e==this.text?this:new RT(this.type,this.attrs,e,this.marks)}cut(e=0,a=this.text.length){return e==0&&a==this.text.length?this:this.withText(this.text.slice(e,a))}eq(e){return this.sameMarkup(e)&&this.text==e.text}toJSON(){let e=super.toJSON();return e.text=this.text,e}}function soe(t,e){for(let a=t.length-1;a>=0;a--)e=t[a].type.name+"("+e+")";return e}class sb{constructor(e){this.validEnd=e,this.next=[],this.wrapCache=[]}static parse(e,a){let n=new pKe(e,a);if(n.next==null)return sb.empty;let i=ooe(n);n.next&&n.err("Unexpected trailing text");let s=vKe(yKe(i));return wKe(s,n),s}matchType(e){for(let a=0;ad.createAndFill()));for(let d=0;d=this.next.length)throw new RangeError(`There's no ${e}th edge in this content match`);return this.next[e]}toString(){let e=[];function a(n){e.push(n);for(let i=0;i{let s=i+(n.validEnd?"*":" ")+" ";for(let o=0;o"+e.indexOf(n.next[o].next);return s}).join(` `)}}sb.empty=new sb(!0);class pKe{constructor(e,a){this.string=e,this.nodeTypes=a,this.inline=null,this.pos=0,this.tokens=e.split(/\s*(?=\b|\W|$)/),this.tokens[this.tokens.length-1]==""&&this.tokens.pop(),this.tokens[0]==""&&this.tokens.shift()}get next(){return this.tokens[this.pos]}eat(e){return this.next==e&&(this.pos++||!0)}err(e){throw new SyntaxError(e+" (in content expression '"+this.string+"')")}}function ooe(t){let e=[];do e.push(hKe(t));while(t.eat("|"));return e.length==1?e[0]:{type:"choice",exprs:e}}function hKe(t){let e=[];do e.push(fKe(t));while(t.next&&t.next!=")"&&t.next!="|");return e.length==1?e[0]:{type:"seq",exprs:e}}function fKe(t){let e=xKe(t);for(;;)if(t.eat("+"))e={type:"plus",expr:e};else if(t.eat("*"))e={type:"star",expr:e};else if(t.eat("?"))e={type:"opt",expr:e};else if(t.eat("{"))e=gKe(t,e);else break;return e}function OY(t){/\D/.test(t.next)&&t.err("Expected number, got '"+t.next+"'");let e=Number(t.next);return t.pos++,e}function gKe(t,e){let a=OY(t),n=a;return t.eat(",")&&(t.next!="}"?n=OY(t):n=-1),t.eat("}")||t.err("Unclosed braced range"),{type:"range",min:a,max:n,expr:e}}function bKe(t,e){let a=t.nodeTypes,n=a[e];if(n)return[n];let i=[];for(let s in a){let o=a[s];o.isInGroup(e)&&i.push(o)}return i.length==0&&t.err("No node type or group '"+e+"' found"),i}function xKe(t){if(t.eat("(")){let e=ooe(t);return t.eat(")")||t.err("Missing closing paren"),e}else if(/\W/.test(t.next))t.err("Unexpected token '"+t.next+"'");else{let e=bKe(t,t.next).map(a=>(t.inline==null?t.inline=a.isInline:t.inline!=a.isInline&&t.err("Mixing inline and block content"),{type:"name",value:a}));return t.pos++,e.length==1?e[0]:{type:"choice",exprs:e}}}function yKe(t){let e=[[]];return i(s(t,0),a()),e;function a(){return e.push([])-1}function n(o,l,c){let d={term:c,to:l};return e[o].push(d),d}function i(o,l){o.forEach(c=>c.to=l)}function s(o,l){if(o.type=="choice")return o.exprs.reduce((c,d)=>c.concat(s(d,l)),[]);if(o.type=="seq")for(let c=0;;c++){let d=s(o.exprs[c],l);if(c==o.exprs.length-1)return d;i(d,l=a())}else if(o.type=="star"){let c=a();return n(l,c),i(s(o.expr,c),c),[n(c)]}else if(o.type=="plus"){let c=a();return i(s(o.expr,l),c),i(s(o.expr,c),c),[n(c)]}else{if(o.type=="opt")return[n(l)].concat(s(o.expr,l));if(o.type=="range"){let c=l;for(let d=0;d{t[o].forEach(({term:l,to:c})=>{if(!l)return;let d;for(let u=0;u{d||i.push([l,d=[]]),d.indexOf(u)==-1&&d.push(u)})})});let s=e[n.join(",")]=new sb(n.indexOf(t.length-1)>-1);for(let o=0;o-1}get whitespace(){return this.spec.whitespace||(this.spec.code?"pre":"normal")}hasRequiredAttrs(){for(let e in this.attrs)if(this.attrs[e].isRequired)return!0;return!1}compatibleContent(e){return this==e||this.contentMatch.compatible(e.contentMatch)}computeAttrs(e){return!e&&this.defaultAttrs?this.defaultAttrs:doe(this.attrs,e)}create(e=null,a,n){if(this.isText)throw new Error("NodeType.create can't construct text nodes");return new gd(this,this.computeAttrs(e),Qt.from(a),vn.setFrom(n))}createChecked(e=null,a,n){return a=Qt.from(a),this.checkContent(a),new gd(this,this.computeAttrs(e),a,vn.setFrom(n))}createAndFill(e=null,a,n){if(e=this.computeAttrs(e),a=Qt.from(a),a.size){let o=this.contentMatch.fillBefore(a);if(!o)return null;a=o.append(a)}let i=this.contentMatch.matchFragment(a),s=i&&i.fillBefore(Qt.empty,!0);return s?new gd(this,e,a.append(s),vn.setFrom(n)):null}validContent(e){let a=this.contentMatch.matchFragment(e);if(!a||!a.validEnd)return!1;for(let n=0;n-1}allowsMarks(e){if(this.markSet==null)return!0;for(let a=0;an[s]=new poe(s,a,o));let i=a.spec.topNode||"doc";if(!n[i])throw new RangeError("Schema is missing its top node type ('"+i+"')");if(!n.text)throw new RangeError("Every schema needs a 'text' type");for(let s in n.text.attrs)throw new RangeError("The text node type should not have attributes");return n}};function SKe(t,e,a){let n=a.split("|");return i=>{let s=i===null?"null":typeof i;if(n.indexOf(s)<0)throw new RangeError(`Expected value of type ${n} for attribute ${e} on type ${t}, got ${s}`)}}class kKe{constructor(e,a,n){this.hasDefault=Object.prototype.hasOwnProperty.call(n,"default"),this.default=n.default,this.validate=typeof n.validate=="string"?SKe(e,a,n.validate):n.validate}get isRequired(){return!this.hasDefault}}class XA{constructor(e,a,n,i){this.name=e,this.rank=a,this.schema=n,this.spec=i,this.attrs=moe(e,i.attrs),this.excluded=null;let s=coe(this.attrs);this.instance=s?new vn(this,s):null}create(e=null){return!e&&this.instance?this.instance:new vn(this,doe(this.attrs,e))}static compile(e,a){let n=Object.create(null),i=0;return e.forEach((s,o)=>n[s]=new XA(s,i++,a,o)),n}removeFromSet(e){for(var a=0;a-1}}class hoe{constructor(e){this.linebreakReplacement=null,this.cached=Object.create(null);let a=this.spec={};for(let i in e)a[i]=e[i];a.nodes=Ms.from(e.nodes),a.marks=Ms.from(e.marks||{}),this.nodes=UY.compile(this.spec.nodes,this),this.marks=XA.compile(this.spec.marks,this);let n=Object.create(null);for(let i in this.nodes){if(i in this.marks)throw new RangeError(i+" can not be both a node and a mark");let s=this.nodes[i],o=s.spec.content||"",l=s.spec.marks;if(s.contentMatch=n[o]||(n[o]=sb.parse(o,this.nodes)),s.inlineContent=s.contentMatch.inlineContent,s.spec.linebreakReplacement){if(this.linebreakReplacement)throw new RangeError("Multiple linebreak nodes defined");if(!s.isInline||!s.isLeaf)throw new RangeError("Linebreak replacement nodes must be inline leaf nodes");this.linebreakReplacement=s}s.markSet=l=="_"?null:l?HY(this,l.split(" ")):l==""||!s.inlineContent?[]:null}for(let i in this.marks){let s=this.marks[i],o=s.spec.excludes;s.excluded=o==null?[s]:o==""?[]:HY(this,o.split(" "))}this.nodeFromJSON=i=>gd.fromJSON(this,i),this.markFromJSON=i=>vn.fromJSON(this,i),this.topNodeType=this.nodes[this.spec.topNode||"doc"],this.cached.wrappings=Object.create(null)}node(e,a=null,n,i){if(typeof e=="string")e=this.nodeType(e);else if(e instanceof UY){if(e.schema!=this)throw new RangeError("Node type from different schema used ("+e.name+")")}else throw new RangeError("Invalid node type: "+e);return e.createChecked(a,n,i)}text(e,a){let n=this.nodes.text;return new RT(n,n.defaultAttrs,e,vn.setFrom(a))}mark(e,a){return typeof e=="string"&&(e=this.marks[e]),e.create(a)}nodeType(e){let a=this.nodes[e];if(!a)throw new RangeError("Unknown node type: "+e);return a}}function HY(t,e){let a=[];for(let n=0;n-1)&&a.push(o=c)}if(!o)throw new SyntaxError("Unknown mark type: '"+e[n]+"'")}return a}function _Ke(t){return t.tag!=null}function PKe(t){return t.style!=null}let yw=class Ez{constructor(e,a){this.schema=e,this.rules=a,this.tags=[],this.styles=[];let n=this.matchedStyles=[];a.forEach(i=>{if(_Ke(i))this.tags.push(i);else if(PKe(i)){let s=/[^=]*/.exec(i.style)[0];n.indexOf(s)<0&&n.push(s),this.styles.push(i)}}),this.normalizeLists=!this.tags.some(i=>{if(!/^(ul|ol)\b/.test(i.tag)||!i.node)return!1;let s=e.nodes[i.node];return s.contentMatch.matchType(s)})}parse(e,a={}){let n=new VY(this,a,!1);return n.addAll(e,vn.none,a.from,a.to),n.finish()}parseSlice(e,a={}){let n=new VY(this,a,!0);return n.addAll(e,vn.none,a.from,a.to),va.maxOpen(n.finish())}matchTag(e,a,n){for(let i=n?this.tags.indexOf(n)+1:0;ie.length&&(l.charCodeAt(e.length)!=61||l.slice(e.length+1)!=a))){if(o.getAttrs){let c=o.getAttrs(a);if(c===!1)continue;o.attrs=c||void 0}return o}}}static schemaRules(e){let a=[];function n(i){let s=i.priority==null?50:i.priority,o=0;for(;o{n(o=GY(o)),o.mark||o.ignore||o.clearMark||(o.mark=i)})}for(let i in e.nodes){let s=e.nodes[i].spec.parseDOM;s&&s.forEach(o=>{n(o=GY(o)),o.node||o.ignore||o.mark||(o.node=i)})}return a}static fromSchema(e){return e.cached.domParser||(e.cached.domParser=new Ez(e,Ez.schemaRules(e)))}};const foe={address:!0,article:!0,aside:!0,blockquote:!0,canvas:!0,dd:!0,div:!0,dl:!0,fieldset:!0,figcaption:!0,figure:!0,footer:!0,form:!0,h1:!0,h2:!0,h3:!0,h4:!0,h5:!0,h6:!0,header:!0,hgroup:!0,hr:!0,li:!0,noscript:!0,ol:!0,output:!0,p:!0,pre:!0,section:!0,table:!0,tfoot:!0,ul:!0},CKe={head:!0,noscript:!0,object:!0,script:!0,style:!0,title:!0},goe={ol:!0,ul:!0},bS=1,Dz=2,vw=4;function qY(t,e,a){return e!=null?(e?bS:0)|(e==="full"?Dz:0):t&&t.whitespace=="pre"?bS|Dz:a&~vw}class iC{constructor(e,a,n,i,s,o){this.type=e,this.attrs=a,this.marks=n,this.solid=i,this.options=o,this.content=[],this.activeMarks=vn.none,this.match=s||(o&vw?null:e.contentMatch)}findWrapping(e){if(!this.match){if(!this.type)return[];let a=this.type.contentMatch.fillBefore(Qt.from(e));if(a)this.match=this.type.contentMatch.matchFragment(a);else{let n=this.type.contentMatch,i;return(i=n.findWrapping(e.type))?(this.match=n,i):null}}return this.match.findWrapping(e.type)}finish(e){if(!(this.options&bS)){let n=this.content[this.content.length-1],i;if(n&&n.isText&&(i=/[ \t\r\n\u000c]+$/.exec(n.text))){let s=n;n.text.length==i[0].length?this.content.pop():this.content[this.content.length-1]=s.withText(s.text.slice(0,s.text.length-i[0].length))}}let a=Qt.from(this.content);return!e&&this.match&&(a=a.append(this.match.fillBefore(Qt.empty,!0))),this.type?this.type.create(this.attrs,a,this.marks):a}inlineContext(e){return this.type?this.type.inlineContent:this.content.length?this.content[0].isInline:e.parentNode&&!foe.hasOwnProperty(e.parentNode.nodeName.toLowerCase())}}class VY{constructor(e,a,n){this.parser=e,this.options=a,this.isOpen=n,this.open=0,this.localPreserveWS=!1;let i=a.topNode,s,o=qY(null,a.preserveWhitespace,0)|(n?vw:0);i?s=new iC(i.type,i.attrs,vn.none,!0,a.topMatch||i.type.contentMatch,o):n?s=new iC(null,null,vn.none,!0,null,o):s=new iC(e.schema.topNodeType,null,vn.none,!0,null,o),this.nodes=[s],this.find=a.findPositions,this.needsBlock=!1}get top(){return this.nodes[this.open]}addDOM(e,a){e.nodeType==3?this.addTextNode(e,a):e.nodeType==1&&this.addElement(e,a)}addTextNode(e,a){let n=e.nodeValue,i=this.top,s=i.options&Dz?"full":this.localPreserveWS||(i.options&bS)>0,{schema:o}=this.parser;if(s==="full"||i.inlineContext(e)||/[^ \t\r\n\u000c]/.test(n)){if(s)if(s==="full")n=n.replace(/\r\n?/g,` `);else if(o.linebreakReplacement&&/[\r\n]/.test(n)&&this.top.findWrapping(o.linebreakReplacement.create())){let l=n.split(/\r?\n|\r/);for(let c=0;c{de.isPending||(p(!1),b(null),g(null))}})})()]})}function Ilt({isOpen:t,onClose:e,tagId:a,untaggedSpools:n,onLink:i}){const{t:s}=wt(),[o,l]=y.useState(null),c=y.useCallback(()=>{l(null),e()},[e]),d=y.useCallback(m=>{m.key==="Escape"&&c()},[c]);if(y.useEffect(()=>(t&&(document.addEventListener("keydown",d),document.body.style.overflow="hidden"),()=>{document.removeEventListener("keydown",d),document.body.style.overflow=""}),[t,d]),!t)return null;const u=()=>{o&&(i(o),l(null))};return r.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/70 animate-fade-in",onClick:c,children:r.jsxs("div",{className:"bg-zinc-800 rounded-xl shadow-2xl w-full max-w-lg mx-4 animate-slide-up",onClick:m=>m.stopPropagation(),children:[r.jsxs("div",{className:"flex items-center justify-between px-5 py-4 border-b border-zinc-700",children:[r.jsxs("div",{children:[r.jsx("h2",{className:"text-base font-semibold text-zinc-100",children:s("spoolbuddy.dashboard.linkTagTitle","Link Tag to Spool")}),r.jsx("p",{className:"text-sm text-zinc-500 font-mono",children:a})]}),r.jsx("button",{onClick:c,className:"p-2 rounded-lg text-zinc-500 hover:text-zinc-300 hover:bg-zinc-700 transition-colors",children:r.jsx(Ht,{className:"w-5 h-5"})})]}),r.jsxs("div",{className:"px-5 py-4 space-y-3 max-h-[400px] overflow-y-auto",children:[r.jsx("p",{className:"text-sm text-zinc-400",children:s("spoolbuddy.dashboard.selectSpool","Select a spool to link this tag to:")}),n.length===0?r.jsx("div",{className:"text-center py-8 text-zinc-500",children:s("spoolbuddy.dashboard.noUntagged","No spools without tags found")}):r.jsx("div",{className:"space-y-2",children:n.map(m=>r.jsxs("button",{type:"button",onClick:()=>l(m),className:`w-full flex items-center gap-3 p-3 rounded-lg border-2 transition-all text-left ${o?.id===m.id?"border-green-500 bg-green-500/10":"border-zinc-700 hover:border-green-500/50 hover:bg-zinc-700/50"}`,children:[r.jsx(vj,{color:B1(m.rgba),isEmpty:!1,size:40}),r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("div",{className:"font-medium text-zinc-100 truncate",children:m.color_name||"Unknown color"}),r.jsxs("span",{className:"text-[10px] font-mono text-zinc-500 shrink-0",children:["#",m.id]})]}),r.jsxs("div",{className:"text-sm text-zinc-400 truncate",children:[m.brand," • ",m.material,m.subtype&&` ${m.subtype}`]})]}),r.jsxs("div",{className:"text-sm font-mono text-zinc-500",children:[Math.max(0,m.label_weight-m.weight_used),"g"]})]},m.id))})]}),r.jsxs("div",{className:"flex justify-end gap-2 px-5 py-4 border-t border-zinc-700",children:[r.jsx("button",{onClick:c,className:"px-4 py-2.5 rounded-lg text-sm font-medium bg-zinc-700 text-zinc-300 hover:bg-zinc-600 transition-colors min-h-[44px]",children:s("common.cancel","Cancel")}),r.jsx("button",{onClick:u,disabled:!o,className:"px-4 py-2.5 rounded-lg text-sm font-medium bg-green-600 text-white hover:bg-green-700 disabled:opacity-40 disabled:cursor-not-allowed transition-colors min-h-[44px]",children:s("spoolbuddy.dashboard.linkTag","Link Tag")})]})]})})}function rZ(t){return t?t.replace(/[^0-9a-f]/gi,"").toUpperCase():""}function Olt(t,e){const a=rZ(t),n=rZ(e);return!a||!n?!1:a===n?!0:a.endsWith(n)||n.endsWith(a)}const nZ=["#00AE42","#FF6B35","#3B82F6","#EF4444","#A855F7","#FBBF24","#14B8A6","#EC4899","#F97316","#22C55E"];function Blt(){const{t}=wt(),[e,a]=y.useState(0);y.useEffect(()=>{const i=setInterval(()=>{a(s=>(s+1)%nZ.length)},5e3);return()=>clearInterval(i)},[]);const n=nZ[e];return r.jsxs("div",{className:"flex flex-col items-center text-center",children:[r.jsxs("div",{className:"relative mb-6 flex items-center justify-center",style:{width:160,height:160},children:[r.jsx("div",{className:"absolute inset-0 flex items-center justify-center pointer-events-none",children:[0,1].map(i=>r.jsx("div",{className:"absolute rounded-full border spoolbuddy-optimized-ping",style:{width:80,height:80,borderColor:`${n}4D`,transition:"border-color 140ms linear",animationDelay:`${i*.8}s`}},i))}),r.jsxs("div",{className:"relative overflow-hidden rounded-full",children:[r.jsx("div",{className:"absolute inset-0 rounded-full opacity-30 spoolbuddy-spool-glow",style:{background:`radial-gradient(circle, ${n} 0%, transparent 70%)`}}),r.jsx("div",{className:"relative",style:{transition:"opacity 140ms linear"},children:r.jsx(vj,{color:n,isEmpty:!1,size:100})})]})]}),r.jsxs("div",{className:"space-y-2",children:[r.jsx("p",{className:"text-xl font-medium text-zinc-300",children:t("spoolbuddy.dashboard.readyToScan","Ready to scan")}),r.jsx("p",{className:"text-sm text-zinc-500",children:t("spoolbuddy.dashboard.idleMessage","Place a spool on the scale to identify it")})]}),r.jsxs("div",{className:"mt-6 flex items-center gap-2 text-sm text-zinc-600",children:[r.jsx("svg",{className:"w-4 h-4",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:r.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"})}),r.jsx("span",{children:t("spoolbuddy.dashboard.nfcHint","NFC tag will be read automatically")})]})]})}function Ult(){const{t}=wt();return r.jsxs("div",{className:"flex flex-col items-center text-center",children:[r.jsx("div",{className:"relative mb-6 flex items-center justify-center",style:{width:160,height:160},children:r.jsx("div",{className:"w-24 h-24 rounded-full bg-zinc-800 flex items-center justify-center",children:r.jsx("svg",{className:"w-12 h-12 text-zinc-600",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:r.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"})})})}),r.jsxs("div",{className:"space-y-2",children:[r.jsx("p",{className:"text-lg font-medium text-zinc-500",children:t("spoolbuddy.status.deviceOffline","Device Offline")}),r.jsx("p",{className:"text-sm text-zinc-600",children:t("spoolbuddy.status.connectDisplay","Connect the SpoolBuddy display to scan spools")})]}),r.jsxs("div",{className:"mt-6 flex items-center gap-2 text-xs text-zinc-600",children:[r.jsx("svg",{className:"w-4 h-4",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:r.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"})}),r.jsx("span",{children:t("spoolbuddy.status.waitingConnection","Waiting for device connection...")})]})]})}function Hlt(){const{sbState:t,selectedPrinterId:e}=Jy(),{t:a}=wt(),{showToast:n}=oa(),{data:i}=$e({queryKey:["spoolman-settings"],queryFn:ne.getSpoolmanSettings,staleTime:300*1e3}),s=i?.spoolman_enabled==="true"&&!!i?.spoolman_url,{data:o=[],refetch:l}=$e({queryKey:s?["spoolman-inventory-spools"]:["inventory-spools"],queryFn:()=>s?ne.getSpoolmanInventorySpools(!1):ne.getSpools(!1),enabled:i!==void 0}),{data:c=[]}=$e({queryKey:["spoolman-slot-assignments"],queryFn:()=>ne.getSpoolmanSlotAssignments(),enabled:s,staleTime:3*1e3,refetchInterval:3*1e3,refetchIntervalInBackground:!1}),{data:d=[]}=$e({queryKey:["printers"],queryFn:()=>ne.getPrinters()}),u=df({queries:d.map(le=>({queryKey:["printerStatus",le.id],queryFn:()=>ne.getPrinterStatus(le.id),refetchInterval:1e4,select:O=>({connected:O?.connected,awaiting_plate_clear:O?.awaiting_plate_clear===!0})}))}),m=d.map((le,O)=>({printer:le,pending:u[O]?.data?.awaiting_plate_clear===!0})).filter(le=>le.pending),p=na(),f=at({mutationFn:le=>ne.clearPlate(le),onSuccess:(le,O)=>{p.setQueryData(["printerStatus",O],q=>q&&{...q,awaiting_plate_clear:!1}),n(a("spoolbuddy.dashboard.plateClearedToast","Plate marked as cleared"),"success")},onError:()=>{n(a("spoolbuddy.dashboard.plateClearFailed","Could not mark plate as cleared"),"error")}}),g=at({mutationFn:le=>ne.unassignSpoolmanSlot(le),onSuccess:()=>{p.invalidateQueries({queryKey:["spoolman-slot-assignments"]}),p.invalidateQueries({queryKey:["spoolman-inventory-spools"]})},onError:()=>n(a("inventory.unassignFailed","Failed to unassign spool"),"error")}),[v,b]=y.useState(null),[x,S]=y.useState(null),[k,C]=y.useState(null),[N,T]=y.useState(!1),[j,D]=y.useState(!1),[P,E]=y.useState(!1),[z,I]=y.useState(!1),[B,R]=y.useState(null),K=t.matchedSpool?.tag_uid??t.unknownTagUid??null,J=t.weight,X=t.weightStable,ce=y.useRef(null);J===null?ce.current=null:(ce.current===null||Math.abs(J-ce.current)>=3||X)&&(ce.current=J);const oe=ce.current,Y=y.useMemo(()=>{if(t.matchedSpool?.id){const O=o.find(q=>q.id===t.matchedSpool?.id);if(O)return O}if(!v)return null;const le=o.find(O=>Olt(O.tag_uid,v));return le||B||null},[v,t.matchedSpool,o,B]),ie=y.useMemo(()=>{if(Y&&!B)return Y;const le=t.matchedSpool;return le?{id:le.id,tag_uid:le.tag_uid,material:le.material,subtype:le.subtype,color_name:le.color_name,rgba:le.rgba,brand:le.brand,label_weight:le.label_weight,core_weight:le.core_weight,weight_used:le.weight_used}:null},[Y,B,t.matchedSpool]),me=s&&ie!=null?c.some(le=>le.spoolman_spool_id===ie.id):!1,he=y.useMemo(()=>s?o.filter(le=>!le.tag_uid&&!le.tray_uuid&&!le.archived_at):o.filter(le=>!le.tag_uid&&!le.archived_at),[o,s]);y.useEffect(()=>{if(K){const le=k===K;(v!==null&&v!==K||!le&&v!==K)&&(b(K),S(null),C(null),R(null)),!le&&J!==null&&X&&S(Math.round(Math.max(0,J)))}else k&&(b(null),C(null),S(null),R(null))},[K,J,X,v,k]);const xe=()=>{C(v)},V=async le=>{if(v)try{if(s){const O=t.unknownTagUid||void 0,q=!t.unknownTagUid&&t.unknownTrayUuid?t.unknownTrayUuid:void 0;if(!O&&!q){n(a("spoolman.linkFailed"),"error");return}const ee=await ne.linkTagToSpoolmanSpool(le.id,{tray_uuid:q,tag_uid:O});if(!ee){n(a("spoolman.linkFailed"),"error");return}const{id:re,material:se,subtype:fe,color_name:ue,rgba:pe,brand:G,label_weight:L,core_weight:ae,weight_used:ge}=ee;R({id:re,material:se,subtype:fe,color_name:ue,rgba:pe,brand:G,label_weight:L,core_weight:ae,weight_used:ge}),n(a("spoolman.linkSuccess"),"success")}else await ne.linkTagToSpool(le.id,{tag_uid:v,tag_type:"generic",data_origin:"nfc_link"});l()}catch(O){console.error("Failed to link tag:",O),n(a("spoolman.linkFailed"),"error")}finally{T(!1)}},Q=async()=>{if(v){I(!0);try{const le=F??x;if(s){const O=await ne.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:le!==null?Math.round(le):null,last_weighed_at:le!==null?new Date().toISOString():null,category:null,low_stock_threshold_pct:null});await ne.linkTagToSpoolmanSpool(O.id,{tag_uid:t.unknownTagUid||void 0,tray_uuid:!t.unknownTagUid&&t.unknownTrayUuid?t.unknownTrayUuid:void 0})}else await ne.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:v,tray_uuid:null,data_origin:"spoolbuddy",tag_type:"generic",cost_per_kg:null,last_scale_weight:le!==null?Math.round(le):null,last_weighed_at:le!==null?new Date().toISOString():null,category:null,low_stock_threshold_pct:null})}catch(le){const O=le instanceof Error?le.message:String(le);console.error("Failed to quick-add spool:",O),n(O||a("spoolbuddy.errors.quickAddFailed","Failed to add spool"),"error")}finally{E(!1),I(!1),l()}}},F=J!==null&&(K===v||K===null&&v!==null)?J:null,U=o.length,$=new Set(o.map(le=>le.material)).size,H=new Set(o.filter(le=>le.brand).map(le=>le.brand)).size;return r.jsxs("div",{className:"h-full flex flex-col p-4",children:[r.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:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("span",{className:"text-xl font-bold text-zinc-100",children:U}),r.jsx("span",{className:"text-sm text-zinc-500",children:a("spoolbuddy.inventory.spools","Spools")})]}),r.jsx("div",{className:"w-px h-5 bg-zinc-700"}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("span",{className:"text-xl font-bold text-zinc-100",children:$}),r.jsx("span",{className:"text-sm text-zinc-500",children:a("spoolbuddy.spool.material","Materials")})]}),r.jsx("div",{className:"w-px h-5 bg-zinc-700"}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("span",{className:"text-xl font-bold text-zinc-100",children:H}),r.jsx("span",{className:"text-sm text-zinc-500",children:a("spoolbuddy.spool.brand","Brands")})]})]}),r.jsxs("div",{className:"flex-1 flex gap-4 min-h-0",children:[r.jsxs("div",{className:"w-5/12 flex flex-col min-h-0",children:[r.jsxs("div",{className:"border border-dashed border-zinc-700/50 rounded-xl p-4",children:[r.jsx("h2",{className:"text-sm font-semibold text-zinc-400 uppercase tracking-wide mb-3",children:a("spoolbuddy.dashboard.device","Device")}),r.jsxs("div",{className:"space-y-2.5",children:[r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("div",{className:`w-2.5 h-2.5 rounded-full ${t.deviceOnline?"bg-green-500":"bg-red-500"}`}),r.jsx("span",{className:"text-base text-zinc-400",children:t.deviceOnline?a("spoolbuddy.status.online","Online"):a("spoolbuddy.status.offline","Disconnected")})]}),r.jsxs("div",{className:"flex items-center justify-between p-3 bg-zinc-800/50 rounded-lg",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("svg",{className:`w-4 h-4 ${t.deviceOnline?"text-green-500":"text-zinc-500"}`,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:r.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"})}),r.jsx("span",{className:"text-sm text-zinc-500",children:a("spoolbuddy.spool.scaleWeight","Scale")})]}),r.jsx("span",{className:"text-lg font-mono font-semibold text-zinc-100",children:oe!==null?`${Math.abs(oe)<=20?0:Math.round(Math.max(0,oe))}g`:"—"})]}),r.jsxs("div",{className:"flex items-center justify-between p-3 bg-zinc-800/50 rounded-lg",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("svg",{className:`w-4 h-4 ${t.deviceOnline?"text-green-500":"text-zinc-500"}`,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:r.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"})}),r.jsx("span",{className:"text-sm text-zinc-500",children:"NFC"})]}),r.jsx("span",{className:`text-sm font-medium ${K?"text-green-500":"text-zinc-500"}`,children:K?a("spoolbuddy.dashboard.tagDetected","Tag detected"):a("spoolbuddy.dashboard.noTag","No tag")})]})]})]}),d.length>0&&r.jsxs("div",{className:"mt-3 border border-dashed border-zinc-700/50 rounded-xl p-4",children:[r.jsx("h2",{className:"text-sm font-semibold text-zinc-400 uppercase tracking-wide mb-2.5",children:a("spoolbuddy.dashboard.printers","Printers")}),r.jsx("div",{className:"flex flex-wrap gap-2 overflow-hidden",children:d.map((le,O)=>{const q=u[O]?.data?.connected??!1;return r.jsxs("div",{className:"flex items-center gap-1.5 px-2.5 py-1 bg-zinc-800/50 rounded-lg",title:`${le.name} — ${q?"Online":"Offline"}`,children:[r.jsx("div",{className:`w-2 h-2 rounded-full shrink-0 ${q?"bg-green-500":"bg-zinc-600"}`}),r.jsx("span",{className:"text-xs text-zinc-400 truncate max-w-[100px]",children:le.name})]},le.id)})}),m.length>0&&r.jsx("div",{className:"mt-2 flex flex-wrap gap-2","data-testid":"plate-clear-section","aria-label":a("spoolbuddy.dashboard.plateReadyLabel","Plates ready to clear"),children:m.map(({printer:le})=>r.jsxs("button",{type:"button",onClick:()=>f.mutate(le.id),disabled:f.isPending,"data-testid":`plate-clear-button-${le.id}`,title:a("spoolbuddy.dashboard.plateReady","Plate ready: {{name}}",{name:le.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:[r.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:[r.jsx("path",{d:"M12 9v4"}),r.jsx("path",{d:"M12 17h.01"}),r.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"})]}),r.jsx("span",{className:"text-xs truncate max-w-[100px]",children:le.name}),r.jsx("span",{className:"text-xs opacity-70","aria-hidden":"true",children:"·"}),r.jsx("span",{className:"text-xs font-medium",children:a("spoolbuddy.dashboard.plateClearAction","Clear")})]},le.id))})]})]}),r.jsx("div",{className:"w-7/12 min-h-0",children:r.jsxs("div",{className:"border border-dashed border-zinc-700/50 rounded-xl p-6 h-full flex flex-col",children:[r.jsx("h2",{className:"text-sm font-semibold text-zinc-400 uppercase tracking-wide mb-4 shrink-0",children:a("spoolbuddy.dashboard.currentSpool","Current Spool")}),r.jsx("div",{className:"flex-1 flex items-center justify-center min-h-0",children:t.deviceOnline?(Y||t.matchedSpool)&&v&&k!==v?r.jsx(klt,{spool:(()=>{const le=Y??t.matchedSpool;return{id:le.id,tag_uid:v,material:le.material,subtype:le.subtype,color_name:le.color_name,rgba:le.rgba,brand:le.brand,label_weight:le.label_weight,core_weight:le.core_weight,weight_used:le.weight_used}})(),scaleWeight:F??x,onSyncWeight:()=>l(),onAssignToAms:()=>D(!0),isAssigned:me,onUnassignFromAms:me&&Y?.id!=null?()=>g.mutate(Y.id):void 0,onClose:xe}):K&&v&&!Y&&!t.matchedSpool&&k!==v?r.jsx(_lt,{tagUid:v,scaleWeight:F??x,onLinkSpool:he.length>0?()=>T(!0):void 0,onAddToInventory:()=>E(!0),onClose:xe}):r.jsx(Blt,{}):r.jsx(Ult,{})})]})})]}),ie&&!B&&v&&r.jsx($de,{isOpen:j,onClose:()=>D(!1),spool:ie,printerId:e,spoolmanMode:s}),v&&r.jsx(Ilt,{isOpen:N,onClose:()=>T(!1),tagId:v,untaggedSpools:he,onLink:V}),P&&v&&r.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/60",children:r.jsxs("div",{className:"bg-zinc-800 rounded-2xl p-6 mx-4 max-w-sm w-full border border-zinc-700",children:[r.jsx("h3",{className:"text-lg font-semibold text-zinc-100 mb-3",children:a("spoolbuddy.modal.addToInventory","Add to Inventory")}),r.jsxs("div",{className:"flex gap-2.5 p-3 bg-amber-500/10 border border-amber-500/20 rounded-lg mb-4",children:[r.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:r.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"})}),r.jsx("p",{className:"text-sm text-amber-200/80",children:a("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.')})]}),r.jsx("p",{className:"text-sm text-zinc-400 mb-1",children:a("spoolbuddy.modal.quickAddDesc","This will create a basic PLA spool entry with this NFC tag. You can edit the details later in Bambuddy.")}),r.jsx("p",{className:"text-xs text-zinc-500 font-mono mb-5",children:v}),r.jsxs("div",{className:"flex gap-3",children:[r.jsx("button",{onClick:()=>E(!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:a("common.cancel","Cancel")}),r.jsx("button",{onClick:Q,disabled:z,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:z?a("common.saving","Saving..."):a("spoolbuddy.modal.addAnyway","Add Anyway")})]})]})})]})}function iZ(t){return t<=3?`AMS ${String.fromCharCode(65+t)}`:t>=128&&t<=135?`AMS HT ${String.fromCharCode(65+t-128)}`:`AMS ${t}`}function qlt(t){return t?{O1D:"H2D",O1E:"H2D Pro",O2D:"H2D Pro",O1C:"H2C",O1C2:"H2C",O1S:"H2S","BL-P001":"X1C","BL-P002":"X1","BL-P003":"X1E",N6:"X2D",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",H2D:"H2D","H2D Pro":"H2D Pro",H2C:"H2C",H2S:"H2S"}[t]||t:""}function Zf(t){return!t.tray_type||t.tray_type===""}function Vlt(t){return t?`#${t.slice(0,6)}`:"#808080"}function Glt(){const{selectedPrinterId:t,setAlert:e}=Jy(),{t:a}=wt(),n=na(),{showToast:i}=oa(),{data:s}=$e({queryKey:["printerStatus",t],queryFn:()=>ne.getPrinterStatus(t),enabled:t!==null,staleTime:30*1e3}),{data:o}=$e({queryKey:["printer",t],queryFn:()=>ne.getPrinter(t),enabled:t!==null,staleTime:60*1e3}),{data:l}=$e({queryKey:["slotPresets",t],queryFn:()=>ne.getSlotPresets(t),enabled:t!==null,staleTime:120*1e3}),{data:c}=$e({queryKey:["settings"],queryFn:()=>ne.getSettings(),staleTime:300*1e3}),{data:d}=$e({queryKey:["spoolman-status"],queryFn:ne.getSpoolmanStatus,staleTime:60*1e3}),u=d?.enabled&&d?.connected,{data:m}=$e({queryKey:["linked-spools"],queryFn:ne.getLinkedSpools,enabled:!!u,staleTime:30*1e3}),p=m?.linked,{data:f=[]}=$e({queryKey:["spoolman-slot-assignments-all"],queryFn:()=>ne.getSpoolmanSlotAssignments(),enabled:!!u,staleTime:30*1e3}),{data:g=[]}=$e({queryKey:["spoolman-inventory-spools"],queryFn:()=>ne.getSpoolmanInventorySpools(!1),enabled:!!u,staleTime:30*1e3}),{data:v}=$e({queryKey:["spool-assignments",t],queryFn:()=>ne.getAssignments(t),enabled:t!==null,staleTime:30*1e3}),b=y.useMemo(()=>{const se={};if(!v)return se;for(const fe of v){const ue=fe.spool;if(ue&&ue.label_weight>0&&ue.weight_used!=null){const pe=Math.round(Math.max(0,ue.label_weight-ue.weight_used)/ue.label_weight*100);se[`${fe.ams_id}-${fe.tray_id}`]=pe}}return se},[v]),x=o?.serial_number??"",S=y.useCallback((se,fe,ue)=>{if(t!==null&&f.length&&g.length){const pe=f.find(G=>G.printer_id===t&&G.ams_id===se&&G.tray_id===fe);if(pe){const G=g.find(L=>L.id===pe.spoolman_spool_id);if(G&&(G.label_weight??0)>0)return Math.round(Math.max(0,G.label_weight-G.weight_used)/G.label_weight*100)}}if(p&&x){const pe=(ue?.tray_uuid||ue?.tag_uid||Sm(x,se,fe))?.toUpperCase(),G=pe?p[pe]:void 0,L=GC(G);if(L!==null)return L}return null},[p,x,t,f,g]),k=s?.connected??!1,C=y.useRef({});y.useEffect(()=>{t&&s?.ams&&s.ams.length>0&&(C.current[t]=s.ams)},[s?.ams,t]);const N=y.useMemo(()=>{const se=s?.ams;return se&&se.length>0?se:(t?C.current[t]:null)??[]},[s?.ams,t]),T=y.useMemo(()=>N.filter(se=>!se.is_ams_ht),[N]),j=y.useMemo(()=>N.filter(se=>se.is_ams_ht),[N]),D=y.useMemo(()=>{const se={};if(!p||!x)return se;for(const fe of T)for(let ue=0;ue<(fe.tray?.length??0);ue++){const pe=fe.tray[ue],G=S(fe.id,ue,Zf(pe)?null:pe);G!==null&&(se[`${fe.id}-${ue}`]=G)}return se},[p,x,T,S]),P=y.useRef(void 0),E=s?.tray_now;E!==void 0&&E!==255?P.current=E:E===255&&(P.current=void 0);const z=E!==void 0&&E!==255?E:P.current,I=o?.nozzle_count===2||s?.temperatures?.nozzle_2!==void 0,B=y.useMemo(()=>[...s?.vt_tray??[]].sort((se,fe)=>(se.id??254)-(fe.id??254)),[s?.vt_tray]),R=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,K=y.useRef({});y.useEffect(()=>{s?.ams_extruder_map&&Object.keys(s.ams_extruder_map).length>0&&(K.current=s.ams_extruder_map)},[s?.ams_extruder_map]);const J=s?.ams_extruder_map&&Object.keys(s.ams_extruder_map).length>0?s.ams_extruder_map:K.current,X=y.useCallback(se=>{if(!I)return null;const fe=J[String(se)],ue=se>=128?se-128:se;return(fe!==void 0?fe:ue)===1?"L":"R"},[I,J]),[ce,de]=y.useState(null),[oe,Y]=y.useState(null),[ie,me]=y.useState(null),[he,xe]=y.useState(null),V=y.useCallback((se,fe)=>v?.find(ue=>ue.ams_id===Number(se)&&ue.tray_id===Number(fe)),[v]),Q=y.useCallback((se,fe,ue)=>{if(!p||!x)return;const pe=(ue?.tray_uuid||ue?.tag_uid||Sm(x,se,fe))?.toUpperCase();return pe?p[pe]:void 0},[p,x]),A=at({mutationFn:({printerId:se,amsId:fe,trayId:ue})=>ne.unassignSpool(se,fe,ue),onSuccess:()=>{n.invalidateQueries({queryKey:["spool-assignments",t]}),n.invalidateQueries({queryKey:["spool-assignments"]}),i(a("inventory.unassignSuccess","Spool unassigned"),"success"),Y(null)}}),F=at({mutationFn:se=>ne.unlinkSpool(se),onSuccess:se=>{i(a("spoolman.unlinkSuccess")||se?.message,"success"),n.invalidateQueries({queryKey:["linked-spools"]}),n.invalidateQueries({queryKey:["unlinked-spools"]}),n.invalidateQueries({queryKey:["spoolman-slot-assignments"]}),n.invalidateQueries({queryKey:["spoolman-slot-assignments-all"]}),n.invalidateQueries({queryKey:["spoolman-inventory-spools"]}),Y(null)},onError:se=>{i(se.message||a("spoolman.unlinkFailed"),"error")}}),U=at({mutationFn:se=>ne.unassignSpoolmanSlot(se),onSuccess:()=>{i(a("inventory.unassignSuccess","Spool unassigned"),"success"),n.invalidateQueries({queryKey:["spoolman-slot-assignments"]}),n.invalidateQueries({queryKey:["spoolman-slot-assignments-all"]}),n.invalidateQueries({queryKey:["spoolman-inventory-spools"]}),n.invalidateQueries({queryKey:["unlinked-spools"]}),n.invalidateQueries({queryKey:["linked-spools"]}),Y(null)},onError:se=>{i(se.message||a("inventory.assignFailed","Failed to unassign spool"),"error")}}),$=y.useCallback(se=>z===void 0?null:se<=3&&Math.floor(z/4)===se?z%4:se>=128&&se<=135&&z===ib(se,0,!1)?0:null,[z]),H=y.useCallback((se,fe,ue)=>{const pe=ib(se,fe,!1),G=l?.[pe],L=J[String(se)],ae=se>=128?se-128:se,ge=L!==void 0?L:ae,be={amsId:se,trayId:fe,trayCount:ue&&se>=128?1:4,tray:ue,trayType:ue?.tray_type||void 0,trayColor:ue?.tray_color||void 0,traySubBrands:ue?.tray_sub_brands||void 0,trayInfoIdx:ue?.tray_info_idx||void 0,extruderId:I?ge:void 0,caliIdx:ue?.cali_idx,savedPresetId:G?.preset_id,location:`${iZ(se)} Slot ${fe+1}`};Y(be)},[l,J,I]),le=y.useCallback(se=>{const fe=se.id??254,ue=fe-254,pe=l?.[1020+ue],G={amsId:255,trayId:ue,trayCount:1,tray:Zf(se)?null:se,trayType:se.tray_type||void 0,trayColor:se.tray_color||void 0,traySubBrands:se.tray_sub_brands||void 0,trayInfoIdx:se.tray_info_idx||void 0,extruderId:I?fe===254?1:0:void 0,caliIdx:se.cali_idx,savedPresetId:pe?.preset_id,location:I?fe===254?"Ext-L":"Ext-R":"External"};Y(G)},[l,I]),O=y.useCallback(()=>{if(!oe)return;const{tray:se,location:fe,...ue}=oe;Y(null),de(ue)},[oe]),q=y.useCallback(()=>{if(!oe||!t)return;const{amsId:se,trayId:fe,trayType:ue,trayColor:pe,location:G}=oe;Y(null),me({printerId:t,amsId:se,trayId:fe,trayInfo:{type:ue||"",material:ue,color:pe?.slice(0,6)||"",location:G}})},[oe,t]),Z=y.useCallback(()=>{if(!oe||!t)return;const{amsId:se,trayId:fe,tray:ue}=oe,pe=(ue?.tray_uuid||ue?.tag_uid||Sm(x,se,fe))?.toUpperCase()||"";Y(null),xe({tagUid:ue?.tag_uid||pe,trayUuid:ue?.tray_uuid||"",printerId:t,amsId:se,trayId:fe})},[oe,t,x]),ee=y.useCallback(()=>{if(!oe||!t)return;const{amsId:se,trayId:fe}=oe;A.mutate({printerId:t,amsId:se,trayId:fe})},[oe,t,A]);y.useEffect(()=>{if(!k&&t){e({type:"warning",message:a("spoolbuddy.ams.printerDisconnected","Printer disconnected")});return}for(const se of N){const fe=se.tray||[];for(let ue=0;ue=0&&pe.remain<15&&pe.tray_type){const G=se.id===254||se.id===255,L=!G&&se.id>=128,ae=yk(se.id,ue,L,G);e({type:"warning",message:`Low Filament: ${pe.tray_type} (${ae}) - ${pe.remain}% remaining`});return}}}e(null)},[N,k,t,e,a]);const re=y.useMemo(()=>{const se=[];for(const fe of j){const ue=fe.tray?.[0]||{id:0,tray_color:null,tray_type:"",tray_sub_brands:null,tray_id_name:null,tray_info_idx:null,remain:-1,k:null,cali_idx:null,tag_uid:null,tray_uuid:null,nozzle_temp_min:null,nozzle_temp_max:null},pe=S(fe.id,0,Zf(ue)?null:ue),G=b[`${fe.id}-0`]??null,L=ue.remain!=null&&ue.remain>=0?ue.remain:null,ae=G===0&&L!==null&&L>0?null:G;se.push({key:`ht-${fe.id}`,label:iZ(fe.id),tray:ue,isEmpty:Zf(ue),isActive:$(fe.id)===0,temp:fe.temp,humidity:fe.humidity,nozzleSide:X(fe.id),effectiveFill:pe??ae??L,onClick:()=>H(fe.id,0,Zf(ue)?null:ue)})}for(const fe of B){const ue=fe.id??254,pe=I&&z===254?ue===254&&s?.active_extruder===1||ue===255&&s?.active_extruder===0:z===ue,G=ue-254,L=S(255,G,Zf(fe)?null:fe),ae=b[`255-${G}`]??null,ge=fe.remain!=null&&fe.remain>=0?fe.remain:null,be=ae===0&&ge!==null&&ge>0?null:ae;se.push({key:`ext-${ue}`,label:I?ue===254?a("printers.extL","Ext-L"):a("printers.extR","Ext-R"):a("printers.ext","Ext"),tray:fe,isEmpty:Zf(fe),isActive:pe,nozzleSide:null,effectiveFill:L??be??ge,onClick:()=>le(fe)})}return se},[j,B,I,z,s?.active_extruder,a,$,X,H,le,b,S]);return r.jsxs("div",{className:"h-full flex flex-col p-4",children:[r.jsx("div",{className:"flex-1 min-h-0",children:t?k?N.length===0&&B.length===0?r.jsx("div",{className:"flex-1 flex items-center justify-center h-full",children:r.jsxs("div",{className:"text-center text-white/50",children:[r.jsx(tn,{className:"w-12 h-12 mx-auto mb-3 opacity-50"}),r.jsx("p",{className:"text-lg mb-2",children:a("spoolbuddy.ams.noData","No AMS detected")}),r.jsx("p",{className:"text-sm",children:a("spoolbuddy.ams.connectAms","Connect an AMS to see filament slots")})]})}):r.jsxs("div",{className:"flex flex-col gap-3 h-full",children:[r.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:T.map(se=>r.jsx(Gde,{unit:se,activeSlot:$(se.id),onConfigureSlot:H,isDualNozzle:I,nozzleSide:X(se.id),thresholds:R,fillOverrides:b,spoolmanFillOverrides:D},se.id))}),re.length>0&&r.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:re.map(({key:se,label:fe,tray:ue,isEmpty:pe,isActive:G,temp:L,humidity:ae,nozzleSide:ge,effectiveFill:be,onClick:ve})=>{const De=Vlt(ue.tray_color);return r.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 ${G?"ring-2 ring-bambu-green":""}`,onClick:ve,children:[r.jsxs("div",{className:"relative w-10 h-10 flex-shrink-0",children:[pe?r.jsx("div",{className:"w-full h-full rounded-full border-2 border-dashed border-gray-500 flex items-center justify-center",children:r.jsx("div",{className:"w-1.5 h-1.5 rounded-full bg-gray-600"})}):r.jsxs("svg",{viewBox:"0 0 56 56",className:"w-full h-full",children:[r.jsx("circle",{cx:"28",cy:"28",r:"26",fill:De}),r.jsx("circle",{cx:"28",cy:"28",r:"20",fill:De,style:{filter:"brightness(0.85)"}}),r.jsx("ellipse",{cx:"20",cy:"20",rx:"6",ry:"4",fill:"white",opacity:"0.3"}),r.jsx("circle",{cx:"28",cy:"28",r:"8",fill:"#2d2d2d"}),r.jsx("circle",{cx:"28",cy:"28",r:"5",fill:"#1a1a1a"})]}),G&&r.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"})]}),r.jsxs("div",{className:"min-w-0",children:[r.jsxs("div",{className:"flex items-center gap-1",children:[r.jsx("span",{className:"text-xs text-white/50 font-medium truncate",children:fe}),ge&&r.jsx(A5,{side:ge})]}),r.jsx("div",{className:"text-sm text-white/80 truncate",children:pe?"Empty":ue.tray_type||"?"}),(L!=null||ae!=null)&&r.jsxs("div",{className:"flex items-center gap-1.5",children:[L!=null&&r.jsx(Vde,{temp:L,goodThreshold:R?.tempGood,fairThreshold:R?.tempFair}),ae!=null&&r.jsx(qde,{humidity:ae,goodThreshold:R?.humidityGood,fairThreshold:R?.humidityFair})]})]}),!pe&&be!=null&&be>=0&&r.jsx("div",{className:"w-1.5 h-8 bg-bambu-dark-tertiary rounded-full overflow-hidden flex-shrink-0 flex flex-col-reverse",children:r.jsx("div",{className:"w-full rounded-full",style:{height:`${be}%`,backgroundColor:by(be)}})})]},se)})})]}):r.jsx("div",{className:"flex-1 flex items-center justify-center h-full",children:r.jsx("div",{className:"text-center text-white/50",children:r.jsx("p",{className:"text-lg mb-2",children:a("spoolbuddy.ams.printerDisconnected","Printer disconnected")})})}):r.jsx("div",{className:"flex-1 flex items-center justify-center h-full",children:r.jsxs("div",{className:"text-center text-white/50",children:[r.jsx("p",{className:"text-lg mb-2",children:a("spoolbuddy.ams.noPrinter","No printer selected")}),r.jsx("p",{className:"text-sm",children:a("spoolbuddy.ams.selectPrinter","Select a printer from the top bar")})]})})}),ce&&t&&r.jsx(Mse,{isOpen:!!ce,onClose:()=>de(null),printerId:t,slotInfo:ce,printerModel:qlt(o?.model??null)||void 0,fullScreen:!0,onSuccess:()=>{n.invalidateQueries({queryKey:["slotPresets",t]}),n.invalidateQueries({queryKey:["printerStatus",t]})}}),oe&&t&&(()=>{const se=V(oe.amsId,oe.trayId),fe=Q(oe.amsId,oe.trayId,oe.tray),ue=u?f.find(G=>G.printer_id===t&&G.ams_id===oe.amsId&&G.tray_id===oe.trayId):void 0,pe=ue?g.find(G=>G.id===ue.spoolman_spool_id)??null:null;return r.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[r.jsx("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-sm",onClick:()=>Y(null)}),r.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:[r.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[oe.trayColor&&r.jsx("span",{className:"w-4 h-4 rounded-full border border-black/20",style:{backgroundColor:`#${oe.trayColor.slice(0,6)}`}}),r.jsx("h2",{className:"text-lg font-semibold text-white",children:oe.location}),oe.traySubBrands&&r.jsxs("span",{className:"text-sm text-bambu-gray",children:["(",oe.traySubBrands,")"]})]}),r.jsx("button",{onClick:()=>Y(null),className:"p-1 text-bambu-gray hover:text-white rounded transition-colors",children:r.jsx(Ht,{className:"w-5 h-5"})})]}),r.jsxs("div",{className:"p-4 space-y-2",children:[!u&&se?.spool&&r.jsxs("div",{className:"p-2.5 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary mb-3",children:[r.jsx("p",{className:"text-xs text-bambu-gray mb-1",children:a("inventory.assignedSpool","Assigned spool")}),r.jsxs("div",{className:"flex items-center gap-2",children:[se.spool.rgba&&r.jsx("span",{className:"w-3 h-3 rounded-full border border-black/20 flex-shrink-0",style:al(se.spool.rgba)}),r.jsxs("span",{className:"text-sm text-white",children:[se.spool.brand?`${se.spool.brand} `:"",se.spool.material,se.spool.color_name?` - ${se.spool.color_name}`:""]}),r.jsxs("span",{className:"text-[10px] font-mono text-zinc-500 shrink-0 ml-auto",children:["#",se.spool.id]})]})]}),u&&fe&&!pe&&r.jsxs("div",{className:"p-2.5 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary mb-3",children:[r.jsx("p",{className:"text-xs text-bambu-gray mb-1",children:a("spoolman.linkedSpool","Linked spool")}),r.jsx("div",{className:"flex items-center gap-2",children:r.jsxs("span",{className:"text-sm text-white",children:["Spoolman #",fe.id,fe.remaining_weight!=null?` (${Math.round(fe.remaining_weight)}g)`:""]})})]}),u&&pe&&r.jsxs("div",{className:"p-2.5 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary mb-3",children:[r.jsx("p",{className:"text-xs text-bambu-gray mb-1",children:a("inventory.assignedSpool","Assigned spool")}),r.jsxs("div",{className:"flex items-center gap-2",children:[pe.rgba&&r.jsx("span",{className:"w-3 h-3 rounded-full border border-black/20 flex-shrink-0",style:al(pe.rgba)}),r.jsxs("span",{className:"text-sm text-white",children:[pe.brand?`${pe.brand} `:"",pe.material,pe.color_name?` - ${pe.color_name}`:""]})]})]}),r.jsxs("button",{onClick:O,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:[r.jsx(xd,{className:"w-5 h-5 text-bambu-blue flex-shrink-0"}),r.jsxs("div",{children:[r.jsx("p",{className:"text-white font-medium",children:a("configureAmsSlot.title")}),r.jsx("p",{className:"text-xs text-bambu-gray",children:a("spoolbuddy.ams.configureDesc","Set filament preset, K-profile, and color")})]})]}),!u&&(Qs(oe?.tray)?null:se?r.jsxs("button",{onClick:ee,disabled:A.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:[r.jsx(pu,{className:"w-5 h-5 text-amber-400 flex-shrink-0"}),r.jsxs("div",{children:[r.jsx("p",{className:"text-amber-400 font-medium",children:a("inventory.unassignSpool","Unassign")}),r.jsx("p",{className:"text-xs text-bambu-gray",children:a("spoolbuddy.ams.unassignDesc","Remove inventory spool from this slot")})]})]}):r.jsxs("button",{onClick:q,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:[r.jsx(Kr,{className:"w-5 h-5 text-bambu-green flex-shrink-0"}),r.jsxs("div",{children:[r.jsx("p",{className:"text-white font-medium",children:a("inventory.assignSpool")}),r.jsx("p",{className:"text-xs text-bambu-gray",children:a("spoolbuddy.ams.assignDesc","Track a spool from your inventory")})]})]})),u&&(fe?.id?r.jsxs("button",{onClick:()=>F.mutate(fe.id),disabled:F.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:[r.jsx(pu,{className:"w-5 h-5 text-amber-400 flex-shrink-0"}),r.jsxs("div",{children:[r.jsx("p",{className:"text-amber-400 font-medium",children:a("inventory.unassignSpool")}),r.jsx("p",{className:"text-xs text-bambu-gray",children:a("spoolbuddy.ams.unlinkDesc","Remove Spoolman link from this slot")})]})]}):pe?r.jsxs("button",{onClick:()=>U.mutate(pe.id),disabled:U.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:[r.jsx(pu,{className:"w-5 h-5 text-amber-400 flex-shrink-0"}),r.jsxs("div",{children:[r.jsx("p",{className:"text-amber-400 font-medium",children:a("inventory.unassignSpool")}),r.jsx("p",{className:"text-xs text-bambu-gray",children:a("spoolbuddy.ams.unassignDesc","Remove inventory spool from this slot")})]})]}):r.jsxs("button",{onClick:Z,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:[r.jsx(Ih,{className:"w-5 h-5 text-bambu-green flex-shrink-0"}),r.jsxs("div",{children:[r.jsx("p",{className:"text-white font-medium",children:a("inventory.assignSpool")}),r.jsx("p",{className:"text-xs text-bambu-gray",children:a("spoolbuddy.ams.linkDesc","Link a Spoolman spool to this slot")})]})]}))]})]})]})})(),ie&&r.jsx(yse,{isOpen:!!ie,onClose:()=>{me(null),n.invalidateQueries({queryKey:["spool-assignments",t]}),n.invalidateQueries({queryKey:["spool-assignments"]})},printerId:ie.printerId,amsId:ie.amsId,trayId:ie.trayId,trayInfo:ie.trayInfo,spoolmanEnabled:!!u}),he&&r.jsx(xse,{isOpen:!!he,onClose:()=>xe(null),tagUid:he.tagUid,trayUuid:he.trayUuid,printerId:he.printerId,amsId:he.amsId,trayId:he.trayId})]})}function $lt({type:t,deviceId:e,onClose:a}){const{t:n}=wt(),[i,s]=y.useState(!1),[o,l]=y.useState(""),[c,d]=y.useState(""),[u,m]=y.useState(!1);y.useEffect(()=>{const g=v=>{v.key==="Escape"&&!i&&a()};return window.addEventListener("keydown",g),()=>window.removeEventListener("keydown",g)},[i,a]);const p=y.useCallback(async()=>{s(!0),l(""),d(""),m(!0);try{l(n("spoolbuddy.diagnostic.queuing",`Queuing diagnostic on device... +${s("inventory.assignReconfigureNote")}`,r.jsx(ka,{title:s("inventory.assignMismatchTitle"),message:A,confirmText:s("inventory.assignMismatchConfirm"),variant:"warning",isLoading:de.isPending,onConfirm:xe,onCancel:()=>{de.isPending||(p(!1),b(null),g(null))}})})()]})}function Ilt({isOpen:t,onClose:e,tagId:a,untaggedSpools:n,onLink:i}){const{t:s}=wt(),[o,l]=y.useState(null),c=y.useCallback(()=>{l(null),e()},[e]),d=y.useCallback(m=>{m.key==="Escape"&&c()},[c]);if(y.useEffect(()=>(t&&(document.addEventListener("keydown",d),document.body.style.overflow="hidden"),()=>{document.removeEventListener("keydown",d),document.body.style.overflow=""}),[t,d]),!t)return null;const u=()=>{o&&(i(o),l(null))};return r.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/70 animate-fade-in",onClick:c,children:r.jsxs("div",{className:"bg-zinc-800 rounded-xl shadow-2xl w-full max-w-lg mx-4 animate-slide-up",onClick:m=>m.stopPropagation(),children:[r.jsxs("div",{className:"flex items-center justify-between px-5 py-4 border-b border-zinc-700",children:[r.jsxs("div",{children:[r.jsx("h2",{className:"text-base font-semibold text-zinc-100",children:s("spoolbuddy.dashboard.linkTagTitle","Link Tag to Spool")}),r.jsx("p",{className:"text-sm text-zinc-500 font-mono",children:a})]}),r.jsx("button",{onClick:c,className:"p-2 rounded-lg text-zinc-500 hover:text-zinc-300 hover:bg-zinc-700 transition-colors",children:r.jsx(Ht,{className:"w-5 h-5"})})]}),r.jsxs("div",{className:"px-5 py-4 space-y-3 max-h-[400px] overflow-y-auto",children:[r.jsx("p",{className:"text-sm text-zinc-400",children:s("spoolbuddy.dashboard.selectSpool","Select a spool to link this tag to:")}),n.length===0?r.jsx("div",{className:"text-center py-8 text-zinc-500",children:s("spoolbuddy.dashboard.noUntagged","No spools without tags found")}):r.jsx("div",{className:"space-y-2",children:n.map(m=>r.jsxs("button",{type:"button",onClick:()=>l(m),className:`w-full flex items-center gap-3 p-3 rounded-lg border-2 transition-all text-left ${o?.id===m.id?"border-green-500 bg-green-500/10":"border-zinc-700 hover:border-green-500/50 hover:bg-zinc-700/50"}`,children:[r.jsx(vj,{color:B1(m.rgba),isEmpty:!1,size:40}),r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("div",{className:"font-medium text-zinc-100 truncate",children:m.color_name||"Unknown color"}),r.jsxs("span",{className:"text-[10px] font-mono text-zinc-500 shrink-0",children:["#",m.id]})]}),r.jsxs("div",{className:"text-sm text-zinc-400 truncate",children:[m.brand," • ",m.material,m.subtype&&` ${m.subtype}`]})]}),r.jsxs("div",{className:"text-sm font-mono text-zinc-500",children:[Math.max(0,m.label_weight-m.weight_used),"g"]})]},m.id))})]}),r.jsxs("div",{className:"flex justify-end gap-2 px-5 py-4 border-t border-zinc-700",children:[r.jsx("button",{onClick:c,className:"px-4 py-2.5 rounded-lg text-sm font-medium bg-zinc-700 text-zinc-300 hover:bg-zinc-600 transition-colors min-h-[44px]",children:s("common.cancel","Cancel")}),r.jsx("button",{onClick:u,disabled:!o,className:"px-4 py-2.5 rounded-lg text-sm font-medium bg-green-600 text-white hover:bg-green-700 disabled:opacity-40 disabled:cursor-not-allowed transition-colors min-h-[44px]",children:s("spoolbuddy.dashboard.linkTag","Link Tag")})]})]})})}function rZ(t){return t?t.replace(/[^0-9a-f]/gi,"").toUpperCase():""}function Olt(t,e){const a=rZ(t),n=rZ(e);return!a||!n?!1:a===n?!0:a.endsWith(n)||n.endsWith(a)}const nZ=["#00AE42","#FF6B35","#3B82F6","#EF4444","#A855F7","#FBBF24","#14B8A6","#EC4899","#F97316","#22C55E"];function Blt(){const{t}=wt(),[e,a]=y.useState(0);y.useEffect(()=>{const i=setInterval(()=>{a(s=>(s+1)%nZ.length)},5e3);return()=>clearInterval(i)},[]);const n=nZ[e];return r.jsxs("div",{className:"flex flex-col items-center text-center",children:[r.jsxs("div",{className:"relative mb-6 flex items-center justify-center",style:{width:160,height:160},children:[r.jsx("div",{className:"absolute inset-0 flex items-center justify-center pointer-events-none",children:[0,1].map(i=>r.jsx("div",{className:"absolute rounded-full border spoolbuddy-optimized-ping",style:{width:80,height:80,borderColor:`${n}4D`,transition:"border-color 140ms linear",animationDelay:`${i*.8}s`}},i))}),r.jsxs("div",{className:"relative overflow-hidden rounded-full",children:[r.jsx("div",{className:"absolute inset-0 rounded-full opacity-30 spoolbuddy-spool-glow",style:{background:`radial-gradient(circle, ${n} 0%, transparent 70%)`}}),r.jsx("div",{className:"relative",style:{transition:"opacity 140ms linear"},children:r.jsx(vj,{color:n,isEmpty:!1,size:100})})]})]}),r.jsxs("div",{className:"space-y-2",children:[r.jsx("p",{className:"text-xl font-medium text-zinc-300",children:t("spoolbuddy.dashboard.readyToScan","Ready to scan")}),r.jsx("p",{className:"text-sm text-zinc-500",children:t("spoolbuddy.dashboard.idleMessage","Place a spool on the scale to identify it")})]}),r.jsxs("div",{className:"mt-6 flex items-center gap-2 text-sm text-zinc-600",children:[r.jsx("svg",{className:"w-4 h-4",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:r.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"})}),r.jsx("span",{children:t("spoolbuddy.dashboard.nfcHint","NFC tag will be read automatically")})]})]})}function Ult(){const{t}=wt();return r.jsxs("div",{className:"flex flex-col items-center text-center",children:[r.jsx("div",{className:"relative mb-6 flex items-center justify-center",style:{width:160,height:160},children:r.jsx("div",{className:"w-24 h-24 rounded-full bg-zinc-800 flex items-center justify-center",children:r.jsx("svg",{className:"w-12 h-12 text-zinc-600",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:r.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"})})})}),r.jsxs("div",{className:"space-y-2",children:[r.jsx("p",{className:"text-lg font-medium text-zinc-500",children:t("spoolbuddy.status.deviceOffline","Device Offline")}),r.jsx("p",{className:"text-sm text-zinc-600",children:t("spoolbuddy.status.connectDisplay","Connect the SpoolBuddy display to scan spools")})]}),r.jsxs("div",{className:"mt-6 flex items-center gap-2 text-xs text-zinc-600",children:[r.jsx("svg",{className:"w-4 h-4",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:r.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"})}),r.jsx("span",{children:t("spoolbuddy.status.waitingConnection","Waiting for device connection...")})]})]})}function Hlt(){const{sbState:t,selectedPrinterId:e}=Jy(),{t:a}=wt(),{showToast:n}=oa(),{data:i}=$e({queryKey:["spoolman-settings"],queryFn:ne.getSpoolmanSettings,staleTime:300*1e3}),s=i?.spoolman_enabled==="true"&&!!i?.spoolman_url,{data:o=[],refetch:l}=$e({queryKey:s?["spoolman-inventory-spools"]:["inventory-spools"],queryFn:()=>s?ne.getSpoolmanInventorySpools(!1):ne.getSpools(!1),enabled:i!==void 0}),{data:c=[]}=$e({queryKey:["spoolman-slot-assignments"],queryFn:()=>ne.getSpoolmanSlotAssignments(),enabled:s,staleTime:3*1e3,refetchInterval:3*1e3,refetchIntervalInBackground:!1}),{data:d=[]}=$e({queryKey:["printers"],queryFn:()=>ne.getPrinters()}),u=df({queries:d.map(le=>({queryKey:["printerStatus",le.id],queryFn:()=>ne.getPrinterStatus(le.id),refetchInterval:1e4,select:O=>({connected:O?.connected,awaiting_plate_clear:O?.awaiting_plate_clear===!0})}))}),m=d.map((le,O)=>({printer:le,pending:u[O]?.data?.awaiting_plate_clear===!0})).filter(le=>le.pending),p=na(),f=at({mutationFn:le=>ne.clearPlate(le),onSuccess:(le,O)=>{p.setQueryData(["printerStatus",O],q=>q&&{...q,awaiting_plate_clear:!1}),n(a("spoolbuddy.dashboard.plateClearedToast","Plate marked as cleared"),"success")},onError:()=>{n(a("spoolbuddy.dashboard.plateClearFailed","Could not mark plate as cleared"),"error")}}),g=at({mutationFn:le=>ne.unassignSpoolmanSlot(le),onSuccess:()=>{p.invalidateQueries({queryKey:["spoolman-slot-assignments"]}),p.invalidateQueries({queryKey:["spoolman-inventory-spools"]})},onError:()=>n(a("inventory.unassignFailed","Failed to unassign spool"),"error")}),[v,b]=y.useState(null),[x,S]=y.useState(null),[k,C]=y.useState(null),[N,T]=y.useState(!1),[j,D]=y.useState(!1),[P,E]=y.useState(!1),[z,I]=y.useState(!1),[B,R]=y.useState(null),K=t.matchedSpool?.tag_uid??t.unknownTagUid??null,J=t.weight,X=t.weightStable,ce=y.useRef(null);J===null?ce.current=null:(ce.current===null||Math.abs(J-ce.current)>=3||X)&&(ce.current=J);const oe=ce.current,Y=y.useMemo(()=>{if(t.matchedSpool?.id){const O=o.find(q=>q.id===t.matchedSpool?.id);if(O)return O}if(!v)return null;const le=o.find(O=>Olt(O.tag_uid,v));return le||B||null},[v,t.matchedSpool,o,B]),ie=y.useMemo(()=>{if(Y&&!B)return Y;const le=t.matchedSpool;return le?{id:le.id,tag_uid:le.tag_uid,material:le.material,subtype:le.subtype,color_name:le.color_name,rgba:le.rgba,brand:le.brand,label_weight:le.label_weight,core_weight:le.core_weight,weight_used:le.weight_used}:null},[Y,B,t.matchedSpool]),me=s&&ie!=null?c.some(le=>le.spoolman_spool_id===ie.id):!1,he=y.useMemo(()=>s?o.filter(le=>!le.tag_uid&&!le.tray_uuid&&!le.archived_at):o.filter(le=>!le.tag_uid&&!le.archived_at),[o,s]);y.useEffect(()=>{if(K){const le=k===K;(v!==null&&v!==K||!le&&v!==K)&&(b(K),S(null),C(null),R(null)),!le&&J!==null&&X&&S(Math.round(Math.max(0,J)))}else k&&(b(null),C(null),S(null),R(null))},[K,J,X,v,k]);const xe=()=>{C(v)},V=async le=>{if(v)try{if(s){const O=t.unknownTagUid||void 0,q=!t.unknownTagUid&&t.unknownTrayUuid?t.unknownTrayUuid:void 0;if(!O&&!q){n(a("spoolman.linkFailed"),"error");return}const ee=await ne.linkTagToSpoolmanSpool(le.id,{tray_uuid:q,tag_uid:O});if(!ee){n(a("spoolman.linkFailed"),"error");return}const{id:re,material:se,subtype:fe,color_name:ue,rgba:pe,brand:G,label_weight:L,core_weight:ae,weight_used:ge}=ee;R({id:re,material:se,subtype:fe,color_name:ue,rgba:pe,brand:G,label_weight:L,core_weight:ae,weight_used:ge}),n(a("spoolman.linkSuccess"),"success")}else await ne.linkTagToSpool(le.id,{tag_uid:v,tag_type:"generic",data_origin:"nfc_link"});l()}catch(O){console.error("Failed to link tag:",O),n(a("spoolman.linkFailed"),"error")}finally{T(!1)}},Q=async()=>{if(v){I(!0);try{const le=F??x;if(s){const O=await ne.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:le!==null?Math.round(le):null,last_weighed_at:le!==null?new Date().toISOString():null,category:null,low_stock_threshold_pct:null});await ne.linkTagToSpoolmanSpool(O.id,{tag_uid:t.unknownTagUid||void 0,tray_uuid:!t.unknownTagUid&&t.unknownTrayUuid?t.unknownTrayUuid:void 0})}else await ne.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:v,tray_uuid:null,data_origin:"spoolbuddy",tag_type:"generic",cost_per_kg:null,last_scale_weight:le!==null?Math.round(le):null,last_weighed_at:le!==null?new Date().toISOString():null,category:null,low_stock_threshold_pct:null})}catch(le){const O=le instanceof Error?le.message:String(le);console.error("Failed to quick-add spool:",O),n(O||a("spoolbuddy.errors.quickAddFailed","Failed to add spool"),"error")}finally{E(!1),I(!1),l()}}},F=J!==null&&(K===v||K===null&&v!==null)?J:null,U=o.length,$=new Set(o.map(le=>le.material)).size,H=new Set(o.filter(le=>le.brand).map(le=>le.brand)).size;return r.jsxs("div",{className:"h-full flex flex-col p-4",children:[r.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:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("span",{className:"text-xl font-bold text-zinc-100",children:U}),r.jsx("span",{className:"text-sm text-zinc-500",children:a("spoolbuddy.inventory.spools","Spools")})]}),r.jsx("div",{className:"w-px h-5 bg-zinc-700"}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("span",{className:"text-xl font-bold text-zinc-100",children:$}),r.jsx("span",{className:"text-sm text-zinc-500",children:a("spoolbuddy.spool.material","Materials")})]}),r.jsx("div",{className:"w-px h-5 bg-zinc-700"}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("span",{className:"text-xl font-bold text-zinc-100",children:H}),r.jsx("span",{className:"text-sm text-zinc-500",children:a("spoolbuddy.spool.brand","Brands")})]})]}),r.jsxs("div",{className:"flex-1 flex gap-4 min-h-0",children:[r.jsxs("div",{className:"w-5/12 flex flex-col min-h-0",children:[r.jsxs("div",{className:"border border-dashed border-zinc-700/50 rounded-xl p-4",children:[r.jsx("h2",{className:"text-sm font-semibold text-zinc-400 uppercase tracking-wide mb-3",children:a("spoolbuddy.dashboard.device","Device")}),r.jsxs("div",{className:"space-y-2.5",children:[r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("div",{className:`w-2.5 h-2.5 rounded-full ${t.deviceOnline?"bg-green-500":"bg-red-500"}`}),r.jsx("span",{className:"text-base text-zinc-400",children:t.deviceOnline?a("spoolbuddy.status.online","Online"):a("spoolbuddy.status.offline","Disconnected")})]}),r.jsxs("div",{className:"flex items-center justify-between p-3 bg-zinc-800/50 rounded-lg",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("svg",{className:`w-4 h-4 ${t.deviceOnline?"text-green-500":"text-zinc-500"}`,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:r.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"})}),r.jsx("span",{className:"text-sm text-zinc-500",children:a("spoolbuddy.spool.scaleWeight","Scale")})]}),r.jsx("span",{className:"text-lg font-mono font-semibold text-zinc-100",children:oe!==null?`${Math.abs(oe)<=20?0:Math.round(Math.max(0,oe))}g`:"—"})]}),r.jsxs("div",{className:"flex items-center justify-between p-3 bg-zinc-800/50 rounded-lg",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("svg",{className:`w-4 h-4 ${t.deviceOnline?"text-green-500":"text-zinc-500"}`,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:r.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"})}),r.jsx("span",{className:"text-sm text-zinc-500",children:"NFC"})]}),r.jsx("span",{className:`text-sm font-medium ${K?"text-green-500":"text-zinc-500"}`,children:K?a("spoolbuddy.dashboard.tagDetected","Tag detected"):a("spoolbuddy.dashboard.noTag","No tag")})]})]})]}),d.length>0&&r.jsxs("div",{className:"mt-3 border border-dashed border-zinc-700/50 rounded-xl p-4",children:[r.jsx("h2",{className:"text-sm font-semibold text-zinc-400 uppercase tracking-wide mb-2.5",children:a("spoolbuddy.dashboard.printers","Printers")}),r.jsx("div",{className:"flex flex-wrap gap-2 overflow-hidden",children:d.map((le,O)=>{const q=u[O]?.data?.connected??!1;return r.jsxs("div",{className:"flex items-center gap-1.5 px-2.5 py-1 bg-zinc-800/50 rounded-lg",title:`${le.name} — ${q?"Online":"Offline"}`,children:[r.jsx("div",{className:`w-2 h-2 rounded-full shrink-0 ${q?"bg-green-500":"bg-zinc-600"}`}),r.jsx("span",{className:"text-xs text-zinc-400 truncate max-w-[100px]",children:le.name})]},le.id)})}),m.length>0&&r.jsx("div",{className:"mt-2 flex flex-wrap gap-2","data-testid":"plate-clear-section","aria-label":a("spoolbuddy.dashboard.plateReadyLabel","Plates ready to clear"),children:m.map(({printer:le})=>r.jsxs("button",{type:"button",onClick:()=>f.mutate(le.id),disabled:f.isPending,"data-testid":`plate-clear-button-${le.id}`,title:a("spoolbuddy.dashboard.plateReady","Plate ready: {{name}}",{name:le.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:[r.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:[r.jsx("path",{d:"M12 9v4"}),r.jsx("path",{d:"M12 17h.01"}),r.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"})]}),r.jsx("span",{className:"text-xs truncate max-w-[100px]",children:le.name}),r.jsx("span",{className:"text-xs opacity-70","aria-hidden":"true",children:"·"}),r.jsx("span",{className:"text-xs font-medium",children:a("spoolbuddy.dashboard.plateClearAction","Clear")})]},le.id))})]})]}),r.jsx("div",{className:"w-7/12 min-h-0",children:r.jsxs("div",{className:"border border-dashed border-zinc-700/50 rounded-xl p-6 h-full flex flex-col",children:[r.jsx("h2",{className:"text-sm font-semibold text-zinc-400 uppercase tracking-wide mb-4 shrink-0",children:a("spoolbuddy.dashboard.currentSpool","Current Spool")}),r.jsx("div",{className:"flex-1 flex items-center justify-center min-h-0",children:t.deviceOnline?(Y||t.matchedSpool)&&v&&k!==v?r.jsx(klt,{spool:(()=>{const le=Y??t.matchedSpool;return{id:le.id,tag_uid:v,material:le.material,subtype:le.subtype,color_name:le.color_name,rgba:le.rgba,brand:le.brand,label_weight:le.label_weight,core_weight:le.core_weight,weight_used:le.weight_used}})(),scaleWeight:F??x,onSyncWeight:()=>l(),onAssignToAms:()=>D(!0),isAssigned:me,onUnassignFromAms:me&&Y?.id!=null?()=>g.mutate(Y.id):void 0,onClose:xe}):K&&v&&!Y&&!t.matchedSpool&&k!==v?r.jsx(_lt,{tagUid:v,scaleWeight:F??x,onLinkSpool:he.length>0?()=>T(!0):void 0,onAddToInventory:()=>E(!0),onClose:xe}):r.jsx(Blt,{}):r.jsx(Ult,{})})]})})]}),ie&&!B&&v&&r.jsx($de,{isOpen:j,onClose:()=>D(!1),spool:ie,printerId:e,spoolmanMode:s}),v&&r.jsx(Ilt,{isOpen:N,onClose:()=>T(!1),tagId:v,untaggedSpools:he,onLink:V}),P&&v&&r.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/60",children:r.jsxs("div",{className:"bg-zinc-800 rounded-2xl p-6 mx-4 max-w-sm w-full border border-zinc-700",children:[r.jsx("h3",{className:"text-lg font-semibold text-zinc-100 mb-3",children:a("spoolbuddy.modal.addToInventory","Add to Inventory")}),r.jsxs("div",{className:"flex gap-2.5 p-3 bg-amber-500/10 border border-amber-500/20 rounded-lg mb-4",children:[r.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:r.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"})}),r.jsx("p",{className:"text-sm text-amber-200/80",children:a("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.')})]}),r.jsx("p",{className:"text-sm text-zinc-400 mb-1",children:a("spoolbuddy.modal.quickAddDesc","This will create a basic PLA spool entry with this NFC tag. You can edit the details later in Bambuddy.")}),r.jsx("p",{className:"text-xs text-zinc-500 font-mono mb-5",children:v}),r.jsxs("div",{className:"flex gap-3",children:[r.jsx("button",{onClick:()=>E(!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:a("common.cancel","Cancel")}),r.jsx("button",{onClick:Q,disabled:z,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:z?a("common.saving","Saving..."):a("spoolbuddy.modal.addAnyway","Add Anyway")})]})]})})]})}function iZ(t){return t<=3?`AMS ${String.fromCharCode(65+t)}`:t>=128&&t<=135?`AMS HT ${String.fromCharCode(65+t-128)}`:`AMS ${t}`}function qlt(t){return t?{O1D:"H2D",O1E:"H2D Pro",O2D:"H2D Pro",O1C:"H2C",O1C2:"H2C",O1S:"H2S","BL-P001":"X1C","BL-P002":"X1","BL-P003":"X1E",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"}[t]||t:""}function Zf(t){return!t.tray_type||t.tray_type===""}function Vlt(t){return t?`#${t.slice(0,6)}`:"#808080"}function Glt(){const{selectedPrinterId:t,setAlert:e}=Jy(),{t:a}=wt(),n=na(),{showToast:i}=oa(),{data:s}=$e({queryKey:["printerStatus",t],queryFn:()=>ne.getPrinterStatus(t),enabled:t!==null,staleTime:30*1e3}),{data:o}=$e({queryKey:["printer",t],queryFn:()=>ne.getPrinter(t),enabled:t!==null,staleTime:60*1e3}),{data:l}=$e({queryKey:["slotPresets",t],queryFn:()=>ne.getSlotPresets(t),enabled:t!==null,staleTime:120*1e3}),{data:c}=$e({queryKey:["settings"],queryFn:()=>ne.getSettings(),staleTime:300*1e3}),{data:d}=$e({queryKey:["spoolman-status"],queryFn:ne.getSpoolmanStatus,staleTime:60*1e3}),u=d?.enabled&&d?.connected,{data:m}=$e({queryKey:["linked-spools"],queryFn:ne.getLinkedSpools,enabled:!!u,staleTime:30*1e3}),p=m?.linked,{data:f=[]}=$e({queryKey:["spoolman-slot-assignments-all"],queryFn:()=>ne.getSpoolmanSlotAssignments(),enabled:!!u,staleTime:30*1e3}),{data:g=[]}=$e({queryKey:["spoolman-inventory-spools"],queryFn:()=>ne.getSpoolmanInventorySpools(!1),enabled:!!u,staleTime:30*1e3}),{data:v}=$e({queryKey:["spool-assignments",t],queryFn:()=>ne.getAssignments(t),enabled:t!==null,staleTime:30*1e3}),b=y.useMemo(()=>{const se={};if(!v)return se;for(const fe of v){const ue=fe.spool;if(ue&&ue.label_weight>0&&ue.weight_used!=null){const pe=Math.round(Math.max(0,ue.label_weight-ue.weight_used)/ue.label_weight*100);se[`${fe.ams_id}-${fe.tray_id}`]=pe}}return se},[v]),x=o?.serial_number??"",S=y.useCallback((se,fe,ue)=>{if(t!==null&&f.length&&g.length){const pe=f.find(G=>G.printer_id===t&&G.ams_id===se&&G.tray_id===fe);if(pe){const G=g.find(L=>L.id===pe.spoolman_spool_id);if(G&&(G.label_weight??0)>0)return Math.round(Math.max(0,G.label_weight-G.weight_used)/G.label_weight*100)}}if(p&&x){const pe=(ue?.tray_uuid||ue?.tag_uid||Sm(x,se,fe))?.toUpperCase(),G=pe?p[pe]:void 0,L=GC(G);if(L!==null)return L}return null},[p,x,t,f,g]),k=s?.connected??!1,C=y.useRef({});y.useEffect(()=>{t&&s?.ams&&s.ams.length>0&&(C.current[t]=s.ams)},[s?.ams,t]);const N=y.useMemo(()=>{const se=s?.ams;return se&&se.length>0?se:(t?C.current[t]:null)??[]},[s?.ams,t]),T=y.useMemo(()=>N.filter(se=>!se.is_ams_ht),[N]),j=y.useMemo(()=>N.filter(se=>se.is_ams_ht),[N]),D=y.useMemo(()=>{const se={};if(!p||!x)return se;for(const fe of T)for(let ue=0;ue<(fe.tray?.length??0);ue++){const pe=fe.tray[ue],G=S(fe.id,ue,Zf(pe)?null:pe);G!==null&&(se[`${fe.id}-${ue}`]=G)}return se},[p,x,T,S]),P=y.useRef(void 0),E=s?.tray_now;E!==void 0&&E!==255?P.current=E:E===255&&(P.current=void 0);const z=E!==void 0&&E!==255?E:P.current,I=o?.nozzle_count===2||s?.temperatures?.nozzle_2!==void 0,B=y.useMemo(()=>[...s?.vt_tray??[]].sort((se,fe)=>(se.id??254)-(fe.id??254)),[s?.vt_tray]),R=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,K=y.useRef({});y.useEffect(()=>{s?.ams_extruder_map&&Object.keys(s.ams_extruder_map).length>0&&(K.current=s.ams_extruder_map)},[s?.ams_extruder_map]);const J=s?.ams_extruder_map&&Object.keys(s.ams_extruder_map).length>0?s.ams_extruder_map:K.current,X=y.useCallback(se=>{if(!I)return null;const fe=J[String(se)],ue=se>=128?se-128:se;return(fe!==void 0?fe:ue)===1?"L":"R"},[I,J]),[ce,de]=y.useState(null),[oe,Y]=y.useState(null),[ie,me]=y.useState(null),[he,xe]=y.useState(null),V=y.useCallback((se,fe)=>v?.find(ue=>ue.ams_id===Number(se)&&ue.tray_id===Number(fe)),[v]),Q=y.useCallback((se,fe,ue)=>{if(!p||!x)return;const pe=(ue?.tray_uuid||ue?.tag_uid||Sm(x,se,fe))?.toUpperCase();return pe?p[pe]:void 0},[p,x]),A=at({mutationFn:({printerId:se,amsId:fe,trayId:ue})=>ne.unassignSpool(se,fe,ue),onSuccess:()=>{n.invalidateQueries({queryKey:["spool-assignments",t]}),n.invalidateQueries({queryKey:["spool-assignments"]}),i(a("inventory.unassignSuccess","Spool unassigned"),"success"),Y(null)}}),F=at({mutationFn:se=>ne.unlinkSpool(se),onSuccess:se=>{i(a("spoolman.unlinkSuccess")||se?.message,"success"),n.invalidateQueries({queryKey:["linked-spools"]}),n.invalidateQueries({queryKey:["unlinked-spools"]}),n.invalidateQueries({queryKey:["spoolman-slot-assignments"]}),n.invalidateQueries({queryKey:["spoolman-slot-assignments-all"]}),n.invalidateQueries({queryKey:["spoolman-inventory-spools"]}),Y(null)},onError:se=>{i(se.message||a("spoolman.unlinkFailed"),"error")}}),U=at({mutationFn:se=>ne.unassignSpoolmanSlot(se),onSuccess:()=>{i(a("inventory.unassignSuccess","Spool unassigned"),"success"),n.invalidateQueries({queryKey:["spoolman-slot-assignments"]}),n.invalidateQueries({queryKey:["spoolman-slot-assignments-all"]}),n.invalidateQueries({queryKey:["spoolman-inventory-spools"]}),n.invalidateQueries({queryKey:["unlinked-spools"]}),n.invalidateQueries({queryKey:["linked-spools"]}),Y(null)},onError:se=>{i(se.message||a("inventory.assignFailed","Failed to unassign spool"),"error")}}),$=y.useCallback(se=>z===void 0?null:se<=3&&Math.floor(z/4)===se?z%4:se>=128&&se<=135&&z===ib(se,0,!1)?0:null,[z]),H=y.useCallback((se,fe,ue)=>{const pe=ib(se,fe,!1),G=l?.[pe],L=J[String(se)],ae=se>=128?se-128:se,ge=L!==void 0?L:ae,be={amsId:se,trayId:fe,trayCount:ue&&se>=128?1:4,tray:ue,trayType:ue?.tray_type||void 0,trayColor:ue?.tray_color||void 0,traySubBrands:ue?.tray_sub_brands||void 0,trayInfoIdx:ue?.tray_info_idx||void 0,extruderId:I?ge:void 0,caliIdx:ue?.cali_idx,savedPresetId:G?.preset_id,location:`${iZ(se)} Slot ${fe+1}`};Y(be)},[l,J,I]),le=y.useCallback(se=>{const fe=se.id??254,ue=fe-254,pe=l?.[1020+ue],G={amsId:255,trayId:ue,trayCount:1,tray:Zf(se)?null:se,trayType:se.tray_type||void 0,trayColor:se.tray_color||void 0,traySubBrands:se.tray_sub_brands||void 0,trayInfoIdx:se.tray_info_idx||void 0,extruderId:I?fe===254?1:0:void 0,caliIdx:se.cali_idx,savedPresetId:pe?.preset_id,location:I?fe===254?"Ext-L":"Ext-R":"External"};Y(G)},[l,I]),O=y.useCallback(()=>{if(!oe)return;const{tray:se,location:fe,...ue}=oe;Y(null),de(ue)},[oe]),q=y.useCallback(()=>{if(!oe||!t)return;const{amsId:se,trayId:fe,trayType:ue,trayColor:pe,location:G}=oe;Y(null),me({printerId:t,amsId:se,trayId:fe,trayInfo:{type:ue||"",material:ue,color:pe?.slice(0,6)||"",location:G}})},[oe,t]),Z=y.useCallback(()=>{if(!oe||!t)return;const{amsId:se,trayId:fe,tray:ue}=oe,pe=(ue?.tray_uuid||ue?.tag_uid||Sm(x,se,fe))?.toUpperCase()||"";Y(null),xe({tagUid:ue?.tag_uid||pe,trayUuid:ue?.tray_uuid||"",printerId:t,amsId:se,trayId:fe})},[oe,t,x]),ee=y.useCallback(()=>{if(!oe||!t)return;const{amsId:se,trayId:fe}=oe;A.mutate({printerId:t,amsId:se,trayId:fe})},[oe,t,A]);y.useEffect(()=>{if(!k&&t){e({type:"warning",message:a("spoolbuddy.ams.printerDisconnected","Printer disconnected")});return}for(const se of N){const fe=se.tray||[];for(let ue=0;ue=0&&pe.remain<15&&pe.tray_type){const G=se.id===254||se.id===255,L=!G&&se.id>=128,ae=yk(se.id,ue,L,G);e({type:"warning",message:`Low Filament: ${pe.tray_type} (${ae}) - ${pe.remain}% remaining`});return}}}e(null)},[N,k,t,e,a]);const re=y.useMemo(()=>{const se=[];for(const fe of j){const ue=fe.tray?.[0]||{id:0,tray_color:null,tray_type:"",tray_sub_brands:null,tray_id_name:null,tray_info_idx:null,remain:-1,k:null,cali_idx:null,tag_uid:null,tray_uuid:null,nozzle_temp_min:null,nozzle_temp_max:null},pe=S(fe.id,0,Zf(ue)?null:ue),G=b[`${fe.id}-0`]??null,L=ue.remain!=null&&ue.remain>=0?ue.remain:null,ae=G===0&&L!==null&&L>0?null:G;se.push({key:`ht-${fe.id}`,label:iZ(fe.id),tray:ue,isEmpty:Zf(ue),isActive:$(fe.id)===0,temp:fe.temp,humidity:fe.humidity,nozzleSide:X(fe.id),effectiveFill:pe??ae??L,onClick:()=>H(fe.id,0,Zf(ue)?null:ue)})}for(const fe of B){const ue=fe.id??254,pe=I&&z===254?ue===254&&s?.active_extruder===1||ue===255&&s?.active_extruder===0:z===ue,G=ue-254,L=S(255,G,Zf(fe)?null:fe),ae=b[`255-${G}`]??null,ge=fe.remain!=null&&fe.remain>=0?fe.remain:null,be=ae===0&&ge!==null&&ge>0?null:ae;se.push({key:`ext-${ue}`,label:I?ue===254?a("printers.extL","Ext-L"):a("printers.extR","Ext-R"):a("printers.ext","Ext"),tray:fe,isEmpty:Zf(fe),isActive:pe,nozzleSide:null,effectiveFill:L??be??ge,onClick:()=>le(fe)})}return se},[j,B,I,z,s?.active_extruder,a,$,X,H,le,b,S]);return r.jsxs("div",{className:"h-full flex flex-col p-4",children:[r.jsx("div",{className:"flex-1 min-h-0",children:t?k?N.length===0&&B.length===0?r.jsx("div",{className:"flex-1 flex items-center justify-center h-full",children:r.jsxs("div",{className:"text-center text-white/50",children:[r.jsx(tn,{className:"w-12 h-12 mx-auto mb-3 opacity-50"}),r.jsx("p",{className:"text-lg mb-2",children:a("spoolbuddy.ams.noData","No AMS detected")}),r.jsx("p",{className:"text-sm",children:a("spoolbuddy.ams.connectAms","Connect an AMS to see filament slots")})]})}):r.jsxs("div",{className:"flex flex-col gap-3 h-full",children:[r.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:T.map(se=>r.jsx(Gde,{unit:se,activeSlot:$(se.id),onConfigureSlot:H,isDualNozzle:I,nozzleSide:X(se.id),thresholds:R,fillOverrides:b,spoolmanFillOverrides:D},se.id))}),re.length>0&&r.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:re.map(({key:se,label:fe,tray:ue,isEmpty:pe,isActive:G,temp:L,humidity:ae,nozzleSide:ge,effectiveFill:be,onClick:ve})=>{const De=Vlt(ue.tray_color);return r.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 ${G?"ring-2 ring-bambu-green":""}`,onClick:ve,children:[r.jsxs("div",{className:"relative w-10 h-10 flex-shrink-0",children:[pe?r.jsx("div",{className:"w-full h-full rounded-full border-2 border-dashed border-gray-500 flex items-center justify-center",children:r.jsx("div",{className:"w-1.5 h-1.5 rounded-full bg-gray-600"})}):r.jsxs("svg",{viewBox:"0 0 56 56",className:"w-full h-full",children:[r.jsx("circle",{cx:"28",cy:"28",r:"26",fill:De}),r.jsx("circle",{cx:"28",cy:"28",r:"20",fill:De,style:{filter:"brightness(0.85)"}}),r.jsx("ellipse",{cx:"20",cy:"20",rx:"6",ry:"4",fill:"white",opacity:"0.3"}),r.jsx("circle",{cx:"28",cy:"28",r:"8",fill:"#2d2d2d"}),r.jsx("circle",{cx:"28",cy:"28",r:"5",fill:"#1a1a1a"})]}),G&&r.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"})]}),r.jsxs("div",{className:"min-w-0",children:[r.jsxs("div",{className:"flex items-center gap-1",children:[r.jsx("span",{className:"text-xs text-white/50 font-medium truncate",children:fe}),ge&&r.jsx(A5,{side:ge})]}),r.jsx("div",{className:"text-sm text-white/80 truncate",children:pe?"Empty":ue.tray_type||"?"}),(L!=null||ae!=null)&&r.jsxs("div",{className:"flex items-center gap-1.5",children:[L!=null&&r.jsx(Vde,{temp:L,goodThreshold:R?.tempGood,fairThreshold:R?.tempFair}),ae!=null&&r.jsx(qde,{humidity:ae,goodThreshold:R?.humidityGood,fairThreshold:R?.humidityFair})]})]}),!pe&&be!=null&&be>=0&&r.jsx("div",{className:"w-1.5 h-8 bg-bambu-dark-tertiary rounded-full overflow-hidden flex-shrink-0 flex flex-col-reverse",children:r.jsx("div",{className:"w-full rounded-full",style:{height:`${be}%`,backgroundColor:by(be)}})})]},se)})})]}):r.jsx("div",{className:"flex-1 flex items-center justify-center h-full",children:r.jsx("div",{className:"text-center text-white/50",children:r.jsx("p",{className:"text-lg mb-2",children:a("spoolbuddy.ams.printerDisconnected","Printer disconnected")})})}):r.jsx("div",{className:"flex-1 flex items-center justify-center h-full",children:r.jsxs("div",{className:"text-center text-white/50",children:[r.jsx("p",{className:"text-lg mb-2",children:a("spoolbuddy.ams.noPrinter","No printer selected")}),r.jsx("p",{className:"text-sm",children:a("spoolbuddy.ams.selectPrinter","Select a printer from the top bar")})]})})}),ce&&t&&r.jsx(Mse,{isOpen:!!ce,onClose:()=>de(null),printerId:t,slotInfo:ce,printerModel:qlt(o?.model??null)||void 0,fullScreen:!0,onSuccess:()=>{n.invalidateQueries({queryKey:["slotPresets",t]}),n.invalidateQueries({queryKey:["printerStatus",t]})}}),oe&&t&&(()=>{const se=V(oe.amsId,oe.trayId),fe=Q(oe.amsId,oe.trayId,oe.tray),ue=u?f.find(G=>G.printer_id===t&&G.ams_id===oe.amsId&&G.tray_id===oe.trayId):void 0,pe=ue?g.find(G=>G.id===ue.spoolman_spool_id)??null:null;return r.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[r.jsx("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-sm",onClick:()=>Y(null)}),r.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:[r.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[oe.trayColor&&r.jsx("span",{className:"w-4 h-4 rounded-full border border-black/20",style:{backgroundColor:`#${oe.trayColor.slice(0,6)}`}}),r.jsx("h2",{className:"text-lg font-semibold text-white",children:oe.location}),oe.traySubBrands&&r.jsxs("span",{className:"text-sm text-bambu-gray",children:["(",oe.traySubBrands,")"]})]}),r.jsx("button",{onClick:()=>Y(null),className:"p-1 text-bambu-gray hover:text-white rounded transition-colors",children:r.jsx(Ht,{className:"w-5 h-5"})})]}),r.jsxs("div",{className:"p-4 space-y-2",children:[!u&&se?.spool&&r.jsxs("div",{className:"p-2.5 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary mb-3",children:[r.jsx("p",{className:"text-xs text-bambu-gray mb-1",children:a("inventory.assignedSpool","Assigned spool")}),r.jsxs("div",{className:"flex items-center gap-2",children:[se.spool.rgba&&r.jsx("span",{className:"w-3 h-3 rounded-full border border-black/20 flex-shrink-0",style:al(se.spool.rgba)}),r.jsxs("span",{className:"text-sm text-white",children:[se.spool.brand?`${se.spool.brand} `:"",se.spool.material,se.spool.color_name?` - ${se.spool.color_name}`:""]}),r.jsxs("span",{className:"text-[10px] font-mono text-zinc-500 shrink-0 ml-auto",children:["#",se.spool.id]})]})]}),u&&fe&&!pe&&r.jsxs("div",{className:"p-2.5 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary mb-3",children:[r.jsx("p",{className:"text-xs text-bambu-gray mb-1",children:a("spoolman.linkedSpool","Linked spool")}),r.jsx("div",{className:"flex items-center gap-2",children:r.jsxs("span",{className:"text-sm text-white",children:["Spoolman #",fe.id,fe.remaining_weight!=null?` (${Math.round(fe.remaining_weight)}g)`:""]})})]}),u&&pe&&r.jsxs("div",{className:"p-2.5 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary mb-3",children:[r.jsx("p",{className:"text-xs text-bambu-gray mb-1",children:a("inventory.assignedSpool","Assigned spool")}),r.jsxs("div",{className:"flex items-center gap-2",children:[pe.rgba&&r.jsx("span",{className:"w-3 h-3 rounded-full border border-black/20 flex-shrink-0",style:al(pe.rgba)}),r.jsxs("span",{className:"text-sm text-white",children:[pe.brand?`${pe.brand} `:"",pe.material,pe.color_name?` - ${pe.color_name}`:""]})]})]}),r.jsxs("button",{onClick:O,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:[r.jsx(xd,{className:"w-5 h-5 text-bambu-blue flex-shrink-0"}),r.jsxs("div",{children:[r.jsx("p",{className:"text-white font-medium",children:a("configureAmsSlot.title")}),r.jsx("p",{className:"text-xs text-bambu-gray",children:a("spoolbuddy.ams.configureDesc","Set filament preset, K-profile, and color")})]})]}),!u&&(Qs(oe?.tray)?null:se?r.jsxs("button",{onClick:ee,disabled:A.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:[r.jsx(pu,{className:"w-5 h-5 text-amber-400 flex-shrink-0"}),r.jsxs("div",{children:[r.jsx("p",{className:"text-amber-400 font-medium",children:a("inventory.unassignSpool","Unassign")}),r.jsx("p",{className:"text-xs text-bambu-gray",children:a("spoolbuddy.ams.unassignDesc","Remove inventory spool from this slot")})]})]}):r.jsxs("button",{onClick:q,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:[r.jsx(Kr,{className:"w-5 h-5 text-bambu-green flex-shrink-0"}),r.jsxs("div",{children:[r.jsx("p",{className:"text-white font-medium",children:a("inventory.assignSpool")}),r.jsx("p",{className:"text-xs text-bambu-gray",children:a("spoolbuddy.ams.assignDesc","Track a spool from your inventory")})]})]})),u&&(fe?.id?r.jsxs("button",{onClick:()=>F.mutate(fe.id),disabled:F.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:[r.jsx(pu,{className:"w-5 h-5 text-amber-400 flex-shrink-0"}),r.jsxs("div",{children:[r.jsx("p",{className:"text-amber-400 font-medium",children:a("inventory.unassignSpool")}),r.jsx("p",{className:"text-xs text-bambu-gray",children:a("spoolbuddy.ams.unlinkDesc","Remove Spoolman link from this slot")})]})]}):pe?r.jsxs("button",{onClick:()=>U.mutate(pe.id),disabled:U.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:[r.jsx(pu,{className:"w-5 h-5 text-amber-400 flex-shrink-0"}),r.jsxs("div",{children:[r.jsx("p",{className:"text-amber-400 font-medium",children:a("inventory.unassignSpool")}),r.jsx("p",{className:"text-xs text-bambu-gray",children:a("spoolbuddy.ams.unassignDesc","Remove inventory spool from this slot")})]})]}):r.jsxs("button",{onClick:Z,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:[r.jsx(Ih,{className:"w-5 h-5 text-bambu-green flex-shrink-0"}),r.jsxs("div",{children:[r.jsx("p",{className:"text-white font-medium",children:a("inventory.assignSpool")}),r.jsx("p",{className:"text-xs text-bambu-gray",children:a("spoolbuddy.ams.linkDesc","Link a Spoolman spool to this slot")})]})]}))]})]})]})})(),ie&&r.jsx(yse,{isOpen:!!ie,onClose:()=>{me(null),n.invalidateQueries({queryKey:["spool-assignments",t]}),n.invalidateQueries({queryKey:["spool-assignments"]})},printerId:ie.printerId,amsId:ie.amsId,trayId:ie.trayId,trayInfo:ie.trayInfo,spoolmanEnabled:!!u}),he&&r.jsx(xse,{isOpen:!!he,onClose:()=>xe(null),tagUid:he.tagUid,trayUuid:he.trayUuid,printerId:he.printerId,amsId:he.amsId,trayId:he.trayId})]})}function $lt({type:t,deviceId:e,onClose:a}){const{t:n}=wt(),[i,s]=y.useState(!1),[o,l]=y.useState(""),[c,d]=y.useState(""),[u,m]=y.useState(!1);y.useEffect(()=>{const g=v=>{v.key==="Escape"&&!i&&a()};return window.addEventListener("keydown",g),()=>window.removeEventListener("keydown",g)},[i,a]);const p=y.useCallback(async()=>{s(!0),l(""),d(""),m(!0);try{l(n("spoolbuddy.diagnostic.queuing",`Queuing diagnostic on device... `)),await an.queueDiagnostics(e,t);let g=null;const v=60;let b=0;for(;bsetTimeout(x,500));try{g=await an.getDiagnosticResult(e,t);break}catch{b++,b%4===0&&l(x=>x+".")}}if(!g)throw new Error("Diagnostic timed out - device did not report results");l(g.output),g.success||d(`Exit code: ${g.exit_code}`)}catch(g){d(g instanceof Error?g.message:"Unknown error"),l("")}finally{s(!1)}},[t,e,n]),f=t==="scale"?n("spoolbuddy.diagnostic.scaleTitle","Scale Diagnostic"):t==="read_tag"?n("spoolbuddy.diagnostic.readTagTitle","Read Tag Diagnostic"):n("spoolbuddy.diagnostic.nfcTitle","NFC Reader Diagnostic");return r.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/70 animate-fade-in",onClick:a,children:r.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:g=>g.stopPropagation(),children:[r.jsxs("div",{className:"flex justify-between items-center p-4 border-b border-zinc-700",children:[r.jsx("h2",{className:"text-lg font-semibold text-white",children:f}),r.jsx("button",{onClick:a,className:"text-zinc-400 hover:text-white transition-colors","aria-label":"Close",children:r.jsx(Ht,{size:20})})]}),r.jsx("div",{className:"flex-1 overflow-auto p-4 bg-black/50 font-mono text-sm",children:i?r.jsxs("div",{className:"flex items-center gap-2 text-green-400",children:[r.jsx("div",{className:"animate-spin w-4 h-4 border-2 border-green-400 border-t-transparent rounded-full"}),r.jsx("span",{children:n("spoolbuddy.diagnostic.running","Running diagnostic on device...")})]}):o?r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"text-green-400 whitespace-pre-wrap break-words",children:o}),c&&r.jsxs("div",{className:"text-red-400 mt-2",children:["❌ ",c]})]}):u?r.jsx("div",{children:c?r.jsxs("div",{className:"text-red-400",children:["ERROR: ",c]}):r.jsx("span",{className:"text-green-400",children:n("spoolbuddy.diagnostic.completed","Diagnostic completed successfully.")})}):r.jsxs("div",{className:"text-zinc-500",children:[n("spoolbuddy.diagnostic.clickStart",'Click "Run Diagnostic" to start the hardware diagnostic on')," ",e,"."]})}),r.jsxs("div",{className:"flex gap-2 p-4 border-t border-zinc-700 bg-zinc-800",children:[r.jsx("button",{onClick:p,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?r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"animate-spin w-4 h-4 border-2 border-white border-t-transparent rounded-full"}),n("spoolbuddy.diagnostic.runningBtn","Running...")]}):u?r.jsxs(r.Fragment,{children:[r.jsx(Hw,{size:16}),n("spoolbuddy.diagnostic.runAgain","Run Again")]}):r.jsxs(r.Fragment,{children:[r.jsx(gs,{size:16}),n("spoolbuddy.diagnostic.runBtn","Run Diagnostic")]})}),r.jsx("button",{onClick:a,className:"px-4 py-2 rounded bg-zinc-700 hover:bg-zinc-600 text-white font-semibold transition-colors",children:n("spoolbuddy.diagnostic.close","Close")})]})]})})}function Wlt(t){if(t<60)return`${t}s`;if(t<3600)return`${Math.floor(t/60)}m`;const e=Math.floor(t/3600),a=Math.floor(t%3600/60);return`${e}h ${a}m`}function Klt(t){if(!t)return"-";const e=Ga(t);return e?e.toLocaleDateString(void 0,{month:"short",day:"numeric"})+" "+e.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit"}):"-"}const Ylt=[{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 Qlt({device:t}){const{t:e}=wt(),[a,n]=y.useState(null),[i,s]=y.useState(""),[o,l]=y.useState(""),[c,d]=y.useState(!1),[u,m]=y.useState(null);y.useEffect(()=>{!i&&t.backend_url&&s(t.backend_url)},[t.backend_url,i]);const p=async()=>{if(!i.trim()){m({type:"error",text:e("spoolbuddy.settings.systemFieldsRequired","Backend URL is required.")});return}d(!0),m(null);try{await an.updateSystemConfig(t.device_id,i.trim(),o.trim()||void 0),m({type:"ok",text:e("spoolbuddy.settings.systemQueued","Config queued.")})}catch(f){m({type:"error",text:f instanceof Error?f.message:e("common.error","Error")})}finally{d(!1)}};return r.jsxs("div",{className:"space-y-2",children:[r.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[r.jsxs("div",{className:"bg-zinc-800 rounded-lg p-3",children:[r.jsx("h3",{className:"text-sm font-semibold text-zinc-300 mb-2",children:e("spoolbuddy.settings.nfcReader","NFC Reader")}),r.jsxs("div",{className:"space-y-1.5 text-xs",children:[r.jsxs("div",{className:"flex justify-between",children:[r.jsx("span",{className:"text-zinc-500",children:e("spoolbuddy.settings.type","Type")}),r.jsx("span",{className:"text-zinc-300 font-mono",children:t.nfc_reader_type||"N/A"})]}),r.jsxs("div",{className:"flex justify-between",children:[r.jsx("span",{className:"text-zinc-500",children:e("spoolbuddy.settings.connection","Connection")}),r.jsx("span",{className:"text-zinc-300 font-mono",children:t.nfc_connection||"N/A"})]}),r.jsxs("div",{className:"flex justify-between items-center",children:[r.jsx("span",{className:"text-zinc-500",children:e("spoolbuddy.status.status","Status")}),r.jsxs("div",{className:"flex items-center gap-1.5",children:[r.jsx("div",{className:`w-2 h-2 rounded-full ${t.nfc_ok?"bg-green-500":t.nfc_reader_type?"bg-red-500":"bg-zinc-600"}`}),r.jsx("span",{className:t.nfc_ok?"text-green-400":t.nfc_reader_type?"text-red-400":"text-zinc-500",children:t.nfc_ok?e("spoolbuddy.status.nfcReady","Ready"):t.nfc_reader_type?e("common.error","Error"):e("spoolbuddy.settings.notConnected","N/A")})]})]})]})]}),r.jsxs("div",{className:"bg-zinc-800 rounded-lg p-3",children:[r.jsx("h3",{className:"text-sm font-semibold text-zinc-300 mb-2",children:e("spoolbuddy.settings.deviceInfo","Device Info")}),r.jsxs("div",{className:"space-y-1.5 text-xs",children:[r.jsxs("div",{className:"flex justify-between",children:[r.jsx("span",{className:"text-zinc-500",children:e("spoolbuddy.settings.hostname","Host")}),r.jsx("span",{className:"text-zinc-300 truncate ml-2",children:t.hostname})]}),r.jsxs("div",{className:"flex justify-between",children:[r.jsx("span",{className:"text-zinc-500",children:"IP"}),r.jsx("span",{className:"text-zinc-300",children:t.ip_address})]}),r.jsxs("div",{className:"flex justify-between",children:[r.jsx("span",{className:"text-zinc-500",children:e("spoolbuddy.settings.uptime","Uptime")}),r.jsx("span",{className:"text-zinc-300",children:Wlt(t.uptime_s)})]}),r.jsxs("div",{className:"flex justify-between",children:[r.jsx("span",{className:"text-zinc-500",children:"ID"}),r.jsx("span",{className:"text-zinc-400 font-mono truncate ml-2",children:t.device_id})]})]})]})]}),r.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[r.jsxs("div",{className:"bg-zinc-800 rounded-lg p-3 space-y-2",children:[r.jsx("h3",{className:"text-sm font-semibold text-zinc-300",children:e("spoolbuddy.settings.systemConfig","Backend & Auth")}),r.jsx("input",{value:i,onChange:f=>s(f.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"}),r.jsxs("div",{className:"flex gap-2",children:[r.jsx("input",{type:"password",value:o,onChange:f=>l(f.target.value),placeholder:e("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"}),r.jsx("button",{onClick:p,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:e("spoolbuddy.settings.saveConfig","Save")})]}),u&&r.jsx("div",{className:`text-xs ${u.type==="ok"?"text-green-400":"text-red-400"}`,children:u.text})]}),r.jsxs("div",{className:"bg-zinc-800 rounded-lg p-3 flex flex-col gap-2",children:[r.jsxs("button",{onClick:()=>n("nfc"),className:"flex-1 bg-blue-700 hover:bg-blue-600 transition-colors rounded-lg p-2 flex items-center gap-2",children:[r.jsx(qI,{className:"w-4 h-4 text-blue-300 shrink-0"}),r.jsx("span",{className:"text-xs font-medium text-blue-100",children:e("spoolbuddy.settings.nfcDiagnostic","NFC Diagnostic")})]}),r.jsxs("button",{onClick:()=>n("scale"),className:"flex-1 bg-yellow-700 hover:bg-yellow-600 transition-colors rounded-lg p-2 flex items-center gap-2",children:[r.jsx(jc,{className:"w-4 h-4 text-yellow-300 shrink-0"}),r.jsx("span",{className:"text-xs font-medium text-yellow-100",children:e("spoolbuddy.settings.scaleDiagnostic","Scale Diagnostic")})]}),r.jsxs("button",{onClick:()=>n("read_tag"),className:"flex-1 bg-emerald-700 hover:bg-emerald-600 transition-colors rounded-lg p-2 flex items-center gap-2",children:[r.jsx(us,{className:"w-4 h-4 text-emerald-300 shrink-0"}),r.jsx("span",{className:"text-xs font-medium text-emerald-100",children:e("spoolbuddy.settings.readTagDiagnostic","Read Tag")})]})]})]}),a&&t&&r.jsx($lt,{type:a,deviceId:t.device_id,onClose:()=>n(null)})]})}function Xlt({device:t,onBrightnessChange:e}){const{t:a}=wt(),[n,i]=y.useState(t.display_brightness),[s,o]=y.useState(t.display_blank_timeout),[l,c]=y.useState(!1),d=y.useRef(void 0),u=y.useRef(void 0);y.useEffect(()=>{i(t.display_brightness),o(t.display_blank_timeout)},[t.display_brightness,t.display_blank_timeout]);const m=y.useCallback(()=>{c(!0),u.current&&clearTimeout(u.current),u.current=setTimeout(()=>c(!1),1500)},[]),p=y.useCallback((v,b)=>{d.current&&clearTimeout(d.current),d.current=setTimeout(()=>{an.updateDisplay(t.device_id,v,b).then(()=>m()).catch(x=>console.error("Failed to update display:",x))},300)},[t.device_id,m]),f=v=>{i(v),e(v),p(v,s)},g=v=>{o(v),p(n,v)};return r.jsxs("div",{className:"space-y-4",children:[r.jsxs("div",{className:"bg-zinc-800 rounded-lg p-4",children:[r.jsxs("div",{className:"flex items-center justify-between mb-3",children:[r.jsx("h3",{className:"text-sm font-semibold text-zinc-300",children:a("spoolbuddy.settings.brightness","Brightness")}),l&&r.jsxs("span",{className:"text-xs text-green-400 flex items-center gap-1 animate-pulse",children:[r.jsx("svg",{className:"w-3 h-3",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:3,children:r.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M5 13l4 4L19 7"})}),a("spoolbuddy.settings.saved","Saved")]})]}),r.jsxs("div",{className:"flex items-center gap-3",children:[r.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:r.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"})}),r.jsx("input",{type:"range",min:0,max:100,value:n,onChange:v=>f(parseInt(v.target.value)),className:"flex-1 h-2 bg-zinc-700 rounded-lg appearance-none cursor-pointer accent-green-500"}),r.jsxs("span",{className:"text-sm font-mono text-zinc-400 w-10 text-right",children:[n,"%"]})]}),!t.has_backlight&&r.jsx("p",{className:"text-xs text-zinc-600 mt-2",children:a("spoolbuddy.settings.noBacklight","No DSI backlight detected. Brightness control requires a DSI display.")})]}),r.jsxs("div",{className:"bg-zinc-800 rounded-lg p-4",children:[r.jsx("h3",{className:"text-sm font-semibold text-zinc-300 mb-1",children:a("spoolbuddy.settings.screenBlank","Screen Blank Timeout")}),r.jsx("p",{className:"text-xs text-zinc-500 mb-3",children:a("spoolbuddy.settings.screenBlankDesc","Screen turns off after inactivity. Touch to wake.")}),r.jsx("div",{className:"grid grid-cols-3 gap-2",children:Ylt.map(v=>r.jsx("button",{onClick:()=>g(v.value),className:`px-3 py-2 rounded-lg text-sm font-medium transition-colors min-h-[40px] ${s===v.value?"bg-green-600 text-white":"bg-zinc-700 text-zinc-300 hover:bg-zinc-600"}`,children:v.label},v.value))})]}),r.jsx("p",{className:"text-xs text-zinc-600 text-center",children:a("spoolbuddy.settings.displayNote","Brightness is applied as a software filter.")})]})}function Zlt({step:t,labels:e}){return r.jsxs("div",{className:"flex flex-col items-center w-16 shrink-0 pt-1",children:[r.jsx("div",{className:`flex items-center justify-center w-7 h-7 rounded-full text-xs font-bold ${t==="tare"?"bg-green-600 text-white":"bg-green-600/20 text-green-400"}`,children:t==="weight"?r.jsx("svg",{className:"w-3.5 h-3.5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:3,children:r.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M5 13l4 4L19 7"})}):"1"}),r.jsx("span",{className:`text-[10px] mt-0.5 ${t==="tare"?"text-green-400 font-medium":"text-green-400/60"}`,children:e.tare}),r.jsx("div",{className:`w-px h-5 my-1 ${t==="weight"?"bg-green-600/40":"bg-zinc-700"}`}),r.jsx("div",{className:`flex items-center justify-center w-7 h-7 rounded-full text-xs font-bold ${t==="weight"?"bg-green-600 text-white":"bg-zinc-700 text-zinc-500"}`,children:"2"}),r.jsx("span",{className:`text-[10px] mt-0.5 ${t==="weight"?"text-green-400 font-medium":"text-zinc-600"}`,children:e.weight})]})}function Jlt({device:t,weight:e,weightStable:a,rawAdc:n}){const{t:i}=wt(),s=na(),[o,l]=y.useState("idle"),[c,d]=y.useState("500"),[u,m]=y.useState(null),[p,f]=y.useState(!1),[g,v]=y.useState(null),[b,x]=y.useState(null),S=y.useRef(null);y.useEffect(()=>()=>{S.current&&clearTimeout(S.current)},[]);const k=y.useCallback(j=>{S.current&&clearTimeout(S.current),S.current=setTimeout(()=>v(null),j)},[]);y.useEffect(()=>{if(!b)return;const j=15e3,D=1e3,P=()=>Date.now()-b.startedAtMs,E=setInterval(()=>{s.invalidateQueries({queryKey:["spoolbuddy-devices"]})},D),z=setTimeout(()=>{x(null),v({type:"error",msg:i("spoolbuddy.settings.tareTimedOut","Tare timed out — is the SpoolBuddy daemon running?")}),k(5e3)},Math.max(0,j-P()));return()=>{clearInterval(E),clearTimeout(z)}},[b,s,i,k]),y.useEffect(()=>{if(!b)return;(t?.last_calibrated_at??null)!==b.snapshot&&(x(null),v({type:"ok",msg:i("spoolbuddy.settings.tareComplete","Tare complete!")}),k(3e3))},[t?.last_calibrated_at,b,i,k]);const C=j=>{j==="backspace"?d(D=>D.slice(0,-1)||""):j==="."&&!c.includes(".")?d(D=>D+"."):j>="0"&&j<="9"&&d(D=>D==="0"?j:D+j)},N=async()=>{f(!0),v(null),S.current&&(clearTimeout(S.current),S.current=null);const j=t?.last_calibrated_at??null;try{await an.tare(t.device_id),v({type:"ok",msg:i("spoolbuddy.settings.tareSet","Tare command sent. Waiting for device...")}),x({snapshot:j,startedAtMs:Date.now()})}catch{v({type:"error",msg:i("spoolbuddy.settings.tareFailed","Failed to send tare command")}),k(5e3)}finally{f(!1)}},T=async()=>{if(o==="tare"){f(!0),v(null);try{m(n),await an.tare(t.device_id),v({type:"ok",msg:i("spoolbuddy.settings.zeroSet","Zero point set. Place known weight on scale.")}),l("weight")}catch{v({type:"error",msg:i("spoolbuddy.settings.tareFailed","Failed to send tare command")})}finally{f(!1)}}else if(o==="weight"){const j=parseFloat(c);if(n===null||!j||j<=0)return;f(!0),v(null);try{await an.setCalibrationFactor(t.device_id,j,n,u??void 0),v({type:"ok",msg:i("spoolbuddy.settings.calibrationDone","Calibration complete!")}),k(3e3),l("idle")}catch{v({type:"error",msg:i("spoolbuddy.settings.calibrationFailed","Calibration failed")}),k(5e3)}finally{f(!1)}}};return o==="idle"?r.jsxs("div",{className:"flex flex-col h-full",children:[r.jsxs("div",{className:"bg-zinc-800 rounded-lg p-3 mb-3",children:[r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("div",{className:`w-2 h-2 rounded-full ${a?"bg-green-500":"bg-amber-500 animate-pulse"}`}),r.jsx("span",{className:"text-lg font-mono text-zinc-200",children:e!==null?`${e.toFixed(1)} g`:"-- g"})]}),r.jsxs("div",{className:"text-xs text-zinc-500 text-right",children:[r.jsxs("span",{children:[i("spoolbuddy.settings.tareOffset","Tare"),": ",t.tare_offset]}),r.jsx("span",{className:"mx-1.5",children:"·"}),r.jsxs("span",{children:[i("spoolbuddy.settings.calFactor","Factor"),": ",t.calibration_factor.toFixed(2)]})]})]}),t.last_calibrated_at&&r.jsxs("div",{className:"text-xs text-zinc-600 mt-1",children:[i("spoolbuddy.settings.lastCalibrated","Last calibrated"),": ",Klt(t.last_calibrated_at)]})]}),g&&r.jsx("div",{className:`rounded-lg px-3 py-2 mb-3 text-sm ${g.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:g.msg}),r.jsxs("div",{className:"flex gap-2",children:[r.jsxs("button",{onClick:N,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] flex items-center justify-center gap-2",children:[p&&r.jsxs("svg",{className:"w-4 h-4 animate-spin",viewBox:"0 0 24 24",fill:"none",children:[r.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),r.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")]}),r.jsx("button",{onClick:()=>{l("tare"),v(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")})]})]}):r.jsxs("div",{className:"flex gap-3",children:[r.jsx(Zlt,{step:o,labels:{tare:i("spoolbuddy.weight.tare","Tare"),weight:i("spoolbuddy.settings.knownWeight","Known weight")}}),r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsxs("div",{className:"flex items-center gap-2 bg-zinc-800 rounded-lg px-3 py-1.5 mb-1.5",children:[r.jsx("div",{className:`w-2 h-2 rounded-full shrink-0 ${a?"bg-green-500":"bg-amber-500 animate-pulse"}`}),r.jsx("span",{className:"text-sm font-mono text-zinc-200",children:e!==null?`${e.toFixed(1)} g`:"-- g"}),r.jsx("span",{className:`text-xs ml-auto ${a?"text-green-400":"text-amber-400"}`,children:a?i("spoolbuddy.settings.stable","Stable"):i("spoolbuddy.settings.settling","Settling...")})]}),g&&r.jsx("div",{className:`rounded-lg px-3 py-1.5 mb-1.5 text-xs ${g.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:g.msg}),o==="tare"?r.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.")}):r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"flex items-center gap-2 mb-1.5",children:[r.jsx("span",{className:"text-xs text-zinc-400 shrink-0",children:i("spoolbuddy.settings.knownWeight","Known weight")}),r.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",r.jsx("span",{className:"text-zinc-500 ml-1",children:"g"})]})]}),r.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(j=>r.jsx("button",{onClick:()=>C(j),className:`rounded text-lg font-medium transition-colors h-[48px] active:scale-95 ${j==="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:j==="backspace"?"⌫":j},j))})]}),r.jsxs("div",{className:"flex gap-2",children:[r.jsx("button",{onClick:()=>{l("idle"),v(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")}),r.jsxs("button",{onClick:T,disabled:p,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:[p&&r.jsxs("svg",{className:"w-4 h-4 animate-spin",viewBox:"0 0 24 24",fill:"none",children:[r.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),r.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 ect({device:t}){const{t:e}=wt(),[a,n]=y.useState(null),[i,s]=y.useState(null),[o,l]=y.useState(!1),[c,d]=y.useState(!1),u=t.update_status==="pending"||t.update_status==="updating";y.useEffect(()=>{u&&a==="applying"&&n(null)},[u,a]),y.useEffect(()=>{const k=()=>{u&&setTimeout(()=>window.location.reload(),1e3)};return window.addEventListener("spoolbuddy-online",k),()=>window.removeEventListener("spoolbuddy-online",k)},[u]);const{data:m,refetch:p}=$e({queryKey:["spoolbuddy-update-check",t.device_id],queryFn:()=>an.checkDaemonUpdate(t.device_id),staleTime:0}),{data:f}=$e({queryKey:["spoolbuddy-ssh-key"],queryFn:()=>an.getSSHPublicKey(),enabled:o,staleTime:1/0}),g=async()=>{n("checking"),s(null);try{await p()}finally{n(null)}},v=async()=>{n("applying"),s(null);try{await an.triggerUpdate(t.device_id)}catch(k){s(k instanceof Error?k.message:"Failed to trigger update"),n(null)}},b=a!=null||u,x=()=>{f?.public_key&&(navigator.clipboard.writeText(f.public_key),d(!0),setTimeout(()=>d(!1),2e3))},S=t.firmware_version||(m?.current_version&&m.current_version!=="0.0.0"?m.current_version:null);return r.jsxs("div",{className:"space-y-3",children:[r.jsxs("div",{className:"bg-zinc-800 rounded-lg p-3 space-y-3",children:[r.jsxs("div",{className:"flex justify-between items-center text-sm",children:[r.jsx("span",{className:"text-zinc-500",children:e("spoolbuddy.settings.currentVersion","Current Version")}),r.jsx("span",{className:"text-zinc-200 font-mono",children:S||r.jsx("span",{className:"text-zinc-500 italic text-xs",children:e("spoolbuddy.settings.versionPending","Waiting for daemon...")})})]}),b?r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsxs("svg",{className:"w-4 h-4 animate-spin text-green-400 flex-shrink-0",viewBox:"0 0 24 24",fill:"none",children:[r.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),r.jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"})]}),r.jsx("span",{className:"text-green-300 text-xs",children:a==="checking"?e("spoolbuddy.settings.checking","Checking for updates..."):t.update_message||e("spoolbuddy.settings.updateWaiting","Updating...")})]}):t.update_status==="error"?r.jsx("p",{className:"text-xs text-red-300",children:t.update_message||e("spoolbuddy.settings.updateFailed","Update failed")}):i?r.jsx("p",{className:"text-xs text-red-300",children:i}):m?.update_available?r.jsxs("p",{className:"text-xs text-green-300",children:[e("spoolbuddy.settings.updateAvailable","Update available"),": ",S," → ",m.latest_version]}):null,!b&&(m?.update_available?r.jsx("button",{onClick:v,disabled:!t.online,className:"w-full px-3 py-2 rounded-lg text-sm font-medium bg-green-600 text-white hover:bg-green-700 disabled:opacity-40 transition-colors",children:t.online?e("spoolbuddy.settings.applyUpdate","Apply Update"):e("spoolbuddy.settings.deviceOffline","Device Offline")}):r.jsxs("div",{className:"flex gap-2",children:[r.jsx("button",{onClick:g,className:"flex-1 px-3 py-2 rounded-lg text-xs font-medium bg-zinc-700 text-zinc-300 hover:bg-zinc-600 transition-colors",children:e("spoolbuddy.settings.checkUpdates","Check for Updates")}),r.jsx("button",{onClick:v,disabled:!t.online,className:"px-3 py-2 rounded-lg text-xs font-medium bg-zinc-700 text-zinc-400 hover:bg-zinc-600 hover:text-zinc-200 disabled:opacity-40 transition-colors",children:e("spoolbuddy.settings.forceUpdate","Force Update")})]}))]}),r.jsxs("div",{className:"bg-zinc-800 rounded-lg p-3",children:[r.jsxs("button",{onClick:()=>l(!o),className:"w-full flex justify-between items-center text-xs",children:[r.jsx("span",{className:"font-medium text-zinc-400",children:e("spoolbuddy.settings.sshSetup","SSH Setup")}),r.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:r.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M19 9l-7 7-7-7"})})]}),o&&r.jsxs("div",{className:"mt-2 space-y-2",children:[r.jsx("p",{className:"text-xs text-zinc-500",children:e("spoolbuddy.settings.sshDescription","SSH key is deployed automatically. For manual setup, add this key to ~/.ssh/authorized_keys on the device.")}),f?.public_key?r.jsxs("div",{className:"relative",children:[r.jsx("pre",{className:"bg-zinc-900 rounded p-2 text-[10px] text-zinc-400 font-mono break-all whitespace-pre-wrap",children:f.public_key}),r.jsx("button",{onClick:x,className:"absolute top-1 right-1 px-1.5 py-0.5 rounded text-[10px] bg-zinc-700 text-zinc-300 hover:bg-zinc-600 transition-colors",children:c?e("common.copied","Copied!"):e("common.copy","Copy")})]}):r.jsx("span",{className:"text-[10px] text-zinc-500 italic",children:e("spoolbuddy.settings.sshKeyLoading","Loading...")})]})]})]})}function sZ({percent:t,color:e}){return r.jsx("div",{className:"w-full h-2 bg-zinc-700 rounded-full overflow-hidden",children:r.jsx("div",{className:`h-full rounded-full transition-all ${e}`,style:{width:`${Math.min(100,Math.max(0,t))}%`}})})}function tct(t){const e=Math.floor(t/86400),a=Math.floor(t%86400/3600),n=Math.floor(t%3600/60);return e>0?`${e}d ${a}h ${n}m`:a>0?`${a}h ${n}m`:`${n}m`}function act({device:t}){const{t:e}=wt(),a=t.system_stats;if(!a)return r.jsx("div",{className:"flex items-center justify-center h-32",children:r.jsx("p",{className:"text-sm text-zinc-500",children:e("spoolbuddy.settings.systemStatsWaiting","Waiting for system stats...")})});const n=a.memory,i=a.disk,s=(a.cpu_temp_c??0)>=80?"text-red-400":(a.cpu_temp_c??0)>=65?"text-amber-400":"text-green-400",o=(n?.percent??0)>=90?"bg-red-500":(n?.percent??0)>=70?"bg-amber-500":"bg-green-500",l=(i?.percent??0)>=90?"bg-red-500":(i?.percent??0)>=70?"bg-amber-500":"bg-green-500";return r.jsxs("div",{className:"space-y-2",children:[r.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[r.jsxs("div",{className:"bg-zinc-800 rounded-lg p-3",children:[r.jsx("h3",{className:"text-sm font-semibold text-zinc-300 mb-2",children:"CPU"}),r.jsxs("div",{className:"space-y-1.5 text-xs",children:[r.jsxs("div",{className:"flex justify-between",children:[r.jsx("span",{className:"text-zinc-500",children:e("spoolbuddy.settings.cores","Cores")}),r.jsx("span",{className:"text-zinc-300 font-mono",children:a.cpu_count??"-"})]}),r.jsxs("div",{className:"flex justify-between",children:[r.jsx("span",{className:"text-zinc-500",children:e("spoolbuddy.settings.loadAvg","Load Avg")}),r.jsx("span",{className:"text-zinc-300 font-mono",children:a.load_avg?a.load_avg.join(" / "):"-"})]}),r.jsxs("div",{className:"flex justify-between",children:[r.jsx("span",{className:"text-zinc-500",children:e("spoolbuddy.settings.temp","Temp")}),r.jsx("span",{className:`font-mono font-medium ${s}`,children:a.cpu_temp_c!=null?`${a.cpu_temp_c}°C`:"-"})]})]})]}),r.jsxs("div",{className:"bg-zinc-800 rounded-lg p-3",children:[r.jsx("h3",{className:"text-sm font-semibold text-zinc-300 mb-2",children:e("spoolbuddy.settings.memory","Memory")}),n?r.jsxs("div",{className:"space-y-1.5",children:[r.jsx(sZ,{percent:n.percent??0,color:o}),r.jsxs("div",{className:"space-y-1 text-xs",children:[r.jsxs("div",{className:"flex justify-between",children:[r.jsx("span",{className:"text-zinc-500",children:e("spoolbuddy.settings.used","Used")}),r.jsxs("span",{className:"text-zinc-300 font-mono",children:[n.used_mb," / ",n.total_mb," MB"]})]}),r.jsxs("div",{className:"flex justify-between",children:[r.jsx("span",{className:"text-zinc-500",children:e("spoolbuddy.settings.available","Free")}),r.jsxs("span",{className:"text-zinc-300 font-mono",children:[n.available_mb," MB"]})]})]})]}):r.jsx("span",{className:"text-xs text-zinc-500",children:"-"})]})]}),r.jsx("div",{className:"bg-zinc-800 rounded-lg px-3 py-2",children:r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("h3",{className:"text-sm font-semibold text-zinc-300 shrink-0",children:e("spoolbuddy.settings.disk","Disk")}),i?r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"flex-1",children:r.jsx(sZ,{percent:i.percent??0,color:l})}),r.jsxs("span",{className:"text-xs text-zinc-300 font-mono shrink-0",children:[i.used_gb," / ",i.total_gb," GB"]})]}):r.jsx("span",{className:"text-xs text-zinc-500",children:"-"})]})}),r.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[r.jsxs("div",{className:"bg-zinc-800 rounded-lg p-3",children:[r.jsx("h3",{className:"text-sm font-semibold text-zinc-300 mb-1.5",children:e("spoolbuddy.settings.osInfo","OS")}),r.jsxs("div",{className:"space-y-1 text-xs",children:[a.os?.os&&r.jsxs("div",{className:"flex justify-between",children:[r.jsx("span",{className:"text-zinc-500",children:e("spoolbuddy.settings.distro","Distro")}),r.jsx("span",{className:"text-zinc-300 truncate ml-2",children:a.os.os})]}),a.os?.kernel&&r.jsxs("div",{className:"flex justify-between",children:[r.jsx("span",{className:"text-zinc-500",children:e("spoolbuddy.settings.kernel","Kernel")}),r.jsx("span",{className:"text-zinc-300 font-mono truncate ml-2",children:a.os.kernel})]}),a.os?.arch&&r.jsxs("div",{className:"flex justify-between",children:[r.jsx("span",{className:"text-zinc-500",children:e("spoolbuddy.settings.arch","Arch")}),r.jsx("span",{className:"text-zinc-300 font-mono",children:a.os.arch})]})]})]}),r.jsxs("div",{className:"bg-zinc-800 rounded-lg p-3",children:[r.jsx("h3",{className:"text-sm font-semibold text-zinc-300 mb-1.5",children:e("spoolbuddy.settings.runtime","Runtime")}),r.jsxs("div",{className:"space-y-1 text-xs",children:[a.os?.python&&r.jsxs("div",{className:"flex justify-between",children:[r.jsx("span",{className:"text-zinc-500",children:"Python"}),r.jsx("span",{className:"text-zinc-300 font-mono",children:a.os.python})]}),a.system_uptime_s!=null&&r.jsxs("div",{className:"flex justify-between",children:[r.jsx("span",{className:"text-zinc-500",children:e("spoolbuddy.settings.systemUptime","Uptime")}),r.jsx("span",{className:"text-zinc-300",children:tct(a.system_uptime_s)})]})]})]})]})]})}function rct(){const{sbState:t,setDisplayBrightness:e}=Jy(),{t:a}=wt(),[n,i]=y.useState("device"),{data:s=[]}=$e({queryKey:["spoolbuddy-devices"],queryFn:()=>an.getDevices(),refetchInterval:1e4}),o=t.deviceId?s.find(c=>c.device_id===t.deviceId)??s[0]:s[0],l=[{id:"device",label:a("spoolbuddy.settings.tabDevice","Device")},{id:"display",label:a("spoolbuddy.settings.tabDisplay","Display")},{id:"scale",label:a("spoolbuddy.settings.tabScale","Scale")},{id:"updates",label:a("spoolbuddy.settings.tabUpdates","Updates")},{id:"system",label:a("spoolbuddy.settings.tabSystem","System")}];return r.jsxs("div",{className:"h-full flex flex-col p-4",children:[r.jsx("h1",{className:"text-xl font-semibold text-zinc-100 mb-3",children:a("spoolbuddy.nav.settings","Settings")}),r.jsx("div",{className:"flex gap-1 bg-zinc-800/50 rounded-lg p-1 mb-4",children:l.map(c=>r.jsx("button",{onClick:()=>i(c.id),className:`flex-1 px-2 py-2 rounded-md text-sm font-medium transition-colors min-h-[36px] ${n===c.id?"bg-zinc-700 text-zinc-100":"text-zinc-500 hover:text-zinc-300"}`,children:c.label},c.id))}),r.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto",children:o?r.jsxs(r.Fragment,{children:[n==="device"&&r.jsx(Qlt,{device:o}),n==="display"&&r.jsx(Xlt,{device:o,onBrightnessChange:e}),n==="scale"&&r.jsx(Jlt,{device:o,weight:t.weight,weightStable:t.weightStable,rawAdc:t.rawAdc}),n==="updates"&&r.jsx(ect,{device:o}),n==="system"&&r.jsx(act,{device:o})]}):r.jsx("div",{className:"flex items-center justify-center h-32",children:r.jsx("div",{className:"text-center text-zinc-500",children:r.jsx("p",{className:"text-sm",children:a("spoolbuddy.settings.noDevice","No SpoolBuddy device found")})})})})]})}function nct({device:t,weight:e,weightStable:a,rawAdc:n}){const{t:i}=wt(),[s,o]=y.useState(!1),[l,c]=y.useState("idle"),[d,u]=y.useState("500"),[m,p]=y.useState(null),[f,g]=y.useState(!1),v=k=>{k==="backspace"?u(C=>C.slice(0,-1)||""):k==="."&&!d.includes(".")?u(C=>C+"."):k>="0"&&k<="9"&&u(C=>C==="0"?k:C+k)},b=async()=>{g(!0);try{await an.tare(t.device_id)}catch(k){console.error("Failed to tare:",k)}finally{g(!1)}},x=()=>{c("tare")},S=async()=>{if(l==="tare"){o(!0);try{p(n),await an.tare(t.device_id),c("weight")}catch(k){console.error("Failed to tare:",k)}finally{o(!1)}}else if(l==="weight"){const k=parseFloat(d);if(n===null||!k||k<=0)return;o(!0);try{await an.setCalibrationFactor(t.device_id,k,n,m??void 0),c("idle")}catch(C){console.error("Failed to calibrate:",C)}finally{o(!1)}}};return r.jsxs("div",{className:"space-y-4",children:[r.jsxs("div",{className:"bg-zinc-800 rounded-lg p-4",children:[r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsx("span",{className:"text-sm text-zinc-400",children:i("spoolbuddy.settings.currentWeight","Current weight")}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("div",{className:`w-2 h-2 rounded-full ${a?"bg-green-500":"bg-amber-500 animate-pulse"}`}),r.jsx("span",{className:"text-lg font-mono text-zinc-200",children:e!==null?`${e.toFixed(1)} g`:"-- g"})]})]}),r.jsxs("div",{className:"grid grid-cols-2 gap-4 mt-3 text-xs",children:[r.jsxs("div",{className:"flex justify-between",children:[r.jsx("span",{className:"text-zinc-500",children:i("spoolbuddy.settings.tareOffset","Tare offset")}),r.jsx("span",{className:"text-zinc-400 font-mono",children:t.tare_offset})]}),r.jsxs("div",{className:"flex justify-between",children:[r.jsx("span",{className:"text-zinc-500",children:i("spoolbuddy.settings.calFactor","Cal. factor")}),r.jsx("span",{className:"text-zinc-400 font-mono",children:t.calibration_factor.toFixed(2)})]})]})]}),l==="idle"?r.jsxs("div",{className:"flex gap-2",children:[r.jsx("button",{onClick:b,disabled:f,className:"flex-1 px-4 py-2.5 rounded-lg text-sm font-medium bg-zinc-700 text-zinc-200 hover:bg-zinc-600 disabled:opacity-40 transition-colors min-h-[44px]",children:f?"...":i("spoolbuddy.weight.tare","Tare")}),r.jsx("button",{onClick:x,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")})]}):r.jsxs("div",{className:"bg-zinc-800 border border-zinc-700 rounded-lg p-3 space-y-2",children:[r.jsx("div",{className:"text-sm font-medium text-zinc-200",children:l==="tare"?i("spoolbuddy.settings.calStep1","Step 1: Remove all items from the scale"):i("spoolbuddy.settings.calStep2","Step 2: Place known weight on scale")}),l==="weight"&&r.jsxs("div",{className:"space-y-1.5",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("span",{className:"text-xs text-zinc-400",children:i("spoolbuddy.settings.knownWeight","Known weight (g)")}),r.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:[d||"0",r.jsx("span",{className:"text-zinc-500 ml-1",children:"g"})]})]}),r.jsx("div",{className:"grid grid-cols-4 gap-1",children:["7","8","9","backspace","4","5","6",".","1","2","3","0"].map(k=>r.jsx("button",{onClick:()=>v(k),className:`py-2 rounded text-sm font-medium transition-colors min-h-[36px] ${k==="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:k==="backspace"?"⌫":k},k))})]}),r.jsxs("div",{className:"flex gap-2",children:[r.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")}),r.jsx("button",{onClick:S,disabled:s,className:"flex-1 px-4 py-2 rounded-lg text-sm font-medium bg-green-600 text-white hover:bg-green-700 disabled:opacity-40 transition-colors min-h-[40px]",children:s?"...":l==="tare"?i("spoolbuddy.settings.setZero","Set Zero"):i("spoolbuddy.settings.calibrateNow","Calibrate")})]})]})]})}function ict(){const{sbState:t}=Jy(),{t:e}=wt(),a=Ii(),{data:n=[]}=$e({queryKey:["spoolbuddy-devices"],queryFn:()=>an.getDevices(),refetchInterval:1e4}),i=t.deviceId?n.find(s=>s.device_id===t.deviceId)??n[0]:n[0];return r.jsxs("div",{className:"h-full flex flex-col p-4",children:[r.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[r.jsx("button",{onClick:()=>a("/spoolbuddy/settings"),className:"p-1.5 rounded-lg text-zinc-400 hover:text-zinc-200 hover:bg-zinc-800 transition-colors",children:r.jsx("svg",{className:"w-5 h-5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:r.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M15 19l-7-7 7-7"})})}),r.jsx("h1",{className:"text-xl font-semibold text-zinc-100",children:e("spoolbuddy.settings.scaleCalibration","Scale Calibration")})]}),r.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto",children:i?r.jsx(nct,{device:i,weight:t.weight,weightStable:t.weightStable,rawAdc:t.rawAdc}):r.jsx("div",{className:"flex items-center justify-center h-32",children:r.jsx("div",{className:"text-center text-zinc-500",children:r.jsx("p",{className:"text-sm",children:e("spoolbuddy.settings.noDevice","No SpoolBuddy device found")})})})})]})}const sct=["PLA","PETG","ABS","ASA","TPU","PA","PC","PVA","HIPS"];function oct(){const{t}=wt(),{showToast:e}=oa(),{sbState:a}=Jy(),[n,i]=y.useState("existing"),[s,o]=y.useState(null),[l,c]=y.useState(""),[d,u]=y.useState("idle"),[m,p]=y.useState(""),[f,g]=y.useState(!1),[v,b]=y.useState(!1),[x,S]=y.useState(null),{data:k}=$e({queryKey:["spoolman-settings"],queryFn:ne.getSpoolmanSettings,staleTime:300*1e3}),C=k!==void 0,N=k?.spoolman_enabled==="true"&&!!k?.spoolman_url,{data:T=[],refetch:j}=$e({queryKey:[N?"spoolman-inventory-spools":"inventory-spools","write-tag"],queryFn:()=>N?ne.getSpoolmanInventorySpools(!1):ne.getSpools(!1),refetchInterval:1e4,enabled:C}),{data:D=[]}=$e({queryKey:["spoolbuddy-devices"],queryFn:()=>an.getDevices(),refetchInterval:5e3}),{data:P}=$e({queryKey:["settings"],queryFn:ne.getSettings}),E=D[0],z=a.deviceOnline,I=Vo(P?.currency||"USD"),B=y.useMemo(()=>{let he;if(n==="existing")he=T.filter(xe=>!xe.tag_uid&&!xe.archived_at);else if(n==="replace")he=T.filter(xe=>(xe.tag_uid||xe.tray_uuid)&&!xe.archived_at);else return[];if(l){const xe=l.toLowerCase();he=he.filter(V=>V.material?.toLowerCase().includes(xe)||V.color_name?.toLowerCase().includes(xe)||V.brand?.toLowerCase().includes(xe)||V.subtype?.toLowerCase().includes(xe))}return he},[T,n,l]),R=y.useCallback(he=>{const xe=he.detail;(xe.sak??xe.data?.sak)===0&&(b(!0),S(xe.tag_uid??xe.data?.tag_uid??null))},[]),K=y.useCallback(he=>{const xe=he.detail;b(!0),S(xe.tag_uid??xe.data?.tag_uid??null)},[]),J=y.useCallback(()=>{b(!1),S(null)},[]),X=y.useCallback(he=>{const xe=he.detail;(xe.spool_id===s?.id||xe.data?.spool_id===s?.id)&&(u("success"),p(t("spoolbuddy.writeTag.writeSuccess","Tag written successfully!")),j(),setTimeout(()=>{u("idle"),o(null),p("")},5e3))},[s,t,j]),ce=y.useCallback(he=>{const xe=he.detail;(xe.spool_id===s?.id||xe.data?.spool_id===s?.id)&&(u("error"),p(xe.message??xe.data?.message??t("spoolbuddy.writeTag.writeFailed","Write failed")))},[s,t]);y.useEffect(()=>(window.addEventListener("spoolbuddy-unknown-tag",R),window.addEventListener("spoolbuddy-tag-matched",K),window.addEventListener("spoolbuddy-tag-removed",J),window.addEventListener("spoolbuddy-tag-written",X),window.addEventListener("spoolbuddy-tag-write-failed",ce),()=>{window.removeEventListener("spoolbuddy-unknown-tag",R),window.removeEventListener("spoolbuddy-tag-matched",K),window.removeEventListener("spoolbuddy-tag-removed",J),window.removeEventListener("spoolbuddy-tag-written",X),window.removeEventListener("spoolbuddy-tag-write-failed",ce)}),[R,K,J,X,ce]),y.useEffect(()=>{o(null),u("idle"),p(""),c("")},[n]);const de=async()=>{if(!(!s||!E)){u("writing"),p(t("spoolbuddy.writeTag.waiting","Waiting for SpoolBuddy..."));try{const he=await an.writeTag(E.device_id,s.id);if(he?.warnings?.length)for(const xe of he.warnings)e(xe,"warning")}catch{u("error"),p(t("spoolbuddy.writeTag.queueFailed","Failed to queue write command"))}}},oe=async()=>{if(E){try{await an.cancelWrite(E.device_id)}catch{}u("idle"),p("")}},Y=async()=>{if(!(!s||!oZ(s))){g(!0),u("idle"),p("");try{N?await ne.linkTagToSpoolmanSpool(s.id,{tag_uid:"",tray_uuid:""}):await ne.linkTagToSpool(s.id,{tag_uid:"",tray_uuid:"",data_origin:"manual"}),await j(),o(null),u("success"),p(t("spoolbuddy.writeTag.untagSuccess","Tag removed from spool")),setTimeout(()=>{u("idle"),p("")},2500)}catch{u("error"),p(t("spoolbuddy.writeTag.untagFailed","Failed to remove tag from spool"))}finally{g(!1)}}},ie=y.useCallback(he=>{o(he),u("idle"),p(""),j()},[j]),me=s&&z&&d!=="writing"&&d!=="success";return r.jsxs("div",{className:"flex flex-col h-full",children:[r.jsx("div",{className:"flex border-b border-bambu-dark-tertiary shrink-0",children:[{key:"existing",label:t("spoolbuddy.writeTag.tabExisting","Existing Spool")},{key:"new",label:t("spoolbuddy.writeTag.tabNew","New Spool")},{key:"replace",label:t("spoolbuddy.writeTag.tabReplace","Replace Tag")}].map(he=>r.jsx("button",{onClick:()=>i(he.key),className:`flex-1 py-3 text-sm font-medium transition-colors ${n===he.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:he.label},he.key))}),r.jsxs("div",{className:"flex flex-1 overflow-hidden",children:[r.jsx("div",{className:"flex-1 flex flex-col overflow-hidden border-r border-bambu-dark-tertiary",children:n==="new"?r.jsx(cct,{currencySymbol:I,onCreated:ie,selectedSpool:s,spoolmanMode:N,t}):r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"p-3 shrink-0",children:r.jsx("input",{type:"text",value:l,onChange:he=>c(he.target.value),placeholder:t("spoolbuddy.writeTag.searchPlaceholder","Search by material, color, brand..."),className:"w-full px-3 py-2 bg-bambu-dark-tertiary border border-bambu-dark-tertiary rounded text-sm text-white placeholder-zinc-500 focus:outline-none focus:border-bambu-green"})}),r.jsx("div",{className:"flex-1 overflow-y-auto px-3 pb-3 space-y-2",children:B.length===0?r.jsx("div",{className:"text-center text-zinc-500 py-8 text-sm",children:n==="existing"?t("spoolbuddy.writeTag.noUntaggedSpools","No spools without tags"):t("spoolbuddy.writeTag.noTaggedSpools","No spools with tags")}):B.map(he=>r.jsx(lct,{spool:he,selected:s?.id===he.id,showTag:n==="replace",onClick:()=>{o(he),u("idle"),p("")}},he.id))})]})}),r.jsx("div",{className:"w-[340px] flex flex-col items-center justify-center p-6 shrink-0",children:r.jsx(dct,{writeStatus:d,writeMessage:m,selectedSpool:s,tagOnReader:v,tagUid:x,deviceOnline:z,canWrite:!!me,isReplace:n==="replace",canUntag:n==="replace"&&!!s&&oZ(s),untagging:f,onWrite:de,onUntag:Y,onCancel:oe,onRetry:()=>{u("idle"),p("")},t})})]})]})}function oZ(t){return!!(t.tag_uid||t.tray_uuid)}function lct({spool:t,selected:e,showTag:a,onClick:n}){const i=Math.max(0,t.label_weight-t.weight_used),s=t.label_weight>0?Math.round(i/t.label_weight*100):0;return r.jsxs("button",{onClick:n,className:`w-full flex items-center gap-3 p-3 rounded-lg text-left transition-colors ${e?"bg-bambu-green/15 border border-bambu-green/50":"bg-bambu-dark-secondary hover:bg-bambu-dark-tertiary border border-transparent"}`,children:[r.jsx("div",{className:"w-8 h-8 rounded-full shrink-0 border border-white/10",style:t.rgba?al(t.rgba):{backgroundColor:"#666"}}),r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsxs("span",{className:"text-sm font-medium text-white truncate",children:[t.brand?`${t.brand} `:"",t.material,t.subtype?` ${t.subtype}`:""]}),r.jsxs("span",{className:"text-[10px] font-mono text-zinc-500 shrink-0",children:["#",t.id]})]}),r.jsxs("div",{className:"flex items-center gap-2 text-xs text-zinc-400",children:[t.color_name&&r.jsx("span",{children:t.color_name}),r.jsxs("span",{children:[i,"g / ",t.label_weight,"g (",s,"%)"]})]}),a&&t.tag_uid&&r.jsx("div",{className:"text-xs text-zinc-500 mt-0.5 font-mono",children:t.tag_uid})]}),e&&r.jsx("svg",{className:"w-5 h-5 text-bambu-green shrink-0",fill:"currentColor",viewBox:"0 0 20 20",children:r.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 cct({currencySymbol:t,onCreated:e,selectedSpool:a,spoolmanMode:n,t:i}){const{data:s=[]}=$e({queryKey:[n?"spoolman-inventory-spools":"inventory-spools","write-tag-form"],queryFn:()=>n?ne.getSpoolmanInventorySpools(!0):ne.getSpools(!0)}),{data:o}=$e({queryKey:["settings"],queryFn:ne.getSettings}),[l,c]=y.useState("simple"),[d,u]=y.useState("filament"),[m,p]=y.useState(bI),[f,g]=y.useState({}),[v,b]=y.useState(!1),[x,S]=y.useState(1),[k,C]=y.useState(!1),[N,T]=y.useState(null),[j,D]=y.useState(!1),[P,E]=y.useState(!1),[z,I]=y.useState([]),[B,R]=y.useState([]),[K,J]=y.useState([]),[X,ce]=y.useState([]),[de,oe]=y.useState([]),[Y,ie]=y.useState(""),[me,he]=y.useState([]),[xe,V]=y.useState([]),[Q,A]=y.useState(new Set),[F,U]=y.useState(new Set);y.useEffect(()=>{he(Tse())},[]),y.useEffect(()=>{let ae=!1;return(async()=>{if(l==="full"){E(!0);try{const[be,ve]=await Promise.allSettled([(async()=>(await ne.getCloudStatus()).is_authenticated?{connected:!0,presets:await ne.getFilamentPresets()}:{connected:!1,presets:[]})(),(async()=>(await ne.orcaCloudStatus()).connected?{connected:!0,presets:(await ne.orcaCloudListProfiles()).filament}:{connected:!1,presets:[]})()]);if(ae)return;const De=be.status==="fulfilled"&&be.value.connected,je=ve.status==="fulfilled"&&ve.value.connected,Te=be.status==="fulfilled"?be.value.presets:[],qe=ve.status==="fulfilled"?ve.value.presets:[];D(De||je),I([...Te,...qe])}catch{ae||D(!1)}finally{ae||E(!1)}ne.getSpoolCatalog().then(be=>{ae||ce(be)}).catch(()=>{}),ne.getColorCatalog().then(be=>{ae||oe(be)}).catch(()=>{}),ne.getLocalPresets().then(be=>{ae||R(be.filament)}).catch(()=>{}),ne.getBuiltinFilaments().then(be=>{ae||J(be)}).catch(()=>{});try{const be=await ne.getPrinters(),ve=await Promise.all(be.map(je=>ne.getPrinterStatus(je.id).catch(()=>null))),De=[];for(let je=0;je({cali_idx:Ue.slot_id,filament_id:Ue.filament_id,setting_id:Ue.setting_id||"",name:Ue.name,k_value:parseFloat(Ue.k_value)||0,n_coef:parseFloat(Ue.n_coef)||0,extruder_id:Ue.extruder_id,nozzle_diameter:Ue.nozzle_diameter}))}catch{}De.push({printer:{...Te,connected:Ce},calibrations:Ie})}ae||V(De)}catch{}}})(),()=>{ae=!0}},[l]),y.useEffect(()=>{xe.length>0&&U(new Set(xe.map(ae=>String(ae.printer.id))))},[xe]);const $=y.useMemo(()=>Cse(z,new Set,B,K),[z,B,K]),H=y.useMemo(()=>Nse(m.slicer_filament,$),[m.slicer_filament,$]),le=y.useMemo(()=>{const ae=Pse(z,B),ge=de.map(be=>be.manufacturer?.trim()).filter(be=>!!be);return Array.from(new Set([...ae,...ge])).sort((be,ve)=>be.localeCompare(ve))},[z,B,de]),O=y.useMemo(()=>{const ae=de.map(ge=>ge.material?.trim()).filter(ge=>!!ge);return Array.from(new Set([...Sse,...ae])).sort((ge,be)=>ge.localeCompare(be))},[de]),q=y.useMemo(()=>{const ae=[];for(const ge of de){const be=ge.manufacturer?.trim(),ve=ge.material?.trim();be&&ve&&ae.push({brand:be,material:ve})}for(const ge of z){const be=of(ge.name);be.brand&&be.material&&ae.push({brand:be.brand,material:be.material})}for(const ge of B){const be=of(ge.name),ve=ge.filament_vendor?.trim()||be.brand,De=be.material;ve&&De&&ae.push({brand:ve,material:De})}return ae},[z,de,B]),Z=y.useMemo(()=>{const ae=new Map;for(const ge of q){const be=ge.brand.toLowerCase(),ve=ge.material.toLowerCase();ae.has(be)||ae.set(be,new Set),ae.get(be).add(ve)}return ae},[q]),ee=y.useMemo(()=>{const ae=new Map;for(const ge of q){const be=ge.brand.toLowerCase(),ve=ge.material.toLowerCase();ae.has(ve)||ae.set(ve,new Set),ae.get(ve).add(be)}return ae},[q]),re=y.useMemo(()=>{if(!m.material)return le;const ae=m.material.toLowerCase(),ge=ee.get(ae);return!ge||ge.size===0?le:le.filter(be=>ge.has(be.toLowerCase()))},[le,m.material,ee]),se=y.useMemo(()=>{if(!m.brand)return O;const ae=m.brand.toLowerCase(),ge=Z.get(ae);return!ge||ge.size===0?O:O.filter(be=>ge.has(be.toLowerCase()))},[O,m.brand,Z]),fe=(ae,ge)=>{p(be=>({...be,[ae]:ge})),f[ae]&&g(be=>({...be,[ae]:void 0}))},ue=ae=>{he(ge=>Ase(ae,ge))},pe=async ae=>{const ge=n?ne.saveSpoolmanKProfiles:ne.saveSpoolKProfiles;if(Q.size===0){try{await ge(ae,[])}catch{}return}const be=[];for(const ve of Q){const[De,je,Te]=ve.split(":"),qe=parseInt(De),Ce=parseInt(je),Ie=Te==="null"?0:parseInt(Te),Re=xe.find(Ue=>Ue.printer.id===qe);if(Re){const Ue=Re.calibrations.find(ze=>ze.cali_idx===Ce);Ue&&be.push({printer_id:qe,extruder:Ie,nozzle_diameter:Ue.nozzle_diameter||"0.4",k_value:Ue.k_value,name:Ue.name||null,cali_idx:Ue.cali_idx,setting_id:Ue.setting_id||null})}}be.length>0&&await ge(ae,be)},G=async()=>{T(null);const ae=Dde(m,l==="simple"?!0:v);if(!ae.isValid){g(ae.errors),u("filament");return}const ge=H?.displayName||Y||null,be={material:m.material,subtype:m.subtype||null,brand:m.brand||null,color_name:m.color_name||null,rgba:m.rgba||null,extra_colors:m.extra_colors||null,effect_type:m.effect_type||null,label_weight:m.label_weight,core_weight:m.core_weight,core_weight_catalog_id:m.core_weight_catalog_id,weight_used:m.weight_used,slicer_filament:m.slicer_filament||null,slicer_filament_name:ge,nozzle_temp_min:null,nozzle_temp_max:null,note:m.note||null,cost_per_kg:m.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:m.category.trim()||null,low_stock_threshold_pct:m.low_stock_threshold_pct};C(!0);try{if(x>1){const ve=n?await ne.bulkCreateSpoolmanInventorySpools(be,x):await ne.bulkCreateSpools(be,x),De=n&&ve&&typeof ve=="object"&&"created"in ve?ve.created:ve;for(const je of De)await pe(je.id);De.length>0&&e(De[0])}else{const ve=n?await ne.createSpoolmanInventorySpool(be):await ne.createSpool(be);await pe(ve.id),e(ve)}}catch{T(i("spoolbuddy.writeTag.createFailed","Failed to create spool"))}finally{C(!1)}},L=`#${(m.rgba||"808080FF").slice(0,6)}`;return r.jsxs("div",{className:"p-3 space-y-3 overflow-y-auto h-full",children:[r.jsxs("div",{className:"flex items-center justify-between px-2 py-2 bg-bambu-dark-secondary rounded-lg border border-bambu-dark-tertiary",children:[r.jsx("span",{className:"text-sm text-zinc-200",children:i("spoolbuddy.writeTag.viewMode","View")}),r.jsxs("div",{className:"flex rounded-lg overflow-hidden border border-bambu-dark-tertiary",children:[r.jsx("button",{type:"button",onClick:()=>c("simple"),className:`px-3 py-1.5 text-xs font-medium ${l==="simple"?"bg-bambu-green/20 text-bambu-green":"bg-bambu-dark text-zinc-400"}`,children:i("spoolbuddy.writeTag.simpleView","Simple")}),r.jsx("button",{type:"button",onClick:()=>c("full"),className:`px-3 py-1.5 text-xs font-medium ${l==="full"?"bg-bambu-green/20 text-bambu-green":"bg-bambu-dark text-zinc-400"}`,children:i("spoolbuddy.writeTag.fullView","Full")})]})]}),l==="simple"?a?r.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:[r.jsx("div",{className:"w-12 h-12 rounded-full mb-4 border border-white/10",style:a.rgba?al(a.rgba):{backgroundColor:"#666"}}),r.jsxs("p",{className:"text-white font-medium",children:[a.brand?`${a.brand} `:"",a.material]}),a.color_name&&r.jsx("p",{className:"text-zinc-400 text-sm",children:a.color_name}),r.jsxs("p",{className:"text-zinc-500 text-xs mt-1",children:[a.label_weight,"g"]}),r.jsx("p",{className:"text-bambu-green text-sm mt-4",children:i("spoolbuddy.writeTag.spoolCreated","Spool created! Ready to write.")})]}):r.jsxs("div",{className:"p-4 space-y-4 overflow-y-auto bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg",children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-xs text-zinc-400 mb-1",children:i("spoolbuddy.writeTag.material","Material")}),r.jsx("select",{value:m.material,onChange:ae=>fe("material",ae.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:sct.map(ae=>r.jsx("option",{value:ae,children:ae},ae))})]}),r.jsxs("div",{className:"flex gap-3",children:[r.jsxs("div",{className:"flex-1",children:[r.jsx("label",{className:"block text-xs text-zinc-400 mb-1",children:i("spoolbuddy.writeTag.colorName","Color Name")}),r.jsx("input",{type:"text",value:m.color_name,onChange:ae=>fe("color_name",ae.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"})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-xs text-zinc-400 mb-1",children:i("spoolbuddy.writeTag.color","Color")}),r.jsx("input",{type:"color",value:L,onChange:ae=>fe("rgba",ae.target.value.replace("#","").toUpperCase()+"FF"),className:"w-10 h-9 bg-transparent border border-bambu-dark-tertiary rounded cursor-pointer"})]})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-xs text-zinc-400 mb-1",children:i("spoolbuddy.writeTag.brand","Brand")}),r.jsx("input",{type:"text",value:m.brand,onChange:ae=>fe("brand",ae.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"})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-xs text-zinc-400 mb-1",children:i("spoolbuddy.writeTag.weight","Weight (g)")}),r.jsx("input",{type:"number",value:m.label_weight,onChange:ae=>fe("label_weight",parseInt(ae.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"})]}),r.jsx("button",{onClick:G,disabled:k||!m.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:k?i("spoolbuddy.writeTag.creating","Creating..."):i("spoolbuddy.writeTag.createSpool","Create Spool")})]}):r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"flex items-center justify-between px-2 py-2 bg-bambu-dark-secondary rounded-lg border border-bambu-dark-tertiary",children:[r.jsx("span",{className:"text-sm text-zinc-200",children:i("inventory.quickAdd","Quick Add")}),r.jsx("button",{type:"button",onClick:()=>b(ae=>!ae),className:`relative inline-flex h-6 w-11 items-center rounded-full transition-colors ${v?"bg-bambu-green":"bg-bambu-dark-tertiary"}`,children:r.jsx("span",{className:`inline-block h-4.5 w-4.5 rounded-full bg-white transition-transform ${v?"translate-x-6":"translate-x-1"}`})})]}),r.jsxs("div",{className:"flex border border-bambu-dark-tertiary rounded-lg overflow-hidden",children:[r.jsx("button",{onClick:()=>u("filament"),className:`flex-1 py-2.5 text-sm font-medium ${d==="filament"?"bg-bambu-green/15 text-bambu-green":"bg-bambu-dark-secondary text-zinc-400"}`,children:i("inventory.filamentInfoTab","Filament")}),!v&&r.jsx("button",{onClick:()=>u("pa-profile"),className:`flex-1 py-2.5 text-sm font-medium ${d==="pa-profile"?"bg-bambu-green/15 text-bambu-green":"bg-bambu-dark-secondary text-zinc-400"}`,children:i("inventory.paProfileTab","PA Profile")})]}),r.jsx("div",{className:"bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg p-3",children:d==="filament"?r.jsxs("div",{className:"space-y-4",children:[r.jsx(Fde,{formData:m,updateField:fe,cloudAuthenticated:j,loadingCloudPresets:P,presetInputValue:Y,setPresetInputValue:ie,selectedPresetOption:H,filamentOptions:$,availableBrands:re,availableMaterials:se,quickAdd:v,quantity:x,onQuantityChange:S,errors:f}),r.jsx(Lde,{formData:m,updateField:fe,recentColors:me,onColorUsed:ue,catalogColors:de}),r.jsx(Rde,{formData:m,updateField:fe,spoolCatalog:X,currencySymbol:t,availableCategories:Array.from(new Set(s.map(ae=>ae.category?.trim()).filter(ae=>!!ae))).sort((ae,ge)=>ae.localeCompare(ge)),globalLowStockThreshold:o?.low_stock_threshold??20})]}):r.jsx(zde,{formData:m,updateField:fe,printersWithCalibrations:xe,selectedProfiles:Q,setSelectedProfiles:A,expandedPrinters:F,setExpandedPrinters:U})})]}),N&&r.jsx("div",{className:"text-sm text-red-400 bg-red-900/20 border border-red-900/40 rounded-lg px-3 py-2",children:N}),l==="full"&&r.jsx("button",{onClick:G,disabled:k,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:k?i("spoolbuddy.writeTag.creating","Creating..."):i("spoolbuddy.writeTag.createSpool","Create Spool")}),l==="full"&&a&&r.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:[r.jsx("div",{className:"w-12 h-12 rounded-full mb-4 border border-white/10",style:a.rgba?al(a.rgba):{backgroundColor:"#666"}}),r.jsxs("p",{className:"text-white font-medium",children:[a.brand?`${a.brand} `:"",a.material]}),a.color_name&&r.jsx("p",{className:"text-zinc-400 text-sm",children:a.color_name}),r.jsxs("p",{className:"text-zinc-500 text-xs mt-1",children:[a.label_weight,"g"]}),r.jsx("p",{className:"text-bambu-green text-sm mt-4",children:i("spoolbuddy.writeTag.spoolCreated","Spool created! Ready to write.")})]})]})}function dct({writeStatus:t,writeMessage:e,selectedSpool:a,tagOnReader:n,tagUid:i,deviceOnline:s,canWrite:o,isReplace:l,canUntag:c,untagging:d,onWrite:u,onUntag:m,onCancel:p,onRetry:f,t:g}){if(t==="success")return r.jsxs("div",{className:"flex flex-col items-center text-center space-y-4",children:[r.jsx("div",{className:"w-16 h-16 rounded-full bg-green-500/20 flex items-center justify-center",children:r.jsx("svg",{className:"w-8 h-8 text-green-400",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:r.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5 13l4 4L19 7"})})}),r.jsx("p",{className:"text-green-400 font-medium",children:e}),a&&r.jsxs("p",{className:"text-zinc-400 text-sm",children:[a.brand?`${a.brand} `:"",a.material,a.color_name?` - ${a.color_name}`:""]})]});if(t==="error")return r.jsxs("div",{className:"flex flex-col items-center text-center space-y-4",children:[r.jsx("div",{className:"w-16 h-16 rounded-full bg-red-500/20 flex items-center justify-center",children:r.jsx("svg",{className:"w-8 h-8 text-red-400",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:r.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})}),r.jsx("p",{className:"text-red-400 font-medium",children:e}),r.jsx("button",{onClick:f,className:"px-4 py-2 bg-bambu-dark-tertiary hover:bg-bambu-dark-secondary text-white text-sm rounded transition-colors",children:g("spoolbuddy.writeTag.tryAgain","Try Again")})]});if(t==="writing")return r.jsxs("div",{className:"flex flex-col items-center text-center space-y-4",children:[r.jsxs("div",{className:"relative w-16 h-16",children:[r.jsx("div",{className:"absolute inset-0 rounded-full border-2 border-bambu-green/30 animate-ping"}),r.jsx("div",{className:"absolute inset-2 rounded-full border-2 border-bambu-green/50 animate-pulse"}),r.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:r.jsx(H0,{className:"w-8 h-8 text-bambu-green"})})]}),r.jsx("p",{className:"text-bambu-green font-medium",children:g("spoolbuddy.writeTag.writing","Writing tag...")}),r.jsx("p",{className:"text-zinc-500 text-xs",children:e}),r.jsx("button",{onClick:p,className:"px-4 py-2 bg-bambu-dark-tertiary hover:bg-bambu-dark-secondary text-zinc-400 text-sm rounded transition-colors",children:g("spoolbuddy.writeTag.cancel","Cancel")})]});if(!s)return r.jsxs("div",{className:"flex flex-col items-center text-center space-y-3",children:[r.jsx(H0,{className:"w-12 h-12 text-zinc-600"}),r.jsx("p",{className:"text-zinc-500 text-sm",children:g("spoolbuddy.writeTag.deviceOffline","SpoolBuddy is offline")})]});if(!a)return r.jsxs("div",{className:"flex flex-col items-center text-center space-y-3",children:[r.jsx(H0,{className:"w-12 h-12 text-zinc-600"}),r.jsx("p",{className:"text-zinc-400 text-sm",children:g("spoolbuddy.writeTag.selectSpool","Select a spool, then place a blank NTAG on the reader")})]});const v=a.rgba?al(a.rgba):{backgroundColor:"#666"};return r.jsxs("div",{className:"flex flex-col items-center text-center space-y-4 w-full",children:[r.jsx("div",{className:"relative w-16 h-16",children:n?r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"absolute inset-0 rounded-full bg-bambu-green/10"}),r.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:r.jsx(H0,{className:"w-8 h-8 text-bambu-green"})})]}):r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"absolute inset-0 rounded-full border-2 border-zinc-600 animate-pulse"}),r.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:r.jsx(H0,{className:"w-8 h-8 text-zinc-500"})})]})}),n?r.jsxs("div",{className:"space-y-1",children:[r.jsx("p",{className:"text-bambu-green text-sm font-medium",children:g("spoolbuddy.writeTag.tagReady","Tag detected — ready to write")}),i&&r.jsx("p",{className:"text-zinc-500 text-xs font-mono",children:i})]}):r.jsx("p",{className:"text-zinc-400 text-sm",children:g("spoolbuddy.writeTag.placeTag","Place an NTAG on the reader")}),r.jsxs("div",{className:"w-full bg-bambu-dark-secondary rounded-lg p-3 space-y-2",children:[r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("div",{className:"w-8 h-8 rounded-full border border-white/10 shrink-0",style:v}),r.jsxs("div",{className:"text-left min-w-0",children:[r.jsxs("p",{className:"text-white text-sm font-medium truncate",children:[a.brand?`${a.brand} `:"",a.material]}),a.color_name&&r.jsx("p",{className:"text-zinc-400 text-xs",children:a.color_name})]})]}),r.jsxs("div",{className:"text-xs text-zinc-500",children:[a.label_weight,"g"]})]}),l&&a.tag_uid&&r.jsx("p",{className:"text-yellow-500/80 text-xs",children:g("spoolbuddy.writeTag.replaceWarning","Old tag will be unlinked. New tag will replace it.")}),r.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:l?g("spoolbuddy.writeTag.replaceTag","Replace Tag"):g("spoolbuddy.writeTag.writeTag","Write Tag")}),l&&c&&r.jsx("button",{onClick:m,disabled:d,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:d?g("spoolbuddy.writeTag.untagging","Removing tag..."):g("spoolbuddy.writeTag.untagSpool","Untag Selected Spool")})]})}function H0({className:t}){return r.jsxs("svg",{className:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:1.5,children:[r.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"}),r.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M12.53 18.22l-.53.53-.53-.53a.75.75 0 011.06 0z"})]})}const uct="spoolbuddy-default-core-weight";function mct(){try{const t=localStorage.getItem(uct);if(t){const e=parseInt(t,10);if(e>=0&&e<=500)return e}}catch{}return 250}function pct({spool:t,liveScaleWeight:e,persistedGrossWeight:a,onClose:n,onSyncWeight:i,onAssignToAms:s,isAssigned:o,onUnassignFromAms:l,className:c}){const{t:d}=wt(),[u,m]=y.useState(!1),[p,f]=y.useState(!1),[g,v]=y.useState(null),{data:b}=$e({queryKey:["spool-k-profiles",t.id],queryFn:()=>ne.getSpoolKProfiles(t.id),enabled:!t.k_profiles||t.k_profiles.length===0,staleTime:300*1e3}),x=t.k_profiles&&t.k_profiles.length>0?t.k_profiles:b,S=B1(t.rgba),k=t.core_weight&&t.core_weight>0?t.core_weight:mct(),C=e!==null?Math.round(Math.max(0,e)):null,N=g??(a!==void 0?a!==null?Math.round(Math.max(0,a)):null:C),T=Math.round(Math.max(0,(t.label_weight||0)-(t.weight_used||0))),P=C!==null&&C>=10?Math.round(Math.max(0,C-k)):T,E=Math.round(t.label_weight||1e3),z=E>0?Math.min(100,Math.round(P/E*100)):null,I=z!==null?z>50?"#22c55e":z>20?"#eab308":"#ef4444":"#808080",R=Math.max(0,(t.label_weight||0)-(t.weight_used||0))+k,K=C!==null?C-R:null,J=K!==null?Math.abs(K)<=50:null,X=Math.round(R),ce=N??X,de=t.nozzle_temp_min!=null&&t.nozzle_temp_max!=null?`${t.nozzle_temp_min}-${t.nozzle_temp_max}°C`:null,oe=t.slicer_filament_name||t.slicer_filament||null,Y=t.note?.trim()||null,ie=x&&x.length>0?Array.from(new Set(x.map(he=>he.k_value.toFixed(3)))).join(", "):null,me=async()=>{if(e===null)return;const he=Math.round(Math.max(0,e));m(!0);try{await an.updateSpoolWeight(t.id,he),v(he),f(!0),i?.(),setTimeout(()=>f(!1),3e3)}catch(xe){console.error("Failed to sync weight:",xe)}finally{m(!1)}};return r.jsxs("div",{className:`flex flex-col items-center space-y-4 max-w-md ${c??""}`,children:[r.jsxs("div",{className:"flex items-start gap-5",children:[r.jsxs("div",{className:"relative shrink-0",children:[r.jsx(vj,{color:S,isEmpty:!1,size:100}),z!==null&&r.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:I},children:[z,"%"]})]}),r.jsxs("div",{className:"flex-1 min-w-0 pt-1",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("h3",{className:"text-lg font-semibold text-zinc-100",children:t.color_name||"Unknown color"}),r.jsxs("span",{className:"text-xs font-mono text-zinc-500 shrink-0",children:["#",t.id]})]}),r.jsxs("p",{className:"text-sm text-zinc-400",children:[t.brand," • ",t.material,t.subtype&&` ${t.subtype}`]}),r.jsxs("div",{className:"mt-3",children:[r.jsxs("div",{className:"flex items-baseline gap-2",children:[r.jsxs("span",{className:"text-3xl font-bold font-mono text-zinc-100",children:[P,"g"]}),r.jsxs("span",{className:"text-sm text-zinc-500",children:["/ ",E,"g"]})]}),r.jsx("p",{className:"text-xs text-zinc-500 mt-0.5",children:d("spoolbuddy.spool.remaining","Remaining")}),r.jsx("div",{className:"mt-2 max-w-xs",children:r.jsx("div",{className:"h-2 bg-zinc-700 rounded-full overflow-hidden",children:r.jsx("div",{className:"h-full rounded-full transition-all duration-500",style:{width:`${z??0}%`,backgroundColor:I}})})})]})]})]}),r.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:[r.jsxs("div",{className:"flex justify-between",children:[r.jsx("span",{className:"text-zinc-500",children:d("spoolbuddy.dashboard.grossWeight","Gross weight")}),r.jsxs("span",{className:"font-mono text-zinc-300",children:[ce,"g"]})]}),r.jsxs("div",{className:"flex justify-between",children:[r.jsx("span",{className:"text-zinc-500",children:d("spoolbuddy.spool.coreWeight","Core")}),r.jsxs("span",{className:"font-mono text-zinc-300",children:[k,"g"]})]}),r.jsxs("div",{className:"flex justify-between",children:[r.jsx("span",{className:"text-zinc-500",children:d("spoolbuddy.dashboard.spoolSize","Spool size")}),r.jsxs("span",{className:"font-mono text-zinc-300",children:[E,"g"]})]}),r.jsxs("div",{className:"flex justify-between items-center",children:[r.jsx("span",{className:"text-zinc-500",children:d("spoolbuddy.spool.scaleWeight","Scale")}),C!==null?r.jsxs("span",{className:`flex items-center gap-1 font-mono ${J?"text-green-500":"text-yellow-500"}`,children:[C,"g",J?r.jsx(_r,{className:"w-3.5 h-3.5"}):r.jsxs(r.Fragment,{children:[r.jsx(xa,{className:"w-3.5 h-3.5"}),r.jsx("button",{onClick:me,className:"p-1 hover:bg-green-500/20 rounded transition-colors text-green-500",title:d("spoolbuddy.dashboard.syncWeight","Sync Weight"),children:r.jsx(tr,{className:"w-4 h-4"})})]})]}):r.jsx("span",{className:"text-zinc-500",children:"—"})]}),r.jsxs("div",{className:"flex justify-between items-center",children:[r.jsx("span",{className:"text-zinc-500",children:d("spoolbuddy.dashboard.tagId","Tag")}),r.jsx("span",{className:"font-mono text-xs text-zinc-400 truncate max-w-[120px]",title:t.tag_uid||"",children:t.tag_uid?t.tag_uid.slice(-8):"—"})]}),de&&r.jsxs("div",{className:"flex justify-between items-center",children:[r.jsx("span",{className:"text-zinc-500",children:d("spoolbuddy.inventory.nozzleTemp","Nozzle")}),r.jsx("span",{className:"font-mono text-zinc-300",children:de})]}),t.cost_per_kg!=null&&t.cost_per_kg>0&&r.jsxs("div",{className:"flex justify-between items-center",children:[r.jsx("span",{className:"text-zinc-500",children:d("spoolbuddy.inventory.costPerKg","Cost/kg")}),r.jsxs("span",{className:"font-mono text-zinc-300",children:[t.cost_per_kg.toFixed(2),"/kg"]})]}),ie&&r.jsxs("div",{className:"flex justify-between items-center",children:[r.jsx("span",{className:"text-zinc-500",children:d("spoolbuddy.inventory.kProfiles","K-Profile")}),r.jsx("span",{className:"font-mono text-zinc-300 truncate max-w-[220px] text-right",title:ie,children:ie})]}),oe&&r.jsxs("div",{className:"min-w-0",children:[r.jsx("p",{className:"text-xs text-zinc-500 mb-1",children:d("spoolbuddy.inventory.slicerFilament","Slicer Filament")}),r.jsx("p",{className:"text-sm text-zinc-300 whitespace-pre-wrap break-words",children:oe})]}),Y&&r.jsxs("div",{className:"col-span-2",children:[r.jsx("p",{className:"text-xs text-zinc-500 mb-1",children:d("spoolbuddy.inventory.note","Note")}),r.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:Y})]})]}),r.jsxs("div",{className:"flex gap-2 justify-center",children:[s&&r.jsx("button",{onClick:o?void 0:s,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:d("spoolbuddy.modal.assignToAms","Assign to AMS")}),l&&r.jsxs("button",{onClick:l,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:[r.jsx(pu,{className:"w-4 h-4 inline mr-1"}),d("inventory.unassignSpool")]}),r.jsx("button",{onClick:me,disabled:e===null||u,className:`px-5 py-2.5 rounded-lg text-sm font-medium transition-colors min-h-[44px] ${p?"bg-green-600/20 text-green-400":s?"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?"...":p?d("spoolbuddy.dashboard.weightSynced","Synced!"):d("spoolbuddy.dashboard.syncWeight","Sync Weight")}),n&&r.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:d("spoolbuddy.dashboard.close","Close")})]})]})}function hct(t){return B1(t.rgba)}function fct(t){return Math.max(0,t.label_weight-t.weight_used)}function gct(t){return t.label_weight<=0?0:Math.max(0,Math.min(100,(t.label_weight-t.weight_used)/t.label_weight*100))}function bct(t){const e=[t.material];return t.subtype&&e.push(t.subtype),e.join(" ")}function Wde(t){const e=t.ams_id===254||t.ams_id===255,a=!e&&t.ams_id>=128;return yk(t.ams_id,t.tray_id,a,e)}function xct({color:t,size:e=56}){return r.jsxs("svg",{width:e,height:e,viewBox:"0 0 56 56",children:[r.jsx("circle",{cx:"28",cy:"28",r:"26",fill:t}),r.jsx("circle",{cx:"28",cy:"28",r:"20",fill:t,style:{filter:"brightness(0.85)"}}),r.jsx("ellipse",{cx:"20",cy:"20",rx:"6",ry:"4",fill:"white",opacity:"0.3"}),r.jsx("circle",{cx:"28",cy:"28",r:"8",fill:"#2d2d2d"}),r.jsx("circle",{cx:"28",cy:"28",r:"5",fill:"#1a1a1a"})]})}function yct(){const{sbState:t,selectedPrinterId:e}=Jy(),{t:a}=wt(),{showToast:n}=oa(),i=na(),[s,o]=y.useState(""),[l,c]=y.useState("all"),[d,u]=y.useState(null),[m,p]=y.useState(!1),{data:f}=$e({queryKey:["spoolman-settings"],queryFn:ne.getSpoolmanSettings,staleTime:300*1e3}),g=f?.spoolman_enabled==="true"&&!!f?.spoolman_url,{data:v=[],isLoading:b,refetch:x}=$e({queryKey:g?["spoolman-inventory-spools"]:["inventory-spools"],queryFn:()=>g?ne.getSpoolmanInventorySpools(!1):ne.getSpools(!1),enabled:f!==void 0,refetchInterval:3e4}),{data:S=[]}=$e({queryKey:["spool-assignments"],queryFn:()=>ne.getAssignments(),refetchInterval:3e4,enabled:!g}),{data:k=[]}=$e({queryKey:["spoolman-slot-assignments"],queryFn:()=>ne.getSpoolmanSlotAssignments(),refetchInterval:3e4,enabled:g}),C=at({mutationFn:z=>ne.unassignSpoolmanSlot(z),onSuccess:()=>{i.invalidateQueries({queryKey:["spoolman-slot-assignments"]}),i.invalidateQueries({queryKey:["spoolman-inventory-spools"]})},onError:()=>n(a("inventory.unassignFailed","Failed to unassign spool"),"error")}),N=y.useMemo(()=>{if(g){const I={};return k.forEach(B=>{I[B.spoolman_spool_id]={ams_id:B.ams_id,tray_id:B.tray_id}}),I}const z={};return S.forEach(I=>{z[I.spool_id]={ams_id:I.ams_id,tray_id:I.tray_id,printer_name:I.printer_name}}),z},[g,S,k]),T=y.useMemo(()=>v.filter(z=>!z.archived_at),[v]),j=y.useMemo(()=>new Set(Object.keys(N).map(Number)),[N]),D=y.useMemo(()=>T.filter(z=>j.has(z.id)).length,[T,j]),P=y.useMemo(()=>{const z=new Set;return T.forEach(I=>z.add(I.material)),Array.from(z).sort()},[T]),E=y.useMemo(()=>{let z=T;if(l==="in_ams"?z=z.filter(I=>j.has(I.id)):l!=="all"&&(z=z.filter(I=>I.material===l)),s.trim()){const I=s.toLowerCase().trim();z=z.filter(B=>B.material.toLowerCase().includes(I)||B.subtype&&B.subtype.toLowerCase().includes(I)||B.brand&&B.brand.toLowerCase().includes(I)||B.color_name&&B.color_name.toLowerCase().includes(I)||B.note&&B.note.toLowerCase().includes(I))}return[...z].sort((I,B)=>{const R=j.has(I.id)?0:1,K=j.has(B.id)?0:1;return R!==K?R-K:new Date(B.updated_at).getTime()-new Date(I.updated_at).getTime()})},[T,l,s,j]);return r.jsxs("div",{className:"h-full flex flex-col",children:[r.jsxs("div",{className:"px-3 pt-3 pb-2 space-y-2.5",children:[r.jsxs("div",{className:"relative",children:[r.jsx(br,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-white/40"}),r.jsx("input",{type:"text",value:s,onChange:z=>o(z.target.value),placeholder:a("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"}),s&&r.jsx("button",{onClick:()=>o(""),className:"absolute right-2 top-1/2 -translate-y-1/2 text-white/40 hover:text-white/60",children:r.jsx(Ht,{className:"w-4 h-4"})})]}),r.jsxs("div",{className:"flex gap-1.5 overflow-x-auto no-scrollbar",children:[r.jsx(VL,{active:l==="all",onClick:()=>c("all"),label:`${a("spoolbuddy.inventory.all","All")} (${T.length})`,green:!0}),D>0&&r.jsx(VL,{active:l==="in_ams",onClick:()=>c("in_ams"),label:`${a("spoolbuddy.inventory.inAms","In AMS")} (${D})`}),P.map(z=>r.jsx(VL,{active:l===z,onClick:()=>c(l===z?"all":z),label:z},z))]})]}),r.jsx("div",{className:"flex-1 overflow-y-auto px-3 pb-3",children:b?r.jsx("div",{className:"flex items-center justify-center py-16",children:r.jsx("div",{className:"w-8 h-8 border-2 border-bambu-green border-t-transparent rounded-full animate-spin"})}):E.length===0?r.jsxs("div",{className:"flex flex-col items-center justify-center py-16 text-white/30",children:[r.jsx(Kr,{className:"w-12 h-12 mb-3"}),r.jsx("p",{className:"text-sm",children:s||l!=="all"?a("spoolbuddy.inventory.noResults","No spools match your filters"):a("spoolbuddy.inventory.empty","No spools in inventory")})]}):r.jsx("div",{className:"grid grid-cols-[repeat(auto-fill,minmax(130px,1fr))] gap-2",children:E.map(z=>r.jsx(vct,{spool:z,assignment:N[z.id],onClick:()=>u(z.id)},z.id))})}),d!=null&&(()=>{const z=v.find(B=>B.id===d);if(!z)return null;const I=()=>{u(null),p(!1)};return r.jsxs(r.Fragment,{children:[r.jsx(wct,{spool:z,assignment:N[z.id],sbState:t,onSyncWeight:()=>{x()},onAssignToAms:()=>p(!0),onUnassignFromAms:g&&N[z.id]?()=>C.mutate(z.id):void 0,onClose:I}),r.jsx($de,{isOpen:m,onClose:()=>p(!1),spool:z,printerId:e,spoolmanMode:g})]})})()]})}function VL({active:t,onClick:e,label:a,green:n}){return r.jsx("button",{onClick:e,className:`px-4 py-1.5 rounded-full text-sm font-medium border whitespace-nowrap shrink-0 transition-colors ${t?n?"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:a})}function vct({spool:t,assignment:e,onClick:a}){const n=hct(t),i=gct(t),s=fct(t),o=O1(t.color_name,t.rgba);return r.jsxs("button",{onClick:a,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:[r.jsx(xct,{color:n,size:56}),r.jsx("p",{className:"text-xs font-semibold text-white leading-tight truncate w-full",children:bct(t)}),r.jsxs("div",{className:"flex items-center gap-1 min-w-0 max-w-full",children:[r.jsx("span",{className:"w-2.5 h-2.5 rounded-full shrink-0 border border-white/10",style:al(t.rgba)}),r.jsx("span",{className:"text-[11px] text-white/50 truncate",children:o||"-"})]}),r.jsxs("div",{className:"w-full space-y-0.5",children:[r.jsx("div",{className:"h-1.5 bg-bambu-dark-tertiary rounded-full overflow-hidden",children:r.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)}%`}})}),r.jsxs("p",{className:"text-[11px] text-white/40",children:[Math.round(s),"g (",Math.round(i),"%)"]})]}),e&&r.jsx("span",{className:"px-2 py-0.5 rounded text-[10px] font-bold bg-bambu-green/20 text-bambu-green",children:Wde(e)})]})}function wct({spool:t,assignment:e,sbState:a,onSyncWeight:n,onAssignToAms:i,onUnassignFromAms:s,onClose:o}){const c=a.deviceOnline&&a.weight!==null?Math.round(a.weight):null,d=t.last_scale_weight!=null?Math.round(t.last_scale_weight):null;return r.jsx("div",{className:"fixed inset-0 z-50 bg-black/70 flex items-center justify-center p-4",onClick:o,children:r.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:u=>u.stopPropagation(),children:r.jsxs("div",{className:"space-y-3",children:[e&&r.jsxs("div",{className:"flex items-center justify-center gap-2",children:[r.jsx("span",{className:"px-2.5 py-1 rounded-md text-xs font-bold bg-bambu-green/20 text-bambu-green",children:Wde(e)}),e.printer_name&&r.jsx("span",{className:"text-xs text-zinc-400",children:e.printer_name})]}),r.jsx("div",{className:"flex justify-center",children:r.jsx(pct,{spool:t,liveScaleWeight:c,persistedGrossWeight:d,onSyncWeight:n,onAssignToAms:i,isAssigned:!!e,onUnassignFromAms:s,onClose:o,className:"max-w-md"})})]})})})}class Sct extends y.Component{state={error:null,errorInfo:null};static getDerivedStateFromError(e){return{error:e}}componentDidCatch(e,a){this.setState({errorInfo:a}),console.error("React crash:",e,a)}render(){return this.state.error?r.jsxs("div",{style:{padding:24,color:"#ef4444",backgroundColor:"#18181b",minHeight:"100vh",fontFamily:"monospace"},children:[r.jsx("h1",{style:{fontSize:20,marginBottom:12},children:"UI Crash"}),r.jsx("pre",{style:{whiteSpace:"pre-wrap",fontSize:14},children:this.state.error.message}),r.jsx("pre",{style:{whiteSpace:"pre-wrap",fontSize:12,color:"#a1a1aa",marginTop:12},children:this.state.error.stack}),r.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}}const kct=new Ife({defaultOptions:{queries:{staleTime:1e3*60,retry:1}}});function _ct(){return Ede(),null}function lZ({children:t}){return ilt(),r.jsx(r.Fragment,{children:t})}function cZ({children:t}){const{authEnabled:e,loading:a,user:n}=lr();return a?r.jsx("div",{className:"min-h-screen flex items-center justify-center",children:"Loading..."}):e&&!n?r.jsx(wg,{to:"/login",replace:!0}):r.jsx(r.Fragment,{children:t})}function CC({permission:t,children:e}){const{authEnabled:a,loading:n,user:i,hasPermission:s}=lr();return n?r.jsx("div",{className:"min-h-screen flex items-center justify-center",children:"Loading..."}):a?i?s(t)?r.jsx(r.Fragment,{children:e}):r.jsx(wg,{to:"/",replace:!0}):r.jsx(wg,{to:"/login",replace:!0}):r.jsx(r.Fragment,{children:e})}function Pct({children:t}){const{authEnabled:e,loading:a}=lr();return a?r.jsx("div",{className:"min-h-screen flex items-center justify-center",children:"Loading..."}):e?r.jsx(wg,{to:"/login",replace:!0}):r.jsx(r.Fragment,{children:t})}function Cct(){return r.jsx(Sct,{children:r.jsx(P0e,{children:r.jsx(Ofe,{client:kct,children:r.jsx(y0e,{children:r.jsx(v0e,{children:r.jsx(slt,{children:r.jsxs(h7e,{children:[r.jsx(_ct,{}),r.jsx(nfe,{children:r.jsxs(Dhe,{children:[r.jsx(Er,{path:"/setup",element:r.jsx(Pct,{children:r.jsx(alt,{})})}),r.jsx(Er,{path:"/login",element:r.jsx(tlt,{})}),r.jsx(Er,{path:"/camera/:printerId",element:r.jsx(Yst,{})}),r.jsx(Er,{path:"/overlay/:printerId",element:r.jsx(eot,{})}),r.jsxs(Er,{element:r.jsx(cZ,{children:r.jsx(lZ,{children:r.jsx(wlt,{})})}),children:[r.jsx(Er,{path:"spoolbuddy",element:r.jsx(Hlt,{})}),r.jsx(Er,{path:"spoolbuddy/ams",element:r.jsx(Glt,{})}),r.jsx(Er,{path:"spoolbuddy/write-tag",element:r.jsx(oct,{})}),r.jsx(Er,{path:"spoolbuddy/inventory",element:r.jsx(yct,{})}),r.jsx(Er,{path:"spoolbuddy/settings",element:r.jsx(rct,{})}),r.jsx(Er,{path:"spoolbuddy/calibration",element:r.jsx(ict,{})})]}),r.jsxs(Er,{element:r.jsx(cZ,{children:r.jsx(lZ,{children:r.jsx(K0e,{})})}),children:[r.jsx(Er,{index:!0,element:r.jsx(c7e,{})}),r.jsx(Er,{path:"archives",element:r.jsx(_at,{})}),r.jsx(Er,{path:"queue",element:r.jsx(xnt,{})}),r.jsx(Er,{path:"stats",element:r.jsx(Rnt,{})}),r.jsx(Er,{path:"profiles",element:r.jsx(gst,{})}),r.jsx(Er,{path:"maintenance",element:r.jsx(wst,{})}),r.jsx(Er,{path:"projects",element:r.jsx(_st,{})}),r.jsx(Er,{path:"projects/:id",element:r.jsx(jst,{})}),r.jsx(Er,{path:"inventory",element:r.jsx(Bot,{})}),r.jsx(Er,{path:"files",element:r.jsx(Hst,{})}),r.jsx(Er,{path:"files/trash",element:r.jsx(Vst,{})}),r.jsx(Er,{path:"makerworld",element:r.jsx(CC,{permission:"makerworld:view",children:r.jsx(Kot,{})})}),r.jsx(Er,{path:"settings",element:r.jsx(CC,{permission:"settings:read",children:r.jsx(Wit,{})})}),r.jsx(Er,{path:"groups/new",element:r.jsx(CC,{permission:"groups:create",children:r.jsx(WX,{})})}),r.jsx(Er,{path:"groups/:id/edit",element:r.jsx(CC,{permission:"groups:update",children:r.jsx(WX,{})})}),r.jsx(Er,{path:"users",element:r.jsx(wg,{to:"/settings?tab=users",replace:!0})}),r.jsx(Er,{path:"groups",element:r.jsx(wg,{to:"/settings?tab=users",replace:!0})}),r.jsx(Er,{path:"system",element:r.jsx(Zot,{})}),r.jsx(Er,{path:"notifications",element:r.jsx(rlt,{})}),r.jsx(Er,{path:"gcode-viewer",element:r.jsx(nlt,{})}),r.jsx(Er,{path:"external/:id",element:r.jsx(tot,{})}),r.jsx(Er,{path:"camera-tokens",element:r.jsx(wg,{to:"/settings?tab=apikeys#card-camera-tokens",replace:!0})})]})]})})]})})})})})})})}_me.createRoot(document.getElementById("root")).render(r.jsx(y.StrictMode,{children:r.jsx(Cct,{})})); diff --git a/static/index.html b/static/index.html index d10b0f82b..29a93a42d 100644 --- a/static/index.html +++ b/static/index.html @@ -26,7 +26,7 @@ - +