From 080176c6e5da049a1a106576fae35e77b769dd9c Mon Sep 17 00:00:00 2001 From: maziggy Date: Sun, 10 May 2026 10:15:07 +0200 Subject: [PATCH] fix(filament-mapping): X2D/H2D dual-nozzle without AMS lost external-spool extruder routing (#1257) X2D with 0 AMS units and two external spools (Ext-L feeding left extruder, Ext-R feeding right) showed "Required filament type not found in printer" even when the matching filament was physically loaded. Cause: useFilamentMapping derived dual-nozzle status from ams_extruder_map being non-empty -- that map is populated from AMS info bits, so dual-nozzle printers without AMS got an empty map and hasDualNozzle=false. External spools then fell through to extruderId=undefined, and the nozzle-aware filter rejected every candidate because undefined !== 0/1. Prefer the hardware-reported printerStatus.nozzles array length as the dual-nozzle signal -- populated regardless of AMS configuration -- and keep the ams_extruder_map branch as fallback for older firmware that might not surface nozzles. Affects all dual-nozzle printers running without AMS: X2D, H2D, X2 Pro. Regression test pins both layers the bug straddled -- buildLoadedFilaments extruderId assignment per external spool, and computeAmsMapping picking the correct external for a per-nozzle requirement -- so a future change that re-breaks either fails CI. --- CHANGELOG.md | 2 + .../hooks/useFilamentMapping.test.ts | 63 +++++++++++++++++++ frontend/src/hooks/useFilamentMapping.ts | 14 ++++- .../{index-CwfrW2a1.js => index-CBFhMIk6.js} | 2 +- static/index.html | 2 +- 5 files changed, 80 insertions(+), 3 deletions(-) rename static/assets/{index-CwfrW2a1.js => index-CBFhMIk6.js} (99%) diff --git a/CHANGELOG.md b/CHANGELOG.md index 397270321..0ba12149d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,8 @@ All notable changes to Bambuddy will be documented in this file. - **Copy spool — duplicate any spool's settings into a fresh inventory row in two clicks** ([#1234](https://github.com/maziggy/bambuddy/issues/1234), [PR #1246](https://github.com/maziggy/bambuddy/pull/1246) by @MiguelAngelLV) — Adds a copy button (`Copy` icon) next to the existing edit button on every spool in the inventory page across all three views (table row, card, grouped table inner row). Clicking it opens the existing `SpoolFormModal` pre-filled with every field from the source spool — material, brand, color, slicer preset, label/core/cost, K-profiles, all of it — except `weight_used` which is reset to 0 (since the new spool starts full) and the RFID identity fields (`tag_uid`, `tray_uuid`, `tag_type`, `data_origin`) which aren't part of the form payload anyway, so the new spool is its own physical roll. Save calls `api.createSpool` (or `api.createSpoolmanInventorySpool` in Spoolman mode — both inherit the dispatch routing for free). Closes the long-running gap where users with many near-identical spools (e.g. five 1 kg PETG-CF rolls bought in a single order) had to re-enter every field from scratch on each one. **Implementation shape:** `SpoolFormModalProps.mode: 'create' | 'edit' | 'copy'` (exported as `SpoolFormMode`) replaces the previous `isEditing = !!spool` heuristic — every existing call site in `InventoryPage.tsx` was updated to pass the explicit mode, and the modal's title / submit-button label / weight-reset gate / submit-route branching all key on `mode` directly. The `onCopy` callback is optional on `SpoolCard`, `SpoolTableRow`, and `SpoolTableGroup` (matches the existing `onPrintLabel?` pattern), so the button is conditionally rendered and other consumers of those subcomponents don't get a copy affordance forced on them. Card-view and table-row buttons stop click propagation so clicking copy doesn't also fire the parent row's edit handler. **Quick Add interaction:** the Quick Add toggle is gated `mode === 'create'` (was `!isEditing`), so it stays out of copy mode — otherwise a user could enable Quick Add and bump quantity to N under the singular "Copy Spool" title and silently bulk-create N copies via `bulkCreateMutation`. **i18n:** new `inventory.copySpool` key across all 8 locales (en + de translated, fr/it/ja/pt-BR/zh-CN/zh-TW seeded with English fallback per project flow). **Tests:** 3 new in `SpoolFormModal.test.tsx` (`SpoolFormModal copy mode` describe block — title shows "Copy Spool", save calls `createSpool` not `updateSpool`, `weight_used` reset to 0 in the create payload when copying a spool with non-zero usage), 2 new in `InventoryPageCopyButton.test.tsx` (table-row copy button click → "Copy Spool" heading, cards-view copy button click → same heading after switching view modes) — guards against the three call sites drifting apart. Existing `SpoolFormBulk.test.tsx` and `SpoolFormModal.test.tsx` renders that omitted the `mode` prop were updated with the explicit `mode="create"` so the tightened Quick Add gate doesn't hide the toggle from them. Both `InventoryPageCopyButton.test.tsx` and `InventoryPageDeepLink.test.tsx` gained MSW handlers for the modal's open-time fetches (`/api/v1/cloud/status`, `/api/v1/cloud/local-presets`, `/api/v1/cloud/builtin-filaments`, `/api/v1/inventory/color-catalog`, `/api/v1/inventory/spool-catalog`, `/api/v1/printers/`) — without them MSW passes through to the real network, ECONNREFUSEs, and the rejected fetch resolves after the test environment is torn down, surfacing as a flaky "window is not defined" unhandled rejection in the modal's `setLoadingCloudPresets(false)` finally block (pre-existing flake hit ~1 in 3 full-suite runs at PR head). ### Fixed +- **X2D / H2D dual-nozzle without AMS: filament mapping reported "Required filament type not found in printer" even when the spools were physically loaded** ([#1257](https://github.com/maziggy/bambuddy/issues/1257)) — Repro: X2D with 0 AMS units, two external spools (Ext-L feeding left extruder, Ext-R feeding right), print job specifies `nozzle_id` per filament. The Schedule Print modal showed the orange "Filament Mapping (Type not found)" header and a forced manual slot picker, even though the matching PETG was sitting right there in the external spool holder. **Cause:** `frontend/src/hooks/useFilamentMapping.ts:18-19` derived dual-nozzle status solely from `printerStatus.ams_extruder_map` being non-empty. That map is populated from AMS units' info bits, so a dual-nozzle printer with zero AMS units gets an empty map → `hasDualNozzle = false` → external spools' `extruderId` falls through to `undefined` (line 64 ternary fallback). The downstream nozzle-aware filter at lines 117 / 377 (`available.filter((f) => f.extruderId === req.nozzle_id)`) then rejected every loaded filament because `undefined !== 0/1` for any non-null `nozzle_id`. The PETG was loaded, just incorrectly stripped from the candidate set during matching. **Fix:** widen the dual-nozzle inference to three independent signals OR'd together: (1) `nozzles[1].nozzle_diameter` populated — the most direct signal, set by `bambu_mqtt.py:2619-2621` only when the printer reports a `right_nozzle_diameter` MQTT field, so a populated value always implies real second-nozzle hardware; (2) `ams_extruder_map` non-empty — preserved as fallback for the dual-nozzle-with-AMS case the original code already handled; (3) `vt_tray.length > 1` — single-nozzle printers (P1S / A1 / X1C) only have one external feed, so multiple external trays only exist on dual-nozzle hardware. The first signal alone is *not* sufficient because the backend `state.nozzles` defaults to a 2-entry list with empty `NozzleInfo()` stubs (`bambu_mqtt.py:160`) on every printer, single-nozzle included — `nozzles.length` would always be 2 on the wire and would have regressed every single-nozzle install. Affects all dual-nozzle printers running without AMS: X2D, H2D, X2 Pro. **Tests:** two new regressions in `src/__tests__/hooks/useFilamentMapping.test.ts`. `matches external spools per-extruder on dual-nozzle without AMS` pins the bug fix — asserts each external spool gets the correct `extruderId` (1 for Ext-L id=254, 0 for Ext-R id=255) and `computeAmsMapping` picks Ext-L for a left-nozzle requirement. `does not fabricate extruderId for single-nozzle with stub nozzles[1]` is the matching guard — asserts that a P1S / A1 / X1C-shape PrinterStatus (with the default-stub second nozzle entry the backend always emits) does NOT trip the dual-nozzle inference, so single-nozzle external spools keep `extruderId=undefined` exactly as they did pre-fix. Together they pin both directions: a future change that re-breaks the X2D path fails CI, and one that mistakenly turns single-nozzle printers into dual-nozzle also fails CI. Full frontend suite (1891 tests across 138 files) green. + - **GCode Viewer had no in-app way to navigate back — the only exit was the browser's back button** — Opening the GCode Viewer from a File Manager card or an Archive card calls `navigate('/gcode-viewer?archive=…' | '?library_file=…')`, which mounts `GCodeViewerPage` as a full-height iframe inside the Layout shell. The page rendered nothing but the iframe, so once the third-party viewer's UI took over the content area there was no in-app affordance to return to the originating list — only the browser's back button. Reported by @maziggy. **Fix:** added a thin back bar above the iframe in `frontend/src/pages/GCodeViewerPage.tsx` with an `ArrowLeft` icon button. The button label adapts to the entry point — `Back to Print Archives` when the URL carries `?archive=`, `Back to File Manager` when it carries `?library_file=`, generic `Back` otherwise (covers the rare deep-link / shared-URL case). Click prefers `navigate(-1)` so the user lands back in their original list with scroll position and filters preserved; falls back to `/archives` or `/files` when the page was opened in a fresh tab and there's no SPA history to return to. Iframe height is now `flex: 1` inside a flex column under the bar instead of a hard-coded `calc(100vh - 3.5rem)` — the layout's existing fixed-header offset is unchanged, only the back bar (~36 px) is subtracted from the viewer's vertical real estate. **i18n:** new `gcodeViewer.{back,backToArchives,backToFiles}` namespace added to all 8 locales (en + de fully translated, fr/it/ja/pt-BR/zh-CN/zh-TW translated to native using each locale's existing page-title vocabulary — `Druckarchiv`/`Dateimanager`, `Archives d'impression`/`Gestionnaire de fichiers`, `Archivi di stampa`/`Gestore file`, `印刷アーカイブ`/`ファイル管理`, `Arquivos de impressão`/`Gerenciador de arquivos`, `打印归档`/`文件管理器`, `列印歸檔`/`檔案管理器`). - **Archives card's "Reprint" / "Schedule" / "Slice" button labels truncated to "Re..." / "Sc..." on narrow browser windows** ([#1249](https://github.com/maziggy/bambuddy/issues/1249)) — The action row on each archive card has six buttons: two labelled (Reprint + Schedule, or Slice when the file isn't sliced yet) plus four icon-only utilities (open in slicer, external link, globe, download, trash). The labelled buttons used `flex-1` to share whatever space remained after the four fixed-width icon buttons, with the label rendered as `...` — i.e. visible at any viewport ≥ 640px, with `truncate` ellipsizing when there isn't room. **The Tailwind viewport breakpoint can't see the card width.** The page's grid grows column count alongside viewport (`md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4`), so cards stay roughly 320–380 px wide across breakpoints and the leftover ~30 px in each labelled button isn't enough for "Reprint", which lands on screen as "Re..." — repro'd from a small browser window in the reporter's case. **Fix:** breakpoint bumped from `hidden sm:inline` → `hidden xl:inline` on all three labelled buttons (Reprint at line 1106, Schedule at line 1117, Slice at line 1153 of `frontend/src/pages/ArchivesPage.tsx`). Labels now appear only at viewport ≥ 1280px where the cards (3-4 columns of ~320 px) actually have headroom for them; on narrow windows the buttons render icon-only with their existing `title=` tooltip kept intact for hover and assistive-tech disclosure. Trade-off accepted: a wide-viewport-with-wide-sidebar setup that compresses the card to under ~320px will still see the truncation, but that's a corner case — the common "small browser window" path is fixed without restructuring the row. - **Spool form's "Slicer Preset" dropdown silently dropped Local Profiles when Bambu Cloud was connected, and collapsed per-printer/per-nozzle variants of cloud and local presets into a single entry** ([#1248](https://github.com/maziggy/bambuddy/issues/1248), reported by @andretietz) — Two distinct defects in the same code path. **Defect 1 (the reported bug):** `buildFilamentOptions` in `frontend/src/components/spool-form/utils.ts` was precedence-based — `if (cloudPresets.length > 0)` returned the cloud list and never reached the local-presets branch, so any Local Profile imported via Profiles → Local Profiles was silently invisible whenever the user was logged into Bambu Cloud (the same profile rendered fine with a green `Local` badge in the AMS Slot configuration modal). The wiki documents the dropdown as "merged and deduplicated" across cloud + local + built-in. **Defect 2 (surfaced during fix verification):** the spool form was collapsing all `@Bambu Lab P1S 0.4 nozzle` / `@Bambu Lab X1C 0.4 nozzle` / `@Bambu Lab A1 0.4 nozzle` variants of "Bambu PLA Basic" into a single dropdown entry by stripping the `@printer` suffix and dedup'ing by base name (one Map.set per family for cloud defaults, one per family for local presets). The AMS Slot modal lists each variant individually and filters by the active printer model, so the user observed strictly more entries in the AMS Slot than in the Add Spool modal even after the merge fix. The right semantic for the spool form — printer-agnostic by design, since a spool isn't bound to a printer — is to show every variant as its own row, exactly as if you'd summed the AMS Slot's per-printer-filtered output across all printers. **Fix:** rewrote `buildFilamentOptions` to (a) actually merge all three sources, dropping the precedence early-return, and (b) push each cloud `setting_id` and each `LocalPreset` row as its own `FilamentOption` instead of collapsing by `name.replace(/@.*$/, '')`. `displayName` now keeps the full `@printer 0.4 nozzle` suffix so users can pick the right variant. Built-in dedup against cloud setting_id is preserved (mirrors `ConfigureAmsSlotModal.tsx:498` exactly). Wired `api.getBuiltinFilaments()` into both callers — `SpoolFormModal` and `SpoolBuddyWriteTagPage`. **Persistence safety:** the saved `slicer_filament` shape is unchanged — cloud picks still persist their `setting_id`, local picks still persist `preset.filament_type || String(preset.id)` (consumed by `backend/app/utils/filament_ids.py::normalize_slicer_filament` which expects `GFL05`/`GFSL05` shapes; persisting the bare LocalPreset row id would break slicing). Local-preset `allCodes` now carries both the `filament_type` form and the `String(preset.id)` form so `findPresetOption` resolves both old (pre-fix) and new picks. **React-key collision:** with collapse removed, two LocalPreset rows can share the same `code` if they share `filament_type`; the dropdown key in `FilamentSection.tsx` is now composed `${option.code}::${option.name}` to stay unique. **Tests:** new `frontend/src/__tests__/components/spool-form/buildFilamentOptions.test.ts` with 9 cases — the #1248 regression case, "one entry per cloud setting_id, no @printer collapse", "list each local preset individually", "@printer suffix preserved in displayName", local `allCodes` carrying both shapes, the `GFA00`↔`GFSA00` built-in dedup, the all-empty fallback, and the alphabetical sort. The two existing `vi.mock('../../api/client')` blocks in `SpoolFormModal.test.tsx` and `SpoolFormBulk.test.tsx` were updated with the new `getBuiltinFilaments` stub. diff --git a/frontend/src/__tests__/hooks/useFilamentMapping.test.ts b/frontend/src/__tests__/hooks/useFilamentMapping.test.ts index 470a3cfd6..98b12553b 100644 --- a/frontend/src/__tests__/hooks/useFilamentMapping.test.ts +++ b/frontend/src/__tests__/hooks/useFilamentMapping.test.ts @@ -606,6 +606,69 @@ describe('computeAmsMapping - nozzle filtering', () => { expect(result).toEqual([1]); // Picks AMS 0 tray 1 (PETG green) regardless of nozzle }); + // X2D / H2D / X2 Pro with no AMS but two external spools (one feeding each + // extruder). Pre-fix, dual-nozzle was inferred from `ams_extruder_map` being + // non-empty, which fails when there are no AMS units — both vt_tray entries + // got `extruderId=undefined`, the per-nozzle filter rejected everything, and + // the UI surfaced "Required filament type not found in printer" even though + // the matching filament was sitting in the external spool. (#1257) + it('matches external spools per-extruder on dual-nozzle without AMS', () => { + const reqs = { + filaments: [ + { slot_id: 1, type: 'PETG', color: '#FFFFFF', used_grams: 15, nozzle_id: 1 }, // Left + ], + }; + const status = createPrinterStatus([], [ + // Two external spools, both PETG. Ext-L (id=254) feeds left extruder (1), + // Ext-R (id=255) feeds right (0). 255 - id formula in buildLoadedFilaments + // routes them when hasDualNozzle is true. + { id: 254, tray_type: 'PETG', tray_color: 'FFFFFF' } as PrinterStatus['vt_tray'][number], + { id: 255, tray_type: 'PETG', tray_color: '000000' } as PrinterStatus['vt_tray'][number], + ]); + // Real X2D hardware: both nozzles report a populated diameter via the + // MQTT right_nozzle_diameter / left_nozzle_diameter fields. ams_extruder_map + // is empty because there are zero AMS units. + (status as any).nozzles = [ + { nozzle_type: 'stainless_steel', nozzle_diameter: '0.4' }, + { nozzle_type: 'stainless_steel', nozzle_diameter: '0.4' }, + ]; + (status as any).ams_extruder_map = {}; + + // Loaded filaments must surface extruderId on each external entry, + // otherwise computeAmsMapping's per-nozzle filter strips them out. + const loaded = buildLoadedFilaments(status); + expect(loaded).toHaveLength(2); + expect(loaded.find((f) => f.globalTrayId === 254)?.extruderId).toBe(1); // Ext-L → left + expect(loaded.find((f) => f.globalTrayId === 255)?.extruderId).toBe(0); // Ext-R → right + + // Mapping must succeed and pick Ext-L (left extruder, white PETG). + const result = computeAmsMapping(reqs, status); + expect(result).toEqual([254]); + }); + + // Sibling regression: the bambu_mqtt state defaults `nozzles` to a 2-entry + // list with empty NozzleInfo() stubs even on single-nozzle printers, and the + // route emits both entries on the wire. The dual-nozzle inference must NOT + // be tripped by a stub second entry — only by populated hardware info, + // populated ams_extruder_map, or >1 external trays. Pin: single-nozzle + // printer (P1S/A1/X1C) with one external spool gets extruderId=undefined, + // matching pre-fix behaviour. (#1257) + it('does not fabricate extruderId for single-nozzle with stub nozzles[1]', () => { + const status = createPrinterStatus([], [ + { id: 254, tray_type: 'PLA', tray_color: 'FF0000' } as PrinterStatus['vt_tray'][number], + ]); + // Single-nozzle: nozzles[1] is the default stub (empty fields). + (status as any).nozzles = [ + { nozzle_type: 'stainless_steel', nozzle_diameter: '0.4' }, + { nozzle_type: '', nozzle_diameter: '' }, + ]; + (status as any).ams_extruder_map = {}; + + const loaded = buildLoadedFilaments(status); + expect(loaded).toHaveLength(1); + expect(loaded[0].extruderId).toBeUndefined(); + }); + it('still applies nozzle filter when FTS object is null', () => { // Sanity check: explicit null fila_switch behaves like no FTS — nozzle // filter still applies on real dual-nozzle printers. diff --git a/frontend/src/hooks/useFilamentMapping.ts b/frontend/src/hooks/useFilamentMapping.ts index 3857944f1..8fc920a85 100644 --- a/frontend/src/hooks/useFilamentMapping.ts +++ b/frontend/src/hooks/useFilamentMapping.ts @@ -16,7 +16,19 @@ import type { PrinterStatus } from '../api/client'; export function buildLoadedFilaments(printerStatus: PrinterStatus | undefined): LoadedFilament[] { const filaments: LoadedFilament[] = []; const amsExtruderMap = printerStatus?.ams_extruder_map; - const hasDualNozzle = amsExtruderMap && Object.keys(amsExtruderMap).length > 0; + // Dual-nozzle detection. The backend always emits a 2-entry nozzles array + // (default-stub second entry for single-nozzle printers), so length is not + // a reliable signal. Real second-nozzle hardware sets `nozzle_diameter` from + // the MQTT `right_nozzle_diameter` field (bambu_mqtt.py:2619-2621); without + // that field, nozzles[1] stays at its empty default. Belt-and-braces: a + // populated ams_extruder_map (dual-nozzle with AMS) and >1 vt_tray (only + // dual-nozzle hardware exposes multiple external feeds) each independently + // imply dual-nozzle — keep them as fallbacks for any firmware rev that + // surfaces one signal but not the other. (#1257) + const hasDualNozzle = + Boolean(printerStatus?.nozzles?.[1]?.nozzle_diameter) + || (amsExtruderMap && Object.keys(amsExtruderMap).length > 0) + || (printerStatus?.vt_tray?.length ?? 0) > 1; // Add filaments from all AMS units (regular and HT) printerStatus?.ams?.forEach((amsUnit) => { diff --git a/static/assets/index-CwfrW2a1.js b/static/assets/index-CBFhMIk6.js similarity index 99% rename from static/assets/index-CwfrW2a1.js rename to static/assets/index-CBFhMIk6.js index 66cce3b45..9913c8bb8 100644 --- a/static/assets/index-CwfrW2a1.js +++ b/static/assets/index-CBFhMIk6.js @@ -8510,7 +8510,7 @@ void main() { ${l("inventory.assignProfileMismatchMessage",{spoolProfile:T.spoolProfile||l("common.unknown"),trayProfile:T.trayProfile||l("common.unknown"),location:s.location})}`:T.type==="partial_profile"?K=`${l("inventory.assignPartialMismatchMessage",{spoolMaterial:T.spoolMaterial,trayMaterial:T.trayMaterial,location:s.location})} -${l("inventory.assignProfileMismatchMessage",{spoolProfile:T.spoolProfile||l("common.unknown"),trayProfile:T.trayProfile||l("common.unknown"),location:s.location})}`:T.type==="profile"&&(K=l("inventory.assignProfileMismatchMessage",{spoolProfile:T.spoolProfile||l("common.unknown"),trayProfile:T.trayProfile||l("common.unknown"),location:s.location})),r.jsx(vn,{title:l("inventory.assignMismatchTitle"),message:K,confirmText:l("inventory.assignMismatchConfirm"),variant:"warning",isLoading:re.isPending,onConfirm:$,onCancel:()=>{re.isPending||(P(!1),N(null),A(null))}})})()]})}function AK(t,e){if(t===255)return"External";let n,a=!1;t>=128&&t<=135?(n=t-128,a=!0):t>=0&&t<=3?(n=t,a=e===1):n=0,n=Math.max(0,Math.min(n,7));const i=String.fromCharCode(65+n);return a?`HT-${i}`:`AMS-${i}`}function o3(t){const e=t.includes("_")?t.split("_")[0]:t;return e.startsWith("GFS")?"GF"+e.slice(3):(e.startsWith("PFUS")||e.startsWith("PFSP"),e)}const tw=["PLA","PETG","PCTG","ABS","ASA","TPU","PC","PA","NYLON","PVA","HIPS","PP","PET"];function jK(t){const e=t.replace(/@.+$/,"").trim(),n=e.toUpperCase(),a=n.match(/\bSUPPORT\s+FOR\s+/);if(a){const s=n.slice(a.index+a[0].length);for(const o of tw)if(new RegExp(`\\b${o}\\b`).test(s)){const c=e.slice(0,a.index).trim();return{material:o,brand:c,variant:"Support"}}}for(const s of tw){const o=new RegExp(`\\b${s}\\b`,"i");if(o.test(n)){const l=e.split(o),c=l[0]?.trim()||"",d=l[1]?.trim()||"";return{material:s,brand:c,variant:d}}}const i=e.split(/\s+/);return i.length>=2?{material:i[1],brand:i[0],variant:i.slice(2).join(" ")}:{material:e,brand:"",variant:""}}function s7e(t){return!t.startsWith("GF")&&!t.startsWith("P1")}const o7e={white:"FFFFFF",black:"000000",red:"FF0000",green:"00FF00",blue:"0000FF",yellow:"FFFF00",cyan:"00FFFF",magenta:"FF00FF",orange:"FFA500",purple:"800080",pink:"FFC0CB",brown:"8B4513",gray:"808080",grey:"808080","jade white":"FFFEF2",ivory:"FFFFF0",beige:"F5F5DC",cream:"FFFDD0",silver:"C0C0C0",gold:"FFD700",bronze:"CD7F32",copper:"B87333",navy:"000080",teal:"008080",olive:"808000",maroon:"800000",coral:"FF7F50",salmon:"FA8072",lime:"32CD32",mint:"98FF98","forest green":"228B22","sky blue":"87CEEB","royal blue":"4169E1",turquoise:"40E0D0",lavender:"E6E6FA",violet:"EE82EE",plum:"DDA0DD",tan:"D2B48C",chocolate:"D2691E",charcoal:"36454F",slate:"708090",transparent:"000000",natural:"F5F5DC",wood:"DEB887"},MK=[{name:"White",hex:"FFFFFF"},{name:"Black",hex:"000000"},{name:"Red",hex:"FF0000"},{name:"Blue",hex:"0000FF"},{name:"Green",hex:"00AA00"},{name:"Yellow",hex:"FFFF00"},{name:"Orange",hex:"FFA500"},{name:"Gray",hex:"808080"}],EK=[{name:"Cyan",hex:"00FFFF"},{name:"Magenta",hex:"FF00FF"},{name:"Purple",hex:"800080"},{name:"Pink",hex:"FFC0CB"},{name:"Brown",hex:"8B4513"},{name:"Beige",hex:"F5F5DC"},{name:"Navy",hex:"000080"},{name:"Teal",hex:"008080"},{name:"Lime",hex:"32CD32"},{name:"Gold",hex:"FFD700"},{name:"Silver",hex:"C0C0C0"},{name:"Maroon",hex:"800000"},{name:"Olive",hex:"808000"},{name:"Coral",hex:"FF7F50"},{name:"Salmon",hex:"FA8072"},{name:"Turquoise",hex:"40E0D0"},{name:"Violet",hex:"EE82EE"},{name:"Indigo",hex:"4B0082"},{name:"Chocolate",hex:"D2691E"},{name:"Tan",hex:"D2B48C"},{name:"Slate",hex:"708090"},{name:"Charcoal",hex:"36454F"},{name:"Ivory",hex:"FFFFF0"},{name:"Cream",hex:"FFFDD0"}];function DK(t){const e=t.toLowerCase().trim();return o7e[e]||null}function l7e(t){const e=t.indexOf("@");if(e<0)return null;const a=t.slice(e+1).trim().match(/^BBL\s+(.+?)(?:\s+[\d.]+\s*nozzle)?$/i);return a?a[1].trim():null}function Iie({isOpen:t,onClose:e,printerId:n,slotInfo:a,nozzleDiameter:i="0.4",printerModel:s,onSuccess:o,fullScreen:l}){const{t:c}=kt(),[d,u]=v.useState(""),[m,p]=v.useState(null),[f,b]=v.useState(""),[w,g]=v.useState(""),[x,_]=v.useState(""),[N,C]=v.useState(!1),[P,T]=v.useState(!1),A=v.useRef(""),{data:F,isLoading:S,isError:M}=Ke({queryKey:["cloudSettings"],queryFn:()=>se.getCloudSettings(),enabled:t,retry:!1}),{data:z,isLoading:I}=Ke({queryKey:["localPresets"],queryFn:()=>se.getLocalPresets(),enabled:t}),{data:H,isLoading:L}=Ke({queryKey:["builtinFilaments"],queryFn:()=>se.getBuiltinFilaments(),enabled:t,staleTime:1/0}),{data:Z,isLoading:re}=Ke({queryKey:["kprofiles",n,i],queryFn:()=>se.getKProfiles(n,i),enabled:t&&!!n}),{data:J}=Ke({queryKey:["colorCatalog"],queryFn:()=>se.getColorCatalog(),enabled:t,staleTime:1/0}),de=at({mutationFn:async()=>{if(!d)throw new Error("No filament preset selected");const j=d.startsWith("local_"),B=d.startsWith("builtin_"),X=j?parseInt(d.replace("local_",""),10):null,O=B?d.replace("builtin_",""):null,ie=j?z?.filament.find(Ee=>Ee.id===X):null,U=B?H?.find(Ee=>Ee.filament_id===O):null,G=!j&&!B?F?.filament.find(Ee=>Ee.setting_id===d):null;if(!j&&!B&&!G)throw new Error("Selected preset not found");if(j&&!ie)throw new Error("Selected local preset not found");if(B&&!U)throw new Error("Selected builtin preset not found");const Y=j?ie.name:B?U.name:G.name,Q=jK(Y),oe=m?.slot_id??-1,ee=f||a.trayColor?.slice(0,6)||"FFFFFF",ge=Y.replace(/@.+$/,"").trim();let ce,le;const q=Q.material.toUpperCase();if(j){const Ee=(tw.includes(q)?q:ie?.filament_type||Q.material||"").toUpperCase(),ze={PLA:"GFL99","PLA-CF":"GFL98","PLA SILK":"GFL96","PLA HIGH SPEED":"GFL95",PETG:"GFG99","PETG HF":"GFG96","PETG-CF":"GFG98",PCTG:"GFG97",ABS:"GFB99",ASA:"GFB98",PC:"GFC99",PA:"GFN99","PA-CF":"GFN98",NYLON:"GFN99",TPU:"GFU99",PVA:"GFS99",HIPS:"GFS98",PE:"GFP99",PP:"GFP97"};ce=ze[Ee]||ze[Ee.replace(/[-\s]?CF$/,"")]||ze[Ee.replace(/\+$/,"")]||ze[Ee.split(/[-\s]/)[0]]||"",le=""}else if(B)ce=O,le="";else if(ce=o3(d),le=d,!d.startsWith("GFS"))try{const Ee=await se.getCloudSettingDetail(d);Ee.filament_id&&(ce=Ee.filament_id)}catch(Ee){console.warn("Failed to fetch preset detail for filament_id:",Ee)}let R=j&&ie?.nozzle_temp_min?ie.nozzle_temp_min:190,ne=j&&ie?.nozzle_temp_max?ie.nozzle_temp_max:230;if(!j||B||!ie?.nozzle_temp_min&&!ie?.nozzle_temp_max){const Ee=(j?tw.includes(q)?q:ie?.filament_type||Q.material||"":Q.material).toUpperCase();Ee.includes("PLA")?(R=190,ne=230):Ee.includes("PETG")?(R=220,ne=260):Ee.includes("ABS")||Ee.includes("ASA")?(R=240,ne=280):Ee.includes("TPU")?(R=200,ne=240):Ee==="PCTG"?(R=220,ne=260):Ee.includes("PC")?(R=260,ne=300):(Ee.includes("PA")||Ee.includes("NYLON"))&&(R=250,ne=290)}const be=m?.k_value?parseFloat(m.k_value):0,Se=j?tw.includes(q)?q:ie?.filament_type||Q.material||"PLA":Q.material||"PLA",Ne=await se.configureAmsSlot(n,a.amsId,a.trayId,{tray_info_idx:ce,tray_type:Se,tray_sub_brands:ge,tray_color:ee+"FF",nozzle_temp_min:R,nozzle_temp_max:ne,cali_idx:oe,nozzle_diameter:i,setting_id:le,kprofile_filament_id:m?.filament_id,kprofile_setting_id:m?.setting_id||void 0,k_value:be}),ve=j?`local_${X}`:B?`builtin_${O}`:d,xe=j?"local":B?"builtin":"cloud";try{await se.saveSlotPreset(n,a.amsId,a.trayId,ve,ge,xe)}catch(Ee){console.warn("Failed to save slot preset mapping:",Ee)}return Ne},onSuccess:()=>{C(!0),o?.(),setTimeout(()=>{C(!1),e()},1500)}}),me=at({mutationFn:async()=>se.resetAmsSlot(n,a.amsId,a.trayId),onSuccess:()=>{C(!0),o?.(),setTimeout(()=>{C(!1),e()},1500)}}),ue=v.useMemo(()=>{const j=x.toLowerCase(),B=[],X=new Set,O=a.savedPresetId,ie=a.trayInfoIdx;if(F?.filament)for(const U of F.filament){X.add(U.setting_id);const Y=O===U.setting_id||ie&&(U.setting_id===ie||o3(U.setting_id)===ie);if(!(j&&!U.name.toLowerCase().includes(j))){if(!Y&&s){const Q=l7e(U.name);if(Q&&Q.toUpperCase()!==s.toUpperCase())continue}B.push({id:U.setting_id,name:U.name,source:"cloud",isUser:s7e(U.setting_id)})}}if(z?.filament)for(const U of z.filament){const G=`local_${U.id}`;j&&!U.name.toLowerCase().includes(j)||B.push({id:G,name:U.name,source:"local",isUser:!1})}if(H)for(const U of H){if(X.has(U.filament_id))continue;const G=U.filament_id.startsWith("GF")?"GFS"+U.filament_id.slice(2):U.filament_id;X.has(G)||(!j||U.name.toLowerCase().includes(j))&&B.push({id:`builtin_${U.filament_id}`,name:U.name,source:"builtin",isUser:!1})}return B.sort((U,G)=>{const Y={cloud:0,local:1,builtin:2};return U.source!==G.source?Y[U.source]-Y[G.source]:U.isUser&&!G.isUser?-1:!U.isUser&&G.isUser?1:U.name.localeCompare(G.name)})},[F?.filament,z?.filament,H,x,s,a.savedPresetId,a.trayInfoIdx]),W=v.useMemo(()=>{if(!d)return null;let j=null;if(d.startsWith("local_")){const O=parseInt(d.replace("local_",""),10);j=z?.filament.find(U=>U.id===O)?.name||null}else if(d.startsWith("builtin_")){const O=d.replace("builtin_","");j=H?.find(U=>U.filament_id===O)?.name||null}else F?.filament&&(j=F.filament.find(ie=>ie.setting_id===d)?.name||null);if(!j)return null;let B=j.replace(/@.+$/,"").trim();B.startsWith("# ")&&(B=B.slice(2).trim());const X=jK(B);return{fullName:B,material:X.material,brand:X.brand}},[d,F?.filament,z?.filament,H]),ae=W?.fullName||"",pe=v.useMemo(()=>{if(!J||!W)return[];const{fullName:j,brand:B}=W,X=j.replace(/^(Bambu\s*(Lab)?|eSUN|Polymaker|Overture|Sunlu|Hatchbox)\s*/i,"").trim();return J.filter(O=>{const ie=(O.material||"").toUpperCase(),U=O.manufacturer.toUpperCase();if(!(ie===X.toUpperCase()||ie.includes(X.toUpperCase())||X.toUpperCase().includes(ie)))return!1;if(B){const Y=B.toUpperCase();if(!U.includes(Y)&&!Y.includes(U))return!1}return!0})},[J,W]),ye=v.useMemo(()=>{if(!Z?.profiles||!W)return[];const{fullName:j,material:B,brand:X}=W,O=j.toUpperCase(),ie=B.toUpperCase(),U=X.toUpperCase();if(!ie||ie.length<2)return[];const G=Z.profiles.filter(Q=>{const oe=Q.name.toUpperCase();if(U)return!(!oe.includes(U)||!oe.includes(ie));if(oe.includes(O)||oe.includes(ie))return!0;const ge={NYLON:["PA","PA-CF","PA6"],PA:["NYLON"]}[ie]||[];for(const ce of ge)if(oe.includes(ce))return!0;return!1}),Y=new Map;for(const Q of G){const oe=`${Q.name}|${Q.k_value}`,ee=Y.get(oe);ee?a.extruderId!==void 0&&Q.extruder_id===a.extruderId&&ee.extruder_id!==a.extruderId&&Y.set(oe,Q):Y.set(oe,Q)}return Array.from(Y.values())},[Z?.profiles,W,a.extruderId]);v.useEffect(()=>{if(t){if(a.savedPresetId)u(a.savedPresetId);else if(a.trayInfoIdx&&F?.filament){let j=F.filament.find(B=>B.setting_id===a.trayInfoIdx);j||(j=F.filament.find(B=>o3(B.setting_id)===a.trayInfoIdx)),j&&u(j.setting_id)}else if(a.trayInfoIdx&&H?.length){const j=a.trayInfoIdx,B=H.find(X=>X.filament_id===j);B&&u(`builtin_${B.filament_id}`)}if(a.trayColor){const j=a.trayColor.slice(0,6);j&&b(j)}}else u(""),p(null),b(""),g(""),_(""),C(!1),A.current=""},[t,a.savedPresetId,a.trayInfoIdx,a.trayColor,F?.filament,H]),v.useEffect(()=>{if(ye.length>0){if(a.caliIdx!=null&&a.caliIdx>0){const j=ye.find(B=>B.slot_id===a.caliIdx);if(j){p(j);return}}p(ye[0])}else p(null)},[d,ye,a.caliIdx]);const Te=v.useCallback(j=>{j.key==="Escape"&&e()},[e]);v.useEffect(()=>{if(t)return document.addEventListener("keydown",Te),()=>document.removeEventListener("keydown",Te)},[t,Te]);const $=S&&!M||I||L||re;if(v.useEffect(()=>{if(!$&&d&&d!==A.current){const j=requestAnimationFrame(()=>{const X=document.querySelector('[class*="fixed inset-0 z-50"]')?.querySelector(`[data-preset-id="${CSS.escape(d)}"]`);X&&(A.current=d,X.scrollIntoView({block:"nearest"}))});return()=>cancelAnimationFrame(j)}},[d,$]),!t)return null;const K=d&&!de.isPending,D=f||a.trayColor?.slice(0,6)||"FFFFFF";return r.jsxs("div",{className:`fixed inset-0 z-50 flex ${l?"":"items-center justify-center"}`,children:[!l&&r.jsx("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-sm",onClick:e}),r.jsxs("div",{className:l?"relative w-full h-full bg-bambu-dark-secondary flex flex-col":"relative w-full max-w-lg mx-4 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl",children:[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(cu,{className:"w-5 h-5 text-bambu-blue"}),r.jsx("h2",{className:"text-lg font-semibold text-white",children:c("configureAmsSlot.title")}),l&&r.jsxs("div",{className:"flex items-center gap-2 ml-4 text-sm text-bambu-gray",children:[r.jsx("span",{className:"text-white/30",children:"|"}),a.trayColor&&r.jsx("span",{className:"w-4 h-4 rounded-full border border-black/20",style:{backgroundColor:`#${a.trayColor.slice(0,6)}`}}),r.jsx("span",{className:"text-white/70",children:c("configureAmsSlot.slotLabel",{ams:AK(a.amsId,a.trayCount),slot:a.trayId+1})}),a.traySubBrands&&r.jsxs("span",{children:["(",a.traySubBrands,")"]})]})]}),r.jsx("button",{onClick:e,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 overflow-y-auto ${l?"flex-1 min-h-0":"space-y-4 max-h-[60vh]"}`,children:[N&&r.jsx("div",{className:"absolute inset-0 bg-bambu-dark-secondary/95 z-10 flex items-center justify-center rounded-xl",children:r.jsxs("div",{className:"text-center space-y-3",children:[r.jsx(td,{className:"w-16 h-16 text-bambu-green mx-auto"}),r.jsx("p",{className:"text-lg font-semibold text-white",children:c("configureAmsSlot.slotConfigured")}),r.jsx("p",{className:"text-sm text-bambu-gray",children:c("configureAmsSlot.settingsSentToPrinter")})]})}),!l&&r.jsxs("div",{className:"p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[r.jsx("p",{className:"text-xs text-bambu-gray mb-1",children:c("configureAmsSlot.configuringSlot")}),r.jsxs("div",{className:"flex items-center gap-2",children:[a.trayColor&&r.jsx("span",{className:"w-4 h-4 rounded-full border border-black/20",style:{backgroundColor:`#${a.trayColor.slice(0,6)}`}}),r.jsx("span",{className:"text-white font-medium",children:c("configureAmsSlot.slotLabel",{ams:AK(a.amsId,a.trayCount),slot:a.trayId+1})}),a.traySubBrands&&r.jsxs("span",{className:"text-bambu-gray",children:["(",a.traySubBrands,")"]})]})]}),$?r.jsx("div",{className:"flex justify-center py-8",children:r.jsx(mt,{className:"w-6 h-6 text-bambu-green animate-spin"})}):l?r.jsxs("div",{className:"flex gap-4 h-full",children:[r.jsxs("div",{className:"w-1/2 flex flex-col min-h-0",children:[r.jsxs("label",{className:"block text-sm text-bambu-gray mb-2",children:[c("configureAmsSlot.filamentProfile")," ",r.jsx("span",{className:"text-red-400",children:"*"})]}),r.jsx("input",{type:"text",placeholder:c("configureAmsSlot.searchPresets"),value:x,onChange:j=>_(j.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder:text-bambu-gray focus:border-bambu-green focus:outline-none mb-2 shrink-0"}),r.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto space-y-1",children:ue.length===0?r.jsx("p",{className:"text-center py-4 text-bambu-gray",children:F?.filament?.length===0&&!z?.filament?.length?c("configureAmsSlot.noPresetsAvailable"):c("configureAmsSlot.noMatchingPresets")}):ue.map(j=>r.jsx("button",{"data-preset-id":j.id,onClick:()=>u(j.id),className:`group w-full p-2 rounded-lg border text-left transition-colors ${d===j.id?"bg-bambu-green/20 border-bambu-green":"bg-bambu-dark border-bambu-dark-tertiary hover:border-bambu-gray"}`,children:r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsx("span",{className:"text-white text-sm truncate group-hover:whitespace-normal group-hover:break-all",title:j.name,children:j.name}),r.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[j.source==="local"&&r.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded bg-green-500/20 text-green-400",children:c("profiles.localProfiles.badge")}),j.source==="builtin"&&r.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded bg-amber-500/20 text-amber-400",children:c("configureAmsSlot.builtin")}),j.isUser&&r.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded bg-bambu-blue/20 text-bambu-blue",children:c("configureAmsSlot.custom")})]})]})},j.id))})]}),r.jsxs("div",{className:"w-1/2 flex flex-col gap-4 min-h-0 overflow-y-auto",children:[r.jsxs("div",{children:[r.jsxs("label",{className:"block text-sm text-bambu-gray mb-2",children:[c("configureAmsSlot.kProfileLabel"),ae&&r.jsx("span",{className:"ml-2 text-xs text-bambu-blue",children:c("configureAmsSlot.filteringFor",{material:ae})})]}),ye.length>0?r.jsxs("div",{className:"relative",children:[r.jsxs("select",{value:m?.name||"",onChange:j=>{const B=ye.find(X=>X.name===j.target.value);p(B||null)},className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none appearance-none pr-10",children:[r.jsx("option",{value:"",children:c("configureAmsSlot.noKProfile")}),ye.map(j=>r.jsxs("option",{value:j.name,children:[j.name," (K=",j.k_value,")"]},`${j.name}-${j.extruder_id}`))]}),r.jsx(Rn,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]}):d?r.jsx("p",{className:"text-sm text-bambu-gray italic py-2",children:c("configureAmsSlot.noMatchingKProfiles")}):r.jsx("span",{className:"inline-block text-xs px-2 py-1 rounded bg-amber-500/20 text-amber-400 border border-amber-500/30",children:c("configureAmsSlot.selectFilamentFirst")}),m&&r.jsx("p",{className:"text-xs text-bambu-green mt-1",children:c("configureAmsSlot.kFromCalibration",{value:m.k_value})})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-2",children:c("configureAmsSlot.customColorLabel")}),pe.length>0&&r.jsxs("div",{className:"mb-3",children:[r.jsx("p",{className:"text-xs text-bambu-gray mb-1.5",children:c("configureAmsSlot.presetColors",{name:W?.fullName})}),r.jsx("div",{className:"flex flex-wrap gap-1.5",children:pe.map(j=>r.jsxs("button",{onClick:()=>{const B=j.hex_color.replace("#","").toUpperCase();b(B),g(j.color_name)},className:`h-7 px-2 rounded-md border-2 transition-all flex items-center gap-1.5 ${f===j.hex_color.replace("#","").toUpperCase()?"border-bambu-green scale-105":"border-white/20 hover:border-white/40"}`,title:j.color_name,children:[r.jsx("span",{className:"w-4 h-4 rounded-full border border-black/20 flex-shrink-0",style:{backgroundColor:j.hex_color}}),r.jsx("span",{className:"text-xs text-white/80 whitespace-nowrap",children:j.color_name})]},j.id))})]}),r.jsxs("div",{className:"flex flex-wrap gap-1.5 mb-2",children:[MK.map(j=>r.jsx("button",{onClick:()=>{b(j.hex),g(j.name)},className:`w-7 h-7 rounded-md border-2 transition-all ${f===j.hex?"border-bambu-green scale-110":"border-white/20 hover:border-white/40"}`,style:{backgroundColor:`#${j.hex}`},title:j.name},j.hex)),r.jsx("button",{onClick:()=>T(!P),className:"w-7 h-7 rounded-md border-2 border-white/20 hover:border-white/40 flex items-center justify-center text-white/60 hover:text-white/80 transition-all text-xs",title:c(P?"configureAmsSlot.showLessColors":"configureAmsSlot.showMoreColors"),children:P?"−":"+"})]}),P&&r.jsx("div",{className:"flex flex-wrap gap-1.5 mb-2",children:EK.map(j=>r.jsx("button",{onClick:()=>{b(j.hex),g(j.name)},className:`w-7 h-7 rounded-md border-2 transition-all ${f===j.hex?"border-bambu-green scale-110":"border-white/20 hover:border-white/40"}`,style:{backgroundColor:`#${j.hex}`},title:j.name},j.hex))}),r.jsxs("div",{className:"flex gap-2 items-center",children:[r.jsx("div",{className:"w-10 h-10 rounded-lg border-2 border-white/20 flex-shrink-0",style:{backgroundColor:`#${D}`}}),r.jsx("input",{type:"text",placeholder:c("configureAmsSlot.colorPlaceholder"),value:w,onChange:j=>{const B=j.target.value;g(B);const X=DK(B);if(X)b(X);else{const O=B.replace(/[^0-9A-Fa-f]/g,"").toUpperCase();O.length===6?b(O):O.length===3&&b(O.split("").map(ie=>ie+ie).join(""))}},className:"flex-1 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder:text-bambu-gray focus:border-bambu-green focus:outline-none text-sm"}),f&&r.jsx("button",{onClick:()=>{b(""),g("")},className:"px-2 py-1 text-xs text-bambu-gray hover:text-white bg-bambu-dark-tertiary rounded",title:c("configureAmsSlot.clearCustomColor"),children:c("configureAmsSlot.clear")})]}),f&&r.jsx("p",{className:"text-xs text-bambu-gray mt-1.5",children:c("configureAmsSlot.hexLabel",{hex:f})})]})]})]}):r.jsxs(r.Fragment,{children:[r.jsxs("div",{children:[r.jsxs("label",{className:"block text-sm text-bambu-gray mb-2",children:[c("configureAmsSlot.filamentProfile")," ",r.jsx("span",{className:"text-red-400",children:"*"})]}),r.jsxs("div",{className:"relative",children:[r.jsx("input",{type:"text",placeholder:c("configureAmsSlot.searchPresets"),value:x,onChange:j=>_(j.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder:text-bambu-gray focus:border-bambu-green focus:outline-none mb-2"}),r.jsx("div",{className:"max-h-48 overflow-y-auto space-y-1",children:ue.length===0?r.jsx("p",{className:"text-center py-4 text-bambu-gray",children:F?.filament?.length===0&&!z?.filament?.length?c("configureAmsSlot.noPresetsAvailable"):c("configureAmsSlot.noMatchingPresets")}):ue.map(j=>r.jsx("button",{"data-preset-id":j.id,onClick:()=>u(j.id),className:`group w-full p-2 rounded-lg border text-left transition-colors ${d===j.id?"bg-bambu-green/20 border-bambu-green":"bg-bambu-dark border-bambu-dark-tertiary hover:border-bambu-gray"}`,children:r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsx("span",{className:"text-white text-sm truncate group-hover:whitespace-normal group-hover:break-all",title:j.name,children:j.name}),r.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[j.source==="local"&&r.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded bg-green-500/20 text-green-400",children:c("profiles.localProfiles.badge")}),j.source==="builtin"&&r.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded bg-amber-500/20 text-amber-400",children:c("configureAmsSlot.builtin")}),j.isUser&&r.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded bg-bambu-blue/20 text-bambu-blue",children:c("configureAmsSlot.custom")})]})]})},j.id))})]})]}),r.jsxs("div",{children:[r.jsxs("label",{className:"block text-sm text-bambu-gray mb-2",children:[c("configureAmsSlot.kProfileLabel"),ae&&r.jsx("span",{className:"ml-2 text-xs text-bambu-blue",children:c("configureAmsSlot.filteringFor",{material:ae})})]}),ye.length>0?r.jsxs("div",{className:"relative",children:[r.jsxs("select",{value:m?.name||"",onChange:j=>{const B=ye.find(X=>X.name===j.target.value);p(B||null)},className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none appearance-none pr-10",children:[r.jsx("option",{value:"",children:c("configureAmsSlot.noKProfile")}),ye.map(j=>r.jsxs("option",{value:j.name,children:[j.name," (K=",j.k_value,")"]},`${j.name}-${j.extruder_id}`))]}),r.jsx(Rn,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]}):d?r.jsx("p",{className:"text-sm text-bambu-gray italic py-2",children:c("configureAmsSlot.noMatchingKProfiles")}):r.jsx("span",{className:"inline-block text-xs px-2 py-1 rounded bg-amber-500/20 text-amber-400 border border-amber-500/30",children:c("configureAmsSlot.selectFilamentFirst")}),m&&r.jsx("p",{className:"text-xs text-bambu-green mt-1",children:c("configureAmsSlot.kFromCalibration",{value:m.k_value})})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-2",children:c("configureAmsSlot.customColorLabel")}),pe.length>0&&r.jsxs("div",{className:"mb-3",children:[r.jsx("p",{className:"text-xs text-bambu-gray mb-1.5",children:c("configureAmsSlot.presetColors",{name:W?.fullName})}),r.jsx("div",{className:"flex flex-wrap gap-1.5",children:pe.map(j=>r.jsxs("button",{onClick:()=>{const B=j.hex_color.replace("#","").toUpperCase();b(B),g(j.color_name)},className:`h-7 px-2 rounded-md border-2 transition-all flex items-center gap-1.5 ${f===j.hex_color.replace("#","").toUpperCase()?"border-bambu-green scale-105":"border-white/20 hover:border-white/40"}`,title:j.color_name,children:[r.jsx("span",{className:"w-4 h-4 rounded-full border border-black/20 flex-shrink-0",style:{backgroundColor:j.hex_color}}),r.jsx("span",{className:"text-xs text-white/80 whitespace-nowrap",children:j.color_name})]},j.id))})]}),r.jsxs("div",{className:"flex flex-wrap gap-1.5 mb-2",children:[MK.map(j=>r.jsx("button",{onClick:()=>{b(j.hex),g(j.name)},className:`w-7 h-7 rounded-md border-2 transition-all ${f===j.hex?"border-bambu-green scale-110":"border-white/20 hover:border-white/40"}`,style:{backgroundColor:`#${j.hex}`},title:j.name},j.hex)),r.jsx("button",{onClick:()=>T(!P),className:"w-7 h-7 rounded-md border-2 border-white/20 hover:border-white/40 flex items-center justify-center text-white/60 hover:text-white/80 transition-all text-xs",title:c(P?"configureAmsSlot.showLessColors":"configureAmsSlot.showMoreColors"),children:P?"−":"+"})]}),P&&r.jsx("div",{className:"flex flex-wrap gap-1.5 mb-2",children:EK.map(j=>r.jsx("button",{onClick:()=>{b(j.hex),g(j.name)},className:`w-7 h-7 rounded-md border-2 transition-all ${f===j.hex?"border-bambu-green scale-110":"border-white/20 hover:border-white/40"}`,style:{backgroundColor:`#${j.hex}`},title:j.name},j.hex))}),r.jsxs("div",{className:"flex gap-2 items-center",children:[r.jsx("div",{className:"w-10 h-10 rounded-lg border-2 border-white/20 flex-shrink-0",style:{backgroundColor:`#${D}`}}),r.jsx("input",{type:"text",placeholder:c("configureAmsSlot.colorPlaceholder"),value:w,onChange:j=>{const B=j.target.value;g(B);const X=DK(B);if(X)b(X);else{const O=B.replace(/[^0-9A-Fa-f]/g,"").toUpperCase();O.length===6?b(O):O.length===3&&b(O.split("").map(ie=>ie+ie).join(""))}},className:"flex-1 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder:text-bambu-gray focus:border-bambu-green focus:outline-none text-sm"}),f&&r.jsx("button",{onClick:()=>{b(""),g("")},className:"px-2 py-1 text-xs text-bambu-gray hover:text-white bg-bambu-dark-tertiary rounded",title:c("configureAmsSlot.clearCustomColor"),children:c("configureAmsSlot.clear")})]}),f&&r.jsx("p",{className:"text-xs text-bambu-gray mt-1.5",children:c("configureAmsSlot.hexLabel",{hex:f})})]})]})]}),r.jsxs("div",{className:"flex justify-between p-4 border-t border-bambu-dark-tertiary shrink-0",children:[r.jsx(Me,{variant:"secondary",onClick:()=>me.mutate(),disabled:me.isPending||de.isPending,className:"text-red-400 hover:text-red-300 hover:bg-red-500/10",children:me.isPending?r.jsxs(r.Fragment,{children:[r.jsx(mt,{className:"w-4 h-4 animate-spin"}),c("configureAmsSlot.resetting")]}):r.jsxs(r.Fragment,{children:[r.jsx(hs,{className:"w-4 h-4"}),c("configureAmsSlot.resetSlot")]})}),r.jsxs("div",{className:"flex gap-2",children:[r.jsx(Me,{variant:"secondary",onClick:e,children:c("configureAmsSlot.cancel")}),r.jsx(Me,{onClick:()=>de.mutate(),disabled:!K,children:de.isPending?r.jsxs(r.Fragment,{children:[r.jsx(mt,{className:"w-4 h-4 animate-spin"}),c("configureAmsSlot.configuring")]}):r.jsxs(r.Fragment,{children:[r.jsx(cu,{className:"w-4 h-4"}),c("configureAmsSlot.configureSlot")]})})]})]}),(de.isError||me.isError)&&r.jsx("div",{className:"mx-4 mb-4 p-2 bg-red-500/20 border border-red-500/50 rounded text-sm text-red-400",children:de.error?.message||me.error?.message})]})]})}function FK({className:t="w-4 h-4"}){return r.jsx("svg",{viewBox:"0 0 1945 1370",fill:"none",className:t,"aria-hidden":"true",children:r.jsxs("g",{transform:"translate(-754.293 -471.685)",children:[r.jsxs("g",{transform:"translate(0.18191 255.976)",children:[r.jsx("g",{transform:"matrix(1.05469 0 0 0.241063 -153.484 1120.2)",children:r.jsx("rect",{x:"922.048",y:"1195.15",width:"1721.5",height:"470.135",stroke:"currentColor",strokeOpacity:"0.99",strokeWidth:"168.84",strokeLinecap:"round",strokeLinejoin:"round"})}),r.jsx("g",{transform:"matrix(0.983656 0 0 1.0767 -62.2035 141.539)",children:r.jsx("path",{d:"M2741.42,1175.93L895.832,1175.93L1125.16,621.902L2512.09,621.902L2741.42,1175.93Z",fill:"currentColor",fillOpacity:"0.05",stroke:"currentColor",strokeOpacity:"0.99",strokeWidth:"125.26",strokeLinecap:"round",strokeLinejoin:"round"})})]}),r.jsx("g",{transform:"translate(21.1916 0.684817)",children:r.jsx("path",{d:"M1981.31,567.518C1954.86,567.518 1933.39,546.047 1933.39,519.601C1933.39,493.156 1954.86,471.685 1981.31,471.685L2146.61,471.685C2173.07,471.685 2194.53,493.138 2194.53,519.601L2194.53,688.741C2194.53,715.187 2173.05,736.658 2146.61,736.658C2120.16,736.658 2098.69,715.187 2098.69,688.741L2098.69,567.518L1981.31,567.518ZM2098.69,1252.54C2098.69,1226.1 2120.16,1204.62 2146.61,1204.62C2173.05,1204.62 2194.53,1226.1 2194.53,1252.54L2194.53,1421.68C2194.53,1448.14 2173.07,1469.6 2146.61,1469.6L1981.31,1469.6C1954.86,1469.6 1933.39,1448.13 1933.39,1421.68C1933.39,1395.24 1954.86,1373.76 1981.31,1373.76L2098.69,1373.76L2098.69,1252.54ZM1430.29,1373.76C1456.74,1373.76 1478.21,1395.24 1478.21,1421.68C1478.21,1448.13 1456.74,1469.6 1430.29,1469.6L1264.99,1469.6C1238.53,1469.6 1217.07,1448.14 1217.07,1421.68L1217.07,1252.54C1217.07,1226.1 1238.55,1204.62 1264.99,1204.62C1291.44,1204.62 1312.91,1226.1 1312.91,1252.54L1312.91,1373.76L1430.29,1373.76ZM1312.91,688.741C1312.91,715.187 1291.44,736.658 1264.99,736.658C1238.55,736.658 1217.07,715.187 1217.07,688.741L1217.07,519.601C1217.07,493.138 1238.53,471.685 1264.99,471.685L1430.29,471.685C1456.74,471.685 1478.21,493.156 1478.21,519.601C1478.21,546.047 1456.74,567.518 1430.29,567.518L1312.91,567.518L1312.91,688.741Z",fill:"currentColor",fillOpacity:"0.99"})})]})})}function Oie({folderId:t,onClose:e,onUploadComplete:n,onFileUploaded:a,autoUpload:i,validateFile:s,accept:o}){const{t:l}=kt(),[c,d]=v.useState([]),[u,m]=v.useState(!1),[p,f]=v.useState(!1),[b,w]=v.useState(!0),[g,x]=v.useState(!1),[_,N]=v.useState(!0),[C,P]=v.useState(null),T=v.useRef(null),A=ue=>{ue.preventDefault(),m(!0)},F=ue=>{ue.preventDefault(),m(!1)},S=ue=>{ue.preventDefault(),m(!1),H(Array.from(ue.dataTransfer.files))},M=ue=>{ue.target.files&&H(Array.from(ue.target.files))},z=(ue,W)=>{d(ae=>ae.map(pe=>pe.file===ue?{...pe,...W}:pe))},I=async ue=>{f(!0);for(const W of ue)if(W.status==="pending"){z(W.file,{status:"uploading"});try{if(W.isZip){const ae=await se.extractZipFile(W.file,t,b,g,_);z(W.file,{status:ae.errors.length>0&&ae.extracted===0?"error":"success",extractedCount:ae.extracted,error:ae.errors.length>0?l("fileManager.zipFilesFailed","{{count}} files failed",{count:ae.errors.length}):void 0})}else{const ae=await se.uploadLibraryFile(W.file,t,_);z(W.file,{status:"success"});const pe=a?.(ae);if(pe){P(pe),d([]),f(!1);return}}}catch(ae){z(W.file,{status:"error",error:ae instanceof Error?ae.message:l("fileManager.uploadFailed","Upload failed")})}}f(!1),n(),e()},H=ue=>{if(P(null),s)for(const ae of ue){const pe=s(ae);if(pe){P(pe);return}}const W=ue.map(ae=>({file:ae,status:"pending",isZip:ae.name.toLowerCase().endsWith(".zip"),is3mf:ae.name.toLowerCase().endsWith(".3mf")}));d(ae=>[...ae,...W]),i&&ue.length>0&&I(W)},L=ue=>{d(W=>W.filter((ae,pe)=>pe!==ue))},Z=c.some(ue=>ue.isZip&&ue.status==="pending"),re=c.some(ue=>ue.file.name.toLowerCase().endsWith(".stl")&&ue.status==="pending"),J=c.some(ue=>ue.is3mf&&ue.status==="pending"),de=c.filter(ue=>ue.status==="pending").length,me=c.length>0&&de===0&&!p;return r.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:r.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-lg border border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"p-4 border-b border-bambu-dark-tertiary flex items-center justify-between",children:[r.jsx("h2",{className:"text-lg font-semibold text-white",children:l("fileManager.uploadFiles")}),r.jsx("button",{onClick:e,className:"p-1 hover:bg-bambu-dark rounded",children:r.jsx(Ht,{className:"w-5 h-5 text-bambu-gray"})})]}),r.jsxs("div",{className:"p-4 space-y-4",children:[r.jsxs("div",{onDragOver:A,onDragLeave:F,onDrop:S,onClick:()=>T.current?.click(),className:`border-2 border-dashed rounded-lg p-8 text-center cursor-pointer transition-colors ${u?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary hover:border-bambu-green/50"}`,children:[r.jsx(ka,{className:`w-10 h-10 mx-auto mb-3 ${u?"text-bambu-green":"text-bambu-gray"}`}),r.jsx("p",{className:"text-white font-medium",children:l(u?"fileManager.dropFilesHere":"fileManager.dragDropFiles")}),r.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:l("fileManager.orClickToBrowse")}),r.jsx("p",{className:"text-xs text-bambu-gray/70 mt-2",children:l("fileManager.allFileTypesSupported")})]}),r.jsx("input",{ref:T,type:"file",multiple:!0,accept:o,className:"hidden",onChange:M}),Z&&r.jsx("div",{className:"p-3 bg-blue-500/10 border border-blue-500/30 rounded-lg",children:r.jsxs("div",{className:"flex items-start gap-3",children:[r.jsx(yo,{className:"w-5 h-5 text-blue-400 mt-0.5 flex-shrink-0"}),r.jsxs("div",{className:"flex-1",children:[r.jsx("p",{className:"text-sm text-blue-300 font-medium",children:l("fileManager.zipFilesDetected")}),r.jsx("p",{className:"text-xs text-blue-300/70 mt-1",children:l("fileManager.zipExtractOptions")}),r.jsxs("label",{className:"flex items-center gap-2 mt-2 cursor-pointer",children:[r.jsx("input",{type:"checkbox",checked:b,onChange:ue=>w(ue.target.checked),className:"w-4 h-4 rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),r.jsx("span",{className:"text-sm text-white",children:l("fileManager.preserveZipStructure")})]}),r.jsxs("label",{className:"flex items-center gap-2 mt-2 cursor-pointer",children:[r.jsx("input",{type:"checkbox",checked:g,onChange:ue=>x(ue.target.checked),className:"w-4 h-4 rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),r.jsx("span",{className:"text-sm text-white",children:l("fileManager.createFolderFromZip")})]})]})]})}),J&&r.jsx("div",{className:"p-3 bg-purple-500/10 border border-purple-500/30 rounded-lg",children:r.jsxs("div",{className:"flex items-start gap-3",children:[r.jsx(mr,{className:"w-5 h-5 text-purple-400 mt-0.5 flex-shrink-0"}),r.jsxs("div",{className:"flex-1",children:[r.jsx("p",{className:"text-sm text-purple-300 font-medium",children:l("fileManager.threemfDetected")}),r.jsx("p",{className:"text-xs text-purple-300/70 mt-1",children:l("fileManager.threemfExtractionInfo")})]})]})}),(re||Z)&&r.jsx("div",{className:"p-3 bg-bambu-green/10 border border-bambu-green/30 rounded-lg",children:r.jsxs("div",{className:"flex items-start gap-3",children:[r.jsx(lu,{className:"w-5 h-5 text-bambu-green mt-0.5 flex-shrink-0"}),r.jsxs("div",{className:"flex-1",children:[r.jsx("p",{className:"text-sm text-bambu-green font-medium",children:l("fileManager.stlThumbnailGeneration")}),r.jsx("p",{className:"text-xs text-bambu-green/70 mt-1",children:l(Z&&!re?"fileManager.zipMayContainStl":"fileManager.thumbnailsCanBeGenerated")}),r.jsxs("label",{className:"flex items-center gap-2 mt-2 cursor-pointer",children:[r.jsx("input",{type:"checkbox",checked:_,onChange:ue=>N(ue.target.checked),className:"w-4 h-4 rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),r.jsx("span",{className:"text-sm text-white",children:l("fileManager.generateThumbnailsForStl")})]})]})]})}),c.length>0&&r.jsx("div",{className:"max-h-48 overflow-y-auto space-y-2",children:c.map((ue,W)=>r.jsxs("div",{className:"flex items-center gap-3 p-2 bg-bambu-dark rounded-lg",children:[ue.isZip?r.jsx(yo,{className:"w-4 h-4 text-blue-400 flex-shrink-0"}):r.jsx(vT,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"}),r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsx("p",{className:"text-sm text-white truncate",children:ue.file.name}),r.jsxs("p",{className:"text-xs text-bambu-gray",children:[(ue.file.size/1024/1024).toFixed(2)," MB",ue.isZip&&ue.status==="pending"&&r.jsxs("span",{className:"text-blue-400 ml-2",children:["• ",l("fileManager.willBeExtracted")]}),ue.extractedCount!==void 0&&r.jsxs("span",{className:"text-green-400 ml-2",children:["• ",l("fileManager.filesExtracted",{count:ue.extractedCount})]})]})]}),ue.status==="pending"&&r.jsx("button",{onClick:()=>L(W),className:"p-1 hover:bg-bambu-dark-tertiary rounded",children:r.jsx(Ht,{className:"w-4 h-4 text-bambu-gray"})}),ue.status==="uploading"&&r.jsx(mt,{className:"w-4 h-4 text-bambu-green animate-spin"}),ue.status==="success"&&r.jsx(wr,{className:"w-4 h-4 text-green-500"}),ue.status==="error"&&r.jsx("span",{title:ue.error,children:r.jsx(ja,{className:"w-4 h-4 text-red-500"})})]},W))}),C&&r.jsx("div",{className:"p-3 bg-red-500/10 border border-red-500/30 rounded-lg",children:r.jsxs("div",{className:"flex items-start gap-3",children:[r.jsx(ja,{className:"w-5 h-5 text-red-400 mt-0.5 flex-shrink-0"}),r.jsx("p",{className:"text-sm text-red-300",children:C})]})})]}),r.jsxs("div",{className:"p-4 border-t border-bambu-dark-tertiary flex justify-end gap-2",children:[r.jsx(Me,{variant:"secondary",onClick:e,children:l("common.cancel")}),!me&&r.jsx(Me,{onClick:()=>I(c),disabled:de===0||p,children:p?r.jsxs(r.Fragment,{children:[r.jsx(mt,{className:"w-4 h-4 mr-2 animate-spin"}),l("fileManager.uploading")]}):r.jsxs(r.Fragment,{children:[r.jsx(ka,{className:"w-4 h-4 mr-2"}),l("common.upload")," ",de>0?`(${de})`:""]})})]})]})})}function RK(t){return t?`#${t.replace("#","").substring(0,6)}`:"#808080"}function Ia(t){return t?t.replace("#","").toLowerCase().substring(0,6):""}const c7e=[["PA-CF","PA12-CF","PAHT-CF"]],zie={};for(const t of c7e){const e=t[0];for(const n of t)zie[n.toUpperCase()]=e.toUpperCase()}function gP(t){if(!t)return"";const e=t.toUpperCase();return zie[e]??e}function l3(t,e){return gP(t)===gP(e)}function sd(t,e,n=40){const a=Ia(t),i=Ia(e);if(!a||!i||a.length<6||i.length<6)return!1;const s=parseInt(a.substring(0,2),16),o=parseInt(a.substring(2,4),16),l=parseInt(a.substring(4,6),16),c=parseInt(i.substring(0,2),16),d=parseInt(i.substring(2,4),16),u=parseInt(i.substring(4,6),16);return Math.abs(s-c)<=n&&Math.abs(o-d)<=n&&Math.abs(l-u)<=n}function o_(t,e,n,a){if(a)return"Ext";const i=String.fromCharCode(65+(t>=128?t-128:t));return n?`HT-${i}`:`${i}${e+1}`}function Qg(t,e,n){return n?254+e:t>=128?t:t*4+e}function ly(t){return t>50?"#00ae42":t>=15?"#f59e0b":"#ef4444"}function AN(t){return!t?.remaining_weight||!t?.filament_weight||t.filament_weight<=0?null:Math.min(100,Math.round(t.remaining_weight/t.filament_weight*100))}function LK(t,e){return(Number.isFinite(t)?Math.max(0,Math.trunc(t)):0).toString(16).toUpperCase().padStart(e,"0").slice(-e)}function d7e(t){const e=(t||"").trim().toUpperCase();let n=2166136261;for(let a=0;a>>0).toString(16).toUpperCase().padStart(8,"0")}function fm(t,e,n){return`${d7e(t)}${LK(e,4)}${LK(n,4)}`}function IK(t){if(!t)return!1;const e=Date.now()+4320*60*60*1e3;return(Xn(t)?.getTime()??0)>e}function u7e(t,e,n,a){let i=Uie(e,t.nozzle_id);a&&(i=[...i].sort((c,d)=>{const u=(c.remain??-1)>=0?c.remain??-1:101,m=(d.remain??-1)>=0?d.remain??-1:101;return u-m}));const s=i.find(c=>!n.has(c.globalTrayId)&&l3(c.type,t.type)&&Ia(c.color)===Ia(t.color)),o=s?void 0:i.find(c=>!n.has(c.globalTrayId)&&l3(c.type,t.type)&&sd(c.color,t.color)),l=s||o?void 0:i.find(c=>!n.has(c.globalTrayId)&&l3(c.type,t.type));return s??o??l}function Uie(t,e){return t.filter(n=>e==null||n.extruderId===e)}function Ys(t){return t?!!(t.tray_uuid&&t.tray_uuid!=="00000000000000000000000000000000"||t.tag_uid&&t.tag_uid!=="0000000000000000"):!1}function l_(t){const e=[],n=t?.ams_extruder_map,a=n&&Object.keys(n).length>0;t?.ams?.forEach(i=>{const s=i.tray.length===1;i.tray.forEach(o=>{if(o.tray_type){const l=RK(o.tray_color);e.push({type:o.tray_type,color:l,colorName:bc(l),amsId:i.id,trayId:o.id,isHt:s,isExternal:!1,label:o_(i.id,o.id,s,!1),globalTrayId:Qg(i.id,o.id,!1),trayInfoIdx:o.tray_info_idx||"",traySubBrands:o.tray_sub_brands||"",extruderId:n?.[String(i.id)],remain:o.remain??-1})}})});for(const i of t?.vt_tray??[])if(i.tray_type){const s=RK(i.tray_color),o=i.id??254,l=(t?.vt_tray?.length??0)>1;e.push({type:i.tray_type,color:s,colorName:bc(s),amsId:-1,trayId:o-254,isHt:!1,isExternal:!0,label:l?o===254?"Ext-L":"Ext-R":"External",globalTrayId:o,trayInfoIdx:i.tray_info_idx||"",traySubBrands:i.tray_sub_brands||"",extruderId:a?255-o:void 0,remain:i.remain??-1})}return e}function OK(t,e,n){if(!t?.filaments||t.filaments.length===0)return;const a=l_(e);if(a.length===0)return;const i=e?.fila_switch?.installed===!0,s=new Set,o=t.filaments.map(d=>{const u=d.tray_info_idx||"";let m=a.filter(x=>!s.has(x.globalTrayId));d.nozzle_id!=null&&!i&&(m=m.filter(x=>x.extruderId===d.nozzle_id)),n&&(m=[...m].sort((x,_)=>{const N=x.remain>=0?x.remain:101,C=_.remain>=0?_.remain:101;return N-C}));let p,f,b,w;if(u){const x=m.filter(_=>_.trayInfoIdx===u);x.length===1?p=x[0]:x.length>1&&(n&&x.sort((_,N)=>{const C=_.remain>=0?_.remain:101,P=N.remain>=0?N.remain:101;return C-P}),f=x.find(_=>_.type?.toUpperCase()===d.type?.toUpperCase()&&Ia(_.color)===Ia(d.color)),f||(b=x.find(_=>_.type?.toUpperCase()===d.type?.toUpperCase()&&sd(_.color,d.color))),!f&&!b&&(w=x.find(_=>_.type?.toUpperCase()===d.type?.toUpperCase())))}!p&&!f&&!b&&!w&&(f=m.find(x=>x.type?.toUpperCase()===d.type?.toUpperCase()&&Ia(x.color)===Ia(d.color)),f||(b=m.find(x=>x.type?.toUpperCase()===d.type?.toUpperCase()&&sd(x.color,d.color))),!f&&!b&&(w=m.find(x=>x.type?.toUpperCase()===d.type?.toUpperCase())));const g=p||f||b||w||void 0;return g&&s.add(g.globalTrayId),{slot_id:d.slot_id,globalTrayId:g?.globalTrayId??-1}}),l=Math.max(...o.map(d=>d.slot_id||0));if(l<=0)return;const c=new Array(l).fill(-1);return o.forEach(d=>{d.slot_id&&d.slot_id>0&&(c[d.slot_id-1]=d.globalTrayId)}),c}function m7e(t){return v.useMemo(()=>l_(t),[t])}function Bie(t,e,n,a){const i=m7e(e),s=e?.fila_switch?.installed===!0,o=v.useMemo(()=>{if(!t?.filaments||t.filaments.length===0)return[];const u=new Set(Object.values(n));return t.filaments.map(m=>{const p=m.slot_id||0;if(p>0&&n[p]!==void 0){const F=n[p],S=i.find(M=>M.globalTrayId===F);if(S){const M=S.type?.toUpperCase()===m.type?.toUpperCase(),z=Ia(S.color)===Ia(m.color)||sd(S.color,m.color);let I;return M&&z?I="match":M?I="type_only":I="mismatch",{...m,loaded:S,hasFilament:!0,typeMatch:M,colorMatch:z,status:I,isManual:!0}}}const f=m.tray_info_idx||"";let b=i.filter(F=>!u.has(F.globalTrayId));m.nozzle_id!=null&&!s&&(b=b.filter(F=>F.extruderId===m.nozzle_id)),a&&(b=[...b].sort((F,S)=>{const M=F.remain>=0?F.remain:101,z=S.remain>=0?S.remain:101;return M-z}));let w,g,x,_;if(f){const F=b.filter(S=>S.trayInfoIdx===f);F.length===1?w=F[0]:F.length>1&&(a&&F.sort((S,M)=>{const z=S.remain>=0?S.remain:101,I=M.remain>=0?M.remain:101;return z-I}),g=F.find(S=>S.type?.toUpperCase()===m.type?.toUpperCase()&&Ia(S.color)===Ia(m.color)),g||(x=F.find(S=>S.type?.toUpperCase()===m.type?.toUpperCase()&&sd(S.color,m.color))),!g&&!x&&(_=F.find(S=>S.type?.toUpperCase()===m.type?.toUpperCase())))}!w&&!g&&!x&&!_&&(g=b.find(F=>F.type?.toUpperCase()===m.type?.toUpperCase()&&Ia(F.color)===Ia(m.color)),g||(x=b.find(F=>F.type?.toUpperCase()===m.type?.toUpperCase()&&sd(F.color,m.color))),!g&&!x&&(_=b.find(F=>F.type?.toUpperCase()===m.type?.toUpperCase())));const N=w||g||x||_||void 0;N&&u.add(N.globalTrayId);const C=!!N,P=C,T=!!w||!!g||!!x;let A;return w||g||x?A="match":_?A="type_only":A="mismatch",{...m,loaded:N,hasFilament:C,typeMatch:P,colorMatch:T,status:A,isManual:!1}})},[t,i,n,a,s]),l=v.useMemo(()=>{if(o.length===0)return;const u=Math.max(...o.map(p=>p.slot_id||0));if(u<=0)return;const m=new Array(u).fill(-1);return o.forEach(p=>{p.slot_id&&p.slot_id>0&&(m[p.slot_id-1]=p.loaded?.globalTrayId??-1)}),m},[o]),c=o.some(u=>u.status==="mismatch"),d=o.some(u=>u.status==="type_only");return{loadedFilaments:i,filamentComparison:o,amsMapping:l,hasTypeMismatch:c,hasColorMismatch:d}}function p7e(t,e,n,a){if(!t||t.length===0)return{exactMatches:0,typeOnlyMatches:0,missingTypes:0,totalSlots:0,status:"full"};let i=0,s=0,o=0;const l=new Set(Object.values(n));for(const u of t){const m=u.slot_id||0;if(m>0&&n[m]!==void 0){const x=n[m],_=e.find(N=>N.globalTrayId===x);if(_){const N=_.type?.toUpperCase()===u.type?.toUpperCase(),C=Ia(_.color)===Ia(u.color)||sd(_.color,u.color);N&&C?i++:N?s++:o++;continue}}let p=e.filter(x=>!l.has(x.globalTrayId));if(u.nozzle_id!=null){const x=p.filter(_=>_.extruderId===u.nozzle_id);x.length>0&&(p=x)}a&&(p=[...p].sort((x,_)=>{const N=x.remain>=0?x.remain:101,C=_.remain>=0?_.remain:101;return N-C}));const f=p.find(x=>x.type?.toUpperCase()===u.type?.toUpperCase()&&Ia(x.color)===Ia(u.color)),b=f?void 0:p.find(x=>x.type?.toUpperCase()===u.type?.toUpperCase()&&sd(x.color,u.color)),w=f||b?void 0:p.find(x=>x.type?.toUpperCase()===u.type?.toUpperCase()),g=f??b??w;g&&l.add(g.globalTrayId),f||b?i++:w?s++:o++}const c=t.length;let d="full";return o>0?d="missing":s>0&&(d="partial"),{exactMatches:i,typeOnlyMatches:s,missingTypes:o,totalSlots:c,status:d}}function h7e(t,e,n,a){if(!t?.filaments||t.filaments.length===0)return;const i=l_(e);if(i.length===0)return;const s=new Set(Object.values(n)),o=[];for(const d of t.filaments){const u=d.slot_id||0;if(u>0&&n[u]!==void 0){o.push({slot_id:u,globalTrayId:n[u]});continue}let m=i.filter(g=>!s.has(g.globalTrayId));if(d.nozzle_id!=null){const g=m.filter(x=>x.extruderId===d.nozzle_id);g.length>0&&(m=g)}a&&(m=[...m].sort((g,x)=>{const _=g.remain>=0?g.remain:101,N=x.remain>=0?x.remain:101;return _-N}));const p=m.find(g=>g.type?.toUpperCase()===d.type?.toUpperCase()&&Ia(g.color)===Ia(d.color)),f=p?void 0:m.find(g=>g.type?.toUpperCase()===d.type?.toUpperCase()&&sd(g.color,d.color)),b=p||f?void 0:m.find(g=>g.type?.toUpperCase()===d.type?.toUpperCase()),w=p??f??b;w&&s.add(w.globalTrayId),o.push({slot_id:u,globalTrayId:w?.globalTrayId??-1})}const l=Math.max(...o.map(d=>d.slot_id||0));if(l<=0)return;const c=new Array(l).fill(-1);return o.forEach(d=>{d.slot_id&&d.slot_id>0&&(c[d.slot_id-1]=d.globalTrayId)}),c}const zK={useDefault:!0,manualMappings:{},autoConfigured:!1};function f7e(t,e,n,a,i,s,o){const l=tf({queries:t.map(w=>({queryKey:["printer-status",w],queryFn:()=>se.getPrinterStatus(w),enabled:t.length>0,staleTime:5e3}))}),c=v.useMemo(()=>t.map((w,g)=>{const x=l[g],_=x?.data,C=e?.find(z=>z.id===w)?.name||`Printer ${w}`,P=l_(_),T=i[w]||zK,A=OK(n,_,o),F=T.useDefault?a:T.manualMappings,S=h7e(n,_,F,o),M=p7e(n?.filaments,P,F,o);return{printerId:w,printerName:C,status:_,isLoading:x?.isLoading??!1,loadedFilaments:P,autoMapping:A,finalMapping:S,matchStatus:M.status,exactMatches:M.exactMatches,typeOnlyMatches:M.typeOnlyMatches,missingTypes:M.missingTypes,totalSlots:M.totalSlots,config:T}}),[t,l,e,n,i,a,o]),d=l.some(w=>w.isLoading),u=(w,g)=>{s(x=>({...x,[w]:{...x[w]||zK,...g}}))},m=w=>{const g=c.find(N=>N.printerId===w);if(!g||!g.status||!n?.filaments)return;const x=OK(n,g.status,o);if(!x)return;const _={};x.forEach((N,C)=>{N!==-1&&(_[C+1]=N)}),u(w,{useDefault:!1,manualMappings:_,autoConfigured:!0})},p=()=>{for(const w of t)m(w)},f=w=>c.find(x=>x.printerId===w)?.finalMapping,b=c.every(w=>w.matchStatus!=="missing");return{printerResults:c,isLoading:d,perPrinterConfigs:i,updatePrinterConfig:u,autoConfigureAll:p,autoConfigurePrinter:m,getFinalMapping:f,allPrintersReady:b}}const Hie={USD:"$",EUR:"€",GBP:"£",CHF:"Fr.",JPY:"¥",CNY:"¥",CAD:"$",AUD:"$",INR:"₹",HKD:"HK$",KRW:"₩",SEK:"kr",NOK:"kr",DKK:"kr",PLN:"zł",BRL:"R$",TWD:"NT$",SGD:"S$",NZD:"NZ$",MXN:"MX$",MYR:"RM",CZK:"Kč",THB:"฿",ZAR:"R",TRY:"₺",RUB:"₽",HUF:"Ft",ILS:"₪",UAH:"₴"};function Bo(t){return Hie[t.toUpperCase()]||t}const g7e=Object.entries(Hie).map(([t,e])=>({code:t,label:`${t} (${e})`}));function b7e({printerId:t,filamentReqs:e,manualMappings:n,onManualMappingChange:a,currencySymbol:i,defaultCostPerKg:s,defaultExpanded:o=!1}){const{t:l}=kt(),c=tn(),[d,u]=v.useState(!1),[m,p]=v.useState(o),{data:f}=Ke({queryKey:["printer-status",t],queryFn:()=>se.getPrinterStatus(t),enabled:!!t}),{data:b}=Ke({queryKey:["spool-assignments",t],queryFn:()=>se.getAssignments(t),enabled:!!t}),{loadedFilaments:w,filamentComparison:g,hasTypeMismatch:x,hasColorMismatch:_}=Bie(e,f,n),N=v.useMemo(()=>{const L=new Map;for(const Z of b||[]){const re=Z.ams_id===255,J=Qg(Z.ams_id,Z.tray_id,re);L.set(J,Z.spool?.cost_per_kg??null)}return L},[b]),C=v.useMemo(()=>{const L=new Map;for(const Z of b||[]){const re=Z.ams_id===255,J=Qg(Z.ams_id,Z.tray_id,re),de=Z.spool;if(!de){L.set(J,null);continue}L.set(J,Math.max(0,Math.round((de.label_weight??0)-(de.weight_used??0))))}return L},[b]),P=v.useMemo(()=>{let L=0;for(const Z of g){const re=Z.loaded?.globalTrayId;if(re==null)continue;const de=N.get(re)??null??s;de>0&&(L+=Z.used_grams/1e3*de)}return L},[g,N,s]),T=v.useMemo(()=>Array.from(N.values()).some(L=>L!=null&&L>0),[N]),A=e?.filaments&&e.filaments.length>0,F=e?.filaments?.some(L=>L.nozzle_id!=null)??!1,S=f?.fila_switch?.installed===!0,M=L=>{const Z=f?.fila_switch;if(!Z?.installed)return null;const re=Z.in_slots.indexOf(L);return re<0?null:Z.out_extruders[re]??null};if(!A||!f)return null;const z=x?"#f97316":_?"#facc15":"#00ae42",I=(L,Z)=>{if(L>0)if(Z===""){const re={...n};delete re[L],a(re)}else a({...n,[L]:parseInt(Z,10)})},H=async()=>{u(!0);try{await se.refreshPrinterStatus(t),await new Promise(L=>setTimeout(L,500)),await c.refetchQueries({queryKey:["printer-status",t]})}finally{u(!1)}};return r.jsxs("div",{className:"mb-4",children:[r.jsxs("button",{type:"button",onClick:()=>p(!m),className:"flex items-center gap-2 text-sm text-bambu-gray hover:text-white transition-colors w-full",children:[r.jsx(Cw,{className:"w-4 h-4",fill:z,stroke:"none"}),r.jsx("span",{children:l("printModal.filamentMapping")}),x?r.jsx("span",{className:"text-xs text-orange-400",children:"(Type not found)"}):_?r.jsx("span",{className:"text-xs text-yellow-400",children:"(Color mismatch)"}):r.jsx("span",{className:"text-xs text-bambu-green",children:"(Ready)"}),m?r.jsx(Qo,{className:"w-4 h-4 ml-auto"}):r.jsx(Rn,{className:"w-4 h-4 ml-auto"})]}),m&&r.jsxs("div",{className:"mt-2 bg-bambu-dark rounded-lg p-3 space-y-2",children:[r.jsxs("div",{className:"flex items-center justify-between mb-2",children:[r.jsx("span",{className:"text-xs text-bambu-gray",children:"Click to change slot assignment"}),r.jsxs("button",{type:"button",onClick:H,className:"flex items-center gap-1 px-2 py-0.5 text-xs rounded border border-bambu-gray/30 hover:border-bambu-gray hover:bg-bambu-dark-tertiary transition-colors text-bambu-gray hover:text-white",disabled:d,children:[r.jsx(sr,{className:`w-3 h-3 ${d?"animate-spin":""}`}),r.jsx("span",{children:"Re-read"})]})]}),g.map((L,Z)=>r.jsxs("div",{className:"grid items-center gap-2 text-xs",style:{gridTemplateColumns:"16px minmax(70px, 1fr) auto 2fr 16px"},children:[r.jsx("span",{title:`Required: ${L.type} - ${bc(L.color)}`,children:r.jsx(Cw,{className:"w-3 h-3",fill:L.color,stroke:L.color})}),r.jsxs("span",{className:"text-white truncate flex items-center gap-1",children:[F&&L.nozzle_id!=null&&r.jsx("span",{className:"inline-flex items-center justify-center w-3.5 h-3.5 rounded text-[9px] font-bold leading-none bg-bambu-gray/20 text-bambu-gray shrink-0",title:L.nozzle_id===1?l("printModal.leftNozzleTooltip"):l("printModal.rightNozzleTooltip"),children:L.nozzle_id===1?l("printModal.leftNozzle"):l("printModal.rightNozzle")}),L.type," ",r.jsxs("span",{className:"text-bambu-gray",children:["(",L.used_grams,"g)"]})]}),r.jsx("span",{className:"text-bambu-gray",children:"→"}),r.jsxs("select",{value:L.loaded?.globalTrayId??"",onChange:re=>I(L.slot_id||0,re.target.value),className:`flex-1 px-2 py-1 rounded border text-xs bg-bambu-dark-secondary focus:outline-none focus:ring-1 focus:ring-bambu-green ${L.status==="match"?"border-bambu-green/50 text-bambu-green":L.status==="type_only"?"border-yellow-400/50 text-yellow-400":"border-orange-400/50 text-orange-400"} ${L.isManual?"ring-1 ring-blue-400/50":""}`,title:L.isManual?"Manually selected":"Auto-matched",children:[r.jsx("option",{value:"",className:"bg-bambu-dark text-bambu-gray",children:"-- Select slot --"}),w.filter(re=>L.nozzle_id==null||S||re.extruderId===L.nozzle_id).map(re=>{const J=C.get(re.globalTrayId),de=J!=null?l("printModal.slotRemainingShort",{grams:J,defaultValue:` - ${J}g left`}):"",me=S?M(re.globalTrayId):null,ue=me==null?"":` [${l(me===1?"printModal.leftNozzle":"printModal.rightNozzle")}]`;return r.jsxs("option",{value:re.globalTrayId,className:"bg-bambu-dark text-white",children:[re.label,": ",re.traySubBrands||re.type," (",re.colorName,")",de,ue]},re.globalTrayId)})]}),L.status==="match"?r.jsx(_r,{className:"w-3 h-3 text-bambu-green"}):L.status==="type_only"?r.jsx("span",{title:"Same type, different color",children:r.jsx(Sn,{className:"w-3 h-3 text-yellow-400"})}):r.jsx("span",{title:"Filament type not loaded",children:r.jsx(Sn,{className:"w-3 h-3 text-orange-400"})})]},Z)),r.jsxs("div",{className:"text-xs text-bambu-gray",children:[l("printModal.totalCost")," ",r.jsx("span",{className:"text-white",children:P>0||T?`${i}${P.toFixed(2)}`:"N/A"})]}),x&&r.jsx("p",{className:"text-xs text-orange-400 mt-2",children:"Required filament type not found in printer."})]})]})}function x7e({filamentReqs:t,availableFilaments:e,overrides:n,onChange:a,forceColorMatch:i,onForceColorMatchChange:s}){const{t:o}=kt(),l=v.useMemo(()=>{const u={};for(const m of e){const p=gP(m.type);u[p]||(u[p]=[]),u[p].push(m)}return u},[e]),c=t?.filaments;if(!c||c.length===0||e.length===0)return null;const d=(u,m)=>{if(m===""){const p={...n};delete p[u],a(p)}else{const[p,f]=m.split("|");a({...n,[u]:{type:p,color:f}})}};return r.jsxs("div",{className:"mb-4",children:[r.jsx("div",{className:"flex items-center gap-2 text-sm text-bambu-gray mb-2",children:r.jsx("span",{children:o("printModal.filamentOverride")})}),r.jsx("p",{className:"text-xs text-bambu-gray mb-2",children:o("printModal.filamentOverrideHint")}),r.jsx("div",{className:"bg-bambu-dark rounded-lg p-3 space-y-2",children:c.map(u=>{const m=n[u.slot_id],p=!!m,f=l[gP(u.type)]||[],b=u.nozzle_id!=null?f.filter(w=>w.extruder_id==null||w.extruder_id===u.nozzle_id):f;return r.jsxs("div",{className:"space-y-1",children:[r.jsxs("div",{className:"grid items-center gap-2 text-xs",style:{gridTemplateColumns:"16px minmax(70px, 1fr) auto 2fr 20px"},children:[r.jsx("span",{title:`${o("printModal.originalFilament")}: ${u.type} - ${bc(u.color)}`,children:r.jsx(Cw,{className:"w-3 h-3",fill:u.color,stroke:u.color})}),r.jsxs("span",{className:"text-white truncate",children:[u.type," ",r.jsxs("span",{className:"text-bambu-gray",children:["(",u.used_grams,"g)"]})]}),r.jsx("span",{className:"text-bambu-gray",children:"→"}),r.jsxs("select",{value:p?`${m.type}|${m.color}`:"",onChange:w=>d(u.slot_id,w.target.value),disabled:b.length===0,className:`flex-1 px-2 py-1 rounded border text-xs bg-bambu-dark-secondary focus:outline-none focus:ring-1 focus:ring-bambu-green ${p?"border-blue-400/50 text-blue-400":"border-bambu-gray/30 text-bambu-gray"}`,children:[r.jsxs("option",{value:"",className:"bg-bambu-dark text-bambu-gray",children:[o("printModal.originalFilament"),": ",u.type," (",bc(u.color),")"]}),b.map((w,g)=>r.jsxs("option",{value:`${w.type}|${w.color}`,className:"bg-bambu-dark text-white",children:[w.tray_sub_brands||w.type," (",bc(w.color),")"]},`${w.type}-${w.color}-${w.tray_sub_brands}-${g}`))]}),p?r.jsx("button",{type:"button",onClick:()=>d(u.slot_id,""),className:"text-bambu-gray hover:text-white transition-colors",title:o("printModal.resetToOriginal"),children:r.jsx(hs,{className:"w-3 h-3"})}):r.jsx("span",{className:"w-3"})]}),r.jsxs("label",{className:"inline-flex items-center gap-1.5 text-xs text-bambu-gray cursor-pointer select-none pl-5",children:[r.jsx("input",{type:"checkbox",checked:i?.[u.slot_id]??!1,onChange:w=>s?.(u.slot_id,w.target.checked),className:"accent-bambu-green w-3 h-3"}),r.jsx(PS,{className:"w-3 h-3"}),o("printModal.forceColorMatch")]})]},u.slot_id)})})]})}function y7e({plates:t,isMultiPlate:e,selectedPlates:n,onToggle:a,onSelectAll:i,onDeselectAll:s,multiSelect:o}){const{t:l}=kt();if(!e||t.length<=1)return null;const c=n.size===t.length;return r.jsxs("div",{className:"mb-4",children:[r.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[r.jsx(da,{className:"w-4 h-4 text-bambu-gray"}),r.jsxs("span",{className:"text-sm text-bambu-gray",children:["Select Plate",o?"s":""," to Print"]}),n.size===0&&r.jsxs("span",{className:"text-xs text-orange-400 flex items-center gap-1",children:[r.jsx(Sn,{className:"w-3 h-3"}),"Selection required"]}),o&&i&&s&&r.jsx("button",{type:"button",onClick:c?s:i,className:`ml-auto text-xs px-2 py-0.5 rounded-full border transition-colors ${c?"border-bambu-green bg-bambu-green/10 text-bambu-green":"border-bambu-dark-tertiary text-bambu-gray hover:border-bambu-gray"}`,children:c?l("queue.deselectAll"):l("queue.selectAllPlates",{count:t.length})})]}),r.jsx("div",{className:"grid grid-cols-2 gap-2",children:t.map(d=>{const u=n.has(d.index);return r.jsxs("button",{type:"button",onClick:()=>a(d.index),className:`flex items-center gap-2 p-2 rounded-lg border transition-colors text-left ${u?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary bg-bambu-dark hover:border-bambu-gray"}`,children:[o&&(u?r.jsx(fs,{className:"w-4 h-4 text-bambu-green flex-shrink-0"}):r.jsx(ro,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"})),d.has_thumbnail&&d.thumbnail_url!=null?r.jsx("img",{src:Ra(d.thumbnail_url),alt:`Plate ${d.index}`,className:"w-10 h-10 rounded object-cover bg-bambu-dark-tertiary"}):r.jsx("div",{className:"w-10 h-10 rounded bg-bambu-dark-tertiary flex items-center justify-center",children:r.jsx(da,{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:d.name||`Plate ${d.index}`}),r.jsxs("p",{className:"text-xs text-bambu-gray truncate",children:[d.objects.length>0?d.objects.slice(0,3).join(", ")+(d.objects.length>3?"...":""):`${d.filaments.length} filament${d.filaments.length!==1?"s":""}`,d.print_time_seconds!=null?` • ${ls(d.print_time_seconds)}`:""]})]}),!o&&u&&r.jsx(_r,{className:"w-4 h-4 text-bambu-green flex-shrink-0"})]},d.index)})})]})}const v7e=new Set(["IDLE","FINISH","FAILED"]);function w7e({printerResult:t,filamentReqs:e,onUpdateConfig:n}){const a=tn(),[i,s]=v.useState(!1),o=(d,u)=>{if(d<=0)return;const m={...t.config.manualMappings};u===""?delete m[d]:m[d]=parseInt(u,10),n({useDefault:!1,manualMappings:m,autoConfigured:!1})},l=async()=>{s(!0);try{await se.refreshPrinterStatus(t.printerId),await new Promise(d=>setTimeout(d,500)),await a.refetchQueries({queryKey:["printer-status",t.printerId]})}finally{s(!1)}},c=e.map(d=>{const u=d.slot_id||0,m=t.config.manualMappings[u];let p,f=!1;if(m!==void 0)p=t.loadedFilaments.find(w=>w.globalTrayId===m),f=!0;else{const w=new Set(Object.values(t.config.manualMappings)),g=a.getQueryData(["settings"]);p=u7e(d,t.loadedFilaments,w,g?.prefer_lowest_filament)}let b="mismatch";if(p){const w=p.type?.toUpperCase()===d.type?.toUpperCase(),g=Ia(p.color)===Ia(d.color)||sd(p.color,d.color);w&&g?b="match":w&&(b="type_only")}return{req:d,loaded:p,status:b,isManual:f}});return r.jsxs("div",{className:"mt-2 bg-bambu-dark rounded-lg p-3 space-y-2",children:[r.jsxs("div",{className:"flex items-center justify-between mb-2",children:[r.jsx("span",{className:"text-xs text-bambu-gray",children:"Custom slot mapping"}),r.jsxs("button",{type:"button",onClick:l,className:"flex items-center gap-1 px-2 py-0.5 text-xs rounded border border-bambu-gray/30 hover:border-bambu-gray hover:bg-bambu-dark-tertiary transition-colors text-bambu-gray hover:text-white",disabled:i,children:[r.jsx(sr,{className:`w-3 h-3 ${i?"animate-spin":""}`}),r.jsx("span",{children:"Re-read"})]})]}),c.map(({req:d,loaded:u,status:m,isManual:p},f)=>r.jsxs("div",{className:"grid items-center gap-2 text-xs",style:{gridTemplateColumns:"16px minmax(70px, 1fr) auto 2fr 16px"},children:[r.jsx("span",{title:`Required: ${d.type} - ${bc(d.color)}`,children:r.jsx(Cw,{className:"w-3 h-3",fill:d.color,stroke:d.color})}),r.jsxs("span",{className:"text-white truncate",children:[d.type," ",r.jsxs("span",{className:"text-bambu-gray",children:["(",d.used_grams,"g)"]})]}),r.jsx("span",{className:"text-bambu-gray",children:"→"}),r.jsxs("select",{value:u?.globalTrayId??"",onChange:b=>o(d.slot_id||0,b.target.value),className:`flex-1 px-2 py-1 rounded border text-xs bg-bambu-dark-secondary focus:outline-none focus:ring-1 focus:ring-bambu-green ${m==="match"?"border-bambu-green/50 text-bambu-green":m==="type_only"?"border-yellow-400/50 text-yellow-400":"border-orange-400/50 text-orange-400"} ${p?"ring-1 ring-blue-400/50":""}`,title:p?"Manually selected":"Auto-matched",children:[r.jsx("option",{value:"",className:"bg-bambu-dark text-bambu-gray",children:"-- Select slot --"}),Uie(t.loadedFilaments,d.nozzle_id).map(b=>r.jsxs("option",{value:b.globalTrayId,className:"bg-bambu-dark text-white",children:[b.label,": ",b.traySubBrands||b.type," (",b.colorName,")"]},b.globalTrayId))]}),m==="match"?r.jsx(_r,{className:"w-3 h-3 text-bambu-green"}):m==="type_only"?r.jsx("span",{title:"Same type, different color",children:r.jsx(Sn,{className:"w-3 h-3 text-yellow-400"})}):r.jsx("span",{title:"Filament type not loaded",children:r.jsx(Sn,{className:"w-3 h-3 text-orange-400"})})]},f))]})}function S7e({printers:t,selectedPrinterIds:e,onMultiSelect:n,isLoading:a=!1,allowMultiple:i=!1,showInactive:s=!1,disableBusy:o=!1,printerMappingResults:l,filamentReqs:c,onAutoConfigurePrinter:d,onUpdatePrinterConfig:u,assignmentMode:m="printer",onAssignmentModeChange:p,targetModel:f,onTargetModelChange:b,targetLocation:w,onTargetLocationChange:g,slicedForModel:x}){const[_,N]=v.useState(!1),C=s?t:t.filter(ae=>ae.is_active),P=tf({queries:C.map(ae=>({queryKey:["printerStatus",ae.id],queryFn:()=>se.getPrinterStatus(ae.id),staleTime:5e3}))}),T=v.useMemo(()=>{const ae=new Map;return C.forEach((pe,ye)=>{const Te=P[ye];Te?.data&&ae.set(pe.id,Te.data)}),ae},[C,P]),A=ae=>{const pe=T.get(ae);return pe?pe.connected?!v7e.has(pe.state??""):!0:!1},F=ae=>{const pe=T.get(ae);if(!pe)return null;if(!pe.connected)return"Offline";const ye=pe.state;return ye?ye==="RUNNING"?pe.stg_cur_name||"Printing":ye==="PREPARE"?"Preparing":ye==="PAUSE"?"Paused":ye==="IDLE"?"Idle":ye==="FINISH"?"Finished":ye==="FAILED"?"Failed":ye:null},S=v.useMemo(()=>{if(m!=="printer"||!x||_)return C;const ae=C.filter(pe=>pe.model===x);return ae.length>0?ae:C},[C,m,x,_]),M=C.length-S.length,z=v.useMemo(()=>{const ae=C.map(pe=>pe.model).filter(pe=>!!pe);return[...new Set(ae)].sort()},[C]),I=v.useMemo(()=>{if(!f)return[];const ae=C.filter(pe=>pe.model===f&&pe.location).map(pe=>pe.location).filter(pe=>!!pe);return[...new Set(ae)].sort()},[C,f]),H=p&&b&&z.length>0,L=i&&e.length>1&&l&&c?.filaments&&c.filaments.length>0&&d&&u;if(a)return r.jsx("div",{className:"flex justify-center py-8",children:r.jsx(mt,{className:"w-6 h-6 text-bambu-green animate-spin"})});if(S.length===0)return r.jsxs("div",{className:"flex items-center gap-2 text-red-400 text-sm mb-4",children:[r.jsx(Ha,{className:"w-4 h-4"}),"No ",s?"":"active ","printers available"]});const Z=ae=>{o&&A(ae)||(i?e.includes(ae)?n(e.filter(pe=>pe!==ae)):n([...e,ae]):n([ae]))},re=()=>{const ae=o?S.filter(pe=>!A(pe.id)):S;n(ae.map(pe=>pe.id))},J=()=>{n([])},de=(ae,pe,ye)=>{ye.stopPropagation(),!(!d||!u)&&(pe?d(ae):u(ae,{useDefault:!0,manualMappings:{},autoConfigured:!1}))},me=ae=>e.includes(ae),ue=e.length,W=ae=>l?.find(pe=>pe.printerId===ae);return r.jsxs("div",{className:"space-y-2 mb-6",children:[H&&r.jsxs("div",{className:"flex gap-2 mb-4",children:[r.jsxs("button",{type:"button",onClick:()=>{p("printer"),b(null)},className:`flex-1 flex items-center justify-center gap-2 px-3 py-2 rounded-lg border transition-colors ${m==="printer"?"border-bambu-green bg-bambu-green/10 text-white":"border-bambu-dark-tertiary bg-bambu-dark text-bambu-gray hover:border-bambu-gray"}`,children:[r.jsx(mr,{className:"w-4 h-4"}),r.jsx("span",{className:"text-sm",children:"Specific Printer"})]}),r.jsxs("button",{type:"button",onClick:()=>{p("model"),n([]);const ae=x&&z.includes(x)?x:z[0];b(ae)},className:`flex-1 flex items-center justify-center gap-2 px-3 py-2 rounded-lg border transition-colors ${m==="model"?"border-bambu-green bg-bambu-green/10 text-white":"border-bambu-dark-tertiary bg-bambu-dark text-bambu-gray hover:border-bambu-gray"}`,children:[r.jsx(gm,{className:"w-4 h-4"}),r.jsxs("span",{className:"text-sm",children:["Any ",x||"Model"]})]})]}),m==="model"&&H&&r.jsxs("div",{className:"space-y-3 mb-4",children:[!x&&r.jsxs("div",{children:[r.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:"Target Model"}),r.jsxs("select",{value:f||"",onChange:ae=>{b(ae.target.value||null),g&&g(null)},className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none text-sm",children:[r.jsx("option",{value:"",children:"Select a model..."}),z.map(ae=>r.jsx("option",{value:ae,children:ae},ae))]})]}),f&&I.length>0&&g&&r.jsxs("div",{children:[r.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:"Location Filter (optional)"}),r.jsxs("select",{value:w||"",onChange:ae=>g(ae.target.value||null),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none text-sm",children:[r.jsx("option",{value:"",children:"Any location"}),I.map(ae=>r.jsx("option",{value:ae,children:ae},ae))]})]}),f&&r.jsxs("p",{className:"text-xs text-bambu-gray",children:["Scheduler will assign to first available idle ",f," printer",w?` in ${w}`:""]})]}),m==="printer"&&i&&S.length>1&&r.jsxs("div",{className:"flex items-center justify-between text-xs text-bambu-gray mb-2",children:[r.jsx("span",{children:ue===0?"Select printers":`${ue} printer${ue!==1?"s":""} selected`}),r.jsxs("div",{className:"flex gap-2",children:[ue0&&r.jsx("button",{type:"button",onClick:J,className:"text-bambu-gray hover:text-white transition-colors",children:"Clear"})]})]}),m==="printer"&&S.map(ae=>{const pe=me(ae.id),ye=W(ae.id),Te=ye&&!ye.config.useDefault,$=A(ae.id),K=o&&$,D=F(ae.id);return r.jsxs("div",{children:[r.jsxs("button",{type:"button",onClick:()=>Z(ae.id),disabled:K,className:`w-full flex items-center gap-3 p-3 rounded-lg border transition-colors ${K?"border-bambu-dark-tertiary bg-bambu-dark opacity-50 cursor-not-allowed":pe?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary bg-bambu-dark hover:border-bambu-gray"} ${ae.is_active?"":"opacity-60"}`,children:[r.jsx("div",{className:`p-2 rounded-lg ${K?"bg-bambu-dark-tertiary":pe?"bg-bambu-green/20":"bg-bambu-dark-tertiary"}`,children:r.jsx(mr,{className:`w-5 h-5 ${K?"text-bambu-gray/50":pe?"text-bambu-green":"text-bambu-gray"}`})}),r.jsxs("div",{className:"text-left flex-1",children:[r.jsxs("p",{className:`font-medium ${K?"text-bambu-gray":"text-white"}`,children:[ae.name,!ae.is_active&&r.jsx("span",{className:"text-bambu-gray text-xs ml-2",children:"(inactive)"})]}),r.jsxs("p",{className:"text-xs text-bambu-gray",children:[ae.model||"Unknown model"," • ",ae.ip_address]})]}),D&&r.jsx("span",{className:`text-xs px-2 py-0.5 rounded-full ${$?"bg-yellow-500/20 text-yellow-400":"bg-bambu-green/20 text-bambu-green"}`,children:D}),i&&r.jsx("div",{className:`w-5 h-5 rounded border-2 flex items-center justify-center transition-colors ${K?"border-bambu-gray/30":pe?"bg-bambu-green border-bambu-green":"border-bambu-gray/50"}`,children:pe&&r.jsx(_r,{className:"w-3 h-3 text-white"})})]}),pe&&L&&ye&&r.jsxs("div",{className:"ml-4 mt-2 mb-3",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",onClick:j=>j.stopPropagation(),children:[r.jsx("input",{type:"checkbox",checked:Te,onChange:j=>de(ae.id,j.target.checked,j),className:"w-3.5 h-3.5 rounded border-bambu-gray/30 bg-bambu-dark-secondary text-bambu-green focus:ring-bambu-green focus:ring-offset-0"}),r.jsx("span",{className:"text-xs text-bambu-gray",children:"Custom mapping"})]}),r.jsxs("span",{className:`text-xs ml-2 ${ye.matchStatus==="full"?"text-bambu-green":ye.matchStatus==="partial"?"text-yellow-400":"text-orange-400"}`,children:["(",ye.exactMatches,"/",ye.totalSlots," matched)"]}),ye.isLoading&&r.jsx(sr,{className:"w-3 h-3 text-bambu-gray animate-spin"}),Te&&r.jsxs("button",{type:"button",onClick:j=>{j.stopPropagation(),d(ae.id)},className:"ml-auto flex items-center gap-1 px-2 py-0.5 text-xs rounded border border-bambu-gray/30 hover:border-bambu-gray hover:bg-bambu-dark-tertiary transition-colors text-bambu-gray hover:text-white",children:[r.jsx(OZ,{className:"w-3 h-3"}),"Auto"]})]}),Te&&r.jsx(w7e,{printerResult:ye,filamentReqs:c.filaments,onUpdateConfig:j=>u(ae.id,j)})]})]},ae.id)}),m==="printer"&&M>0&&!_&&r.jsxs("button",{type:"button",onClick:()=>N(!0),className:"text-xs text-bambu-gray hover:text-white transition-colors mt-2 flex items-center gap-1",children:[r.jsx(Sn,{className:"w-3 h-3 text-yellow-400"}),M," other printer",M>1?"s":""," hidden (different model) —",r.jsx("span",{className:"underline",children:"show all"})]}),m==="printer"&&_&&x&&r.jsx("button",{type:"button",onClick:()=>N(!1),className:"text-xs text-bambu-gray hover:text-white transition-colors mt-2",children:r.jsxs("span",{className:"underline",children:["Show only ",x," printers"]})}),m==="printer"&&ue===0&&r.jsxs("p",{className:"text-xs text-orange-400 mt-1 flex items-center gap-1",children:[r.jsx(Ha,{className:"w-3 h-3"}),"Select at least one printer"]}),m==="model"&&!f&&r.jsxs("p",{className:"text-xs text-orange-400 mt-1 flex items-center gap-1",children:[r.jsx(Ha,{className:"w-3 h-3"}),"Select a target printer model"]})]})}const _7e=[{key:"bed_levelling",label:"Bed Levelling",desc:"Auto-level bed before print"},{key:"flow_cali",label:"Flow Calibration",desc:"Calibrate extrusion flow"},{key:"vibration_cali",label:"Vibration Calibration",desc:"Reduce ringing artifacts"},{key:"layer_inspect",label:"First Layer Inspection",desc:"AI inspection of first layer"},{key:"timelapse",label:"Timelapse",desc:"Record timelapse video"}];function k7e({options:t,onChange:e,defaultExpanded:n=!1}){const[a,i]=v.useState(n),s=o=>{e({...t,[o]:!t[o]})};return r.jsxs("div",{className:"mb-4",children:[r.jsxs("button",{type:"button",onClick:()=>i(!a),className:"flex items-center gap-2 text-sm text-bambu-gray hover:text-white transition-colors w-full",children:[r.jsx(MS,{className:"w-4 h-4"}),r.jsx("span",{children:"Print Options"}),a?r.jsx(Qo,{className:"w-4 h-4 ml-auto"}):r.jsx(Rn,{className:"w-4 h-4 ml-auto"})]}),a&&r.jsx("div",{className:"mt-2 bg-bambu-dark rounded-lg p-3 space-y-2",children:_7e.map(({key:o,label:l,desc:c})=>r.jsxs("label",{className:"flex items-center justify-between cursor-pointer group",children:[r.jsxs("div",{children:[r.jsx("span",{className:"text-sm text-white",children:l}),r.jsx("p",{className:"text-xs text-bambu-gray",children:c})]}),r.jsx("div",{className:`relative w-10 h-5 rounded-full transition-colors ${t[o]?"bg-bambu-green":"bg-bambu-dark-tertiary"}`,onClick:()=>s(o),children:r.jsx("div",{className:`absolute top-0.5 w-4 h-4 rounded-full bg-white transition-transform ${t[o]?"translate-x-5":"translate-x-0.5"}`})})]},o))})]})}function N7e({options:t,onChange:e,dateFormat:n="system",timeFormat:a="system",canControlPrinter:i=!0,showStagger:s=!1,printerCount:o=0,hasGcodeSnippets:l=!1}){const{t:c}=kt(),[d,u]=v.useState(""),[m,p]=v.useState(""),[f,b]=v.useState(!0),[w,g]=v.useState(!0),x=v.useRef(null),_=v.useRef(!1);v.useEffect(()=>{if(t.scheduleType!=="scheduled"){_.current=!1;return}if(!_.current){_.current=!0;let S;t.scheduledTime?(S=new Date(t.scheduledTime),isNaN(S.getTime())&&(S=new Date,S.setHours(S.getHours()+1,0,0,0))):(S=new Date,S.setHours(S.getHours()+1,0,0,0),e({...t,scheduledTime:KF(S)})),u(WF(S,n)),p(x6(S,a)),b(!0),g(!0)}},[t.scheduleType,t.scheduledTime,n,a,e,t]);const N=S=>{e({...t,scheduleType:S})},C=(S,M)=>{const z=Mve(S,n),I=Eve(M);b(!!z),g(!!I),z&&I&&(z.setHours(I.hours,I.minutes,0,0),z>new Date&&e({...t,scheduledTime:KF(z)}))},P=S=>{u(S),C(S,m)},T=S=>{p(S),C(d,S)},A=S=>{const M=S.target.value;if(M){const z=new Date(M);isNaN(z.getTime())||(u(WF(z,n)),p(x6(z,a)),b(!0),g(!0),e({...t,scheduledTime:M}))}},F=()=>{x.current?.showPicker()};return r.jsxs("div",{className:"space-y-4",children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-2",children:"When to print"}),r.jsxs("div",{className:"flex gap-2",children:[r.jsxs("button",{type:"button",className:`flex-1 px-2 py-2 rounded-lg border text-sm flex items-center justify-center gap-1.5 transition-colors ${t.scheduleType==="asap"?"bg-bambu-green border-bambu-green text-white":"bg-bambu-dark border-bambu-dark-tertiary text-bambu-gray hover:text-white"}`,onClick:()=>N("asap"),children:[r.jsx(Zn,{className:"w-4 h-4"}),"ASAP"]}),r.jsxs("button",{type:"button",className:`flex-1 px-2 py-2 rounded-lg border text-sm flex items-center justify-center gap-1.5 transition-colors ${t.scheduleType==="scheduled"?"bg-bambu-green border-bambu-green text-white":"bg-bambu-dark border-bambu-dark-tertiary text-bambu-gray hover:text-white"}`,onClick:()=>N("scheduled"),children:[r.jsx(ya,{className:"w-4 h-4"}),"Scheduled"]}),r.jsxs("button",{type:"button",className:`flex-1 px-2 py-2 rounded-lg border text-sm flex items-center justify-center gap-1.5 transition-colors ${t.scheduleType==="manual"?"bg-bambu-green border-bambu-green text-white":"bg-bambu-dark border-bambu-dark-tertiary text-bambu-gray hover:text-white"}`,onClick:()=>N("manual"),children:[r.jsx(AZ,{className:"w-4 h-4"}),"Queue Only"]})]})]}),t.scheduleType==="scheduled"&&r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Date & Time"}),r.jsxs("div",{className:"flex gap-2",children:[r.jsxs("div",{className:"flex-1 relative",children:[r.jsx("input",{type:"text",className:`w-full px-3 py-2 pr-10 bg-bambu-dark border rounded-lg text-white focus:outline-none ${f?"border-bambu-dark-tertiary focus:border-bambu-green":"border-red-500"}`,value:d,onChange:S=>P(S.target.value),placeholder:Tve(n)}),r.jsx("button",{type:"button",onClick:F,className:"absolute right-2 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white",title:"Open calendar",children:r.jsx(ya,{className:"w-4 h-4"})}),r.jsx("input",{ref:x,type:"datetime-local",className:"absolute top-0 left-0 w-0 h-0 opacity-0 pointer-events-none",value:t.scheduledTime,onChange:A,tabIndex:-1})]}),r.jsx("div",{className:"w-32",children:r.jsx("input",{type:"text",className:`w-full px-3 py-2 bg-bambu-dark border rounded-lg text-white focus:outline-none ${w?"border-bambu-dark-tertiary focus:border-bambu-green":"border-red-500"}`,value:m,onChange:S=>T(S.target.value),placeholder:Ave(a)})})]}),(!f||!w)&&r.jsx("p",{className:"mt-1 text-xs text-red-400",children:"Please enter a valid date and time"})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("input",{type:"checkbox",id:"requirePrevious",checked:t.requirePreviousSuccess,onChange:S=>e({...t,requirePreviousSuccess:S.target.checked}),className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),r.jsx("label",{htmlFor:"requirePrevious",className:"text-sm text-bambu-gray",children:"Only start if previous print succeeded"})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("input",{type:"checkbox",id:"autoOffAfter",checked:t.autoOffAfter,onChange:S=>e({...t,autoOffAfter:S.target.checked}),disabled:!i,className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green disabled:opacity-50"}),r.jsxs("label",{htmlFor:"autoOffAfter",className:`text-sm flex items-center gap-1 ${i?"text-bambu-gray":"text-bambu-gray/50"}`,children:[r.jsx(yu,{className:"w-3.5 h-3.5"}),"Power off printer when done"]})]}),l&&r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("input",{type:"checkbox",id:"gcodeInjection",checked:t.gcodeInjection,onChange:S=>e({...t,gcodeInjection:S.target.checked}),className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),r.jsxs("label",{htmlFor:"gcodeInjection",className:"text-sm flex items-center gap-1 text-bambu-gray",children:[r.jsx(qy,{className:"w-3.5 h-3.5"}),c("printModal.gcodeInjection","Inject auto-print G-code")]})]}),s&&t.scheduleType!=="manual"&&r.jsxs("div",{className:"space-y-3",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("input",{type:"checkbox",id:"staggerEnabled",checked:t.staggerEnabled,onChange:S=>e({...t,staggerEnabled:S.target.checked}),className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),r.jsxs("label",{htmlFor:"staggerEnabled",className:"text-sm flex items-center gap-1 text-bambu-gray",children:[r.jsx(da,{className:"w-3.5 h-3.5"}),c("printModal.staggerPrinterStarts","Stagger printer starts")]})]}),t.staggerEnabled&&r.jsxs("div",{className:"ml-6 space-y-3",children:[r.jsxs("div",{className:"flex gap-3",children:[r.jsxs("div",{className:"flex-1",children:[r.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:c("printModal.staggerGroupSize","Group size")}),r.jsx("input",{type:"number",min:1,max:o,value:t.staggerGroupSize,onChange:S=>e({...t,staggerGroupSize:Math.max(1,parseInt(S.target.value)||1)}),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:outline-none focus:border-bambu-green"})]}),r.jsxs("div",{className:"flex-1",children:[r.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:c("printModal.staggerInterval","Interval (min)")}),r.jsx("input",{type:"number",min:1,max:60,value:t.staggerIntervalMinutes,onChange:S=>e({...t,staggerIntervalMinutes:Math.max(1,parseInt(S.target.value)||1)}),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:outline-none focus:border-bambu-green"})]})]}),o>0&&(()=>{const S=Math.ceil(o/t.staggerGroupSize),M=o%t.staggerGroupSize,z=(S-1)*t.staggerIntervalMinutes;return r.jsxs("p",{className:"text-xs text-bambu-gray",children:[c("printModal.staggerPreview","{{printers}} printers → {{groups}} groups of {{size}}, starting every {{interval}} min",{printers:o,groups:S,size:t.staggerGroupSize,interval:t.staggerIntervalMinutes}),M!==0&&t.staggerGroupSize1?` (${c("printModal.staggerTotal","total: {{minutes}} min",{minutes:z})})`:""]})})()]})]}),r.jsx("p",{className:"text-xs text-bambu-gray",children:t.scheduleType==="asap"?"Print will start as soon as the printer is idle.":t.scheduleType==="scheduled"?"Print will start at the scheduled time if the printer is idle. If busy, it will wait until the printer becomes available.":"Print will be staged but won't start automatically. Use the Start button to release it to the queue."})]})}const Wc={bed_levelling:!0,flow_cali:!1,vibration_cali:!0,layer_inspect:!1,timelapse:!1},c3={scheduleType:"asap",scheduledTime:"",requirePreviousSuccess:!1,autoOffAfter:!1,gcodeInjection:!1,staggerEnabled:!1,staggerGroupSize:2,staggerIntervalMinutes:5};function yc({mode:t,archiveId:e,libraryFileId:n,archiveName:a,queueItem:i,initialSelectedPrinterIds:s,onClose:o,onSuccess:l,projectId:c,cleanupLibraryAfterDispatch:d}){const{t:u}=kt(),m=tn(),{showToast:p}=an(),{hasPermission:f}=cr(),b=!!n&&!e,[w,g]=v.useState(()=>t==="edit-queue-item"&&i?.printer_id?[i.printer_id]:s?.length?s:[]),[x,_]=v.useState(()=>t==="edit-queue-item"&&i?.plate_id!=null?new Set([i.plate_id]):new Set),N=x.size===1?[...x][0]:null,[C,P]=v.useState(1),[T,A]=v.useState(()=>t==="edit-queue-item"&&i?{bed_levelling:i.bed_levelling??Wc.bed_levelling,flow_cali:i.flow_cali??Wc.flow_cali,vibration_cali:i.vibration_cali??Wc.vibration_cali,layer_inspect:i.layer_inspect??Wc.layer_inspect,timelapse:i.timelapse??Wc.timelapse}:Wc),[F,S]=v.useState(()=>{if(t==="edit-queue-item"&&i){let _t="asap";i.manual_start?_t="manual":i.scheduled_time&&!IK(i.scheduled_time)&&(_t="scheduled");let Ft="";if(i.scheduled_time&&!IK(i.scheduled_time)){const Re=Xn(i.scheduled_time)??new Date;Ft=KF(Re)}return{scheduleType:_t,scheduledTime:Ft,requirePreviousSuccess:i.require_previous_success,autoOffAfter:i.auto_off_after,gcodeInjection:i.gcode_injection??!1,staggerEnabled:!1,staggerGroupSize:c3.staggerGroupSize,staggerIntervalMinutes:c3.staggerIntervalMinutes}}return c3}),[M,z]=v.useState(()=>{if(t==="edit-queue-item"&&i?.ams_mapping&&Array.isArray(i.ams_mapping)){const _t={};return i.ams_mapping.forEach((Ft,Re)=>{Ft!==-1&&(_t[Re+1]=Ft)}),_t}return{}}),[I,H]=v.useState({}),[L,Z]=v.useState(()=>t==="edit-queue-item"&&i?.target_model?"model":"printer"),[re,J]=v.useState(()=>t==="edit-queue-item"&&i?.target_model?i.target_model:null),[de,me]=v.useState(()=>t==="edit-queue-item"&&i?.target_location?i.target_location:null),[ue,W]=v.useState(()=>{if(t==="edit-queue-item"&&i?.filament_overrides){const _t={};for(const Ft of i.filament_overrides)_t[Ft.slot_id]={type:Ft.type,color:Ft.color};return _t}return{}}),[ae,pe]=v.useState(()=>{if(t==="edit-queue-item"&&i?.filament_overrides){const _t={};for(const Ft of i.filament_overrides)_t[Ft.slot_id]=Ft.force_color_match===!0;return _t}return{}}),[ye]=v.useState(()=>t==="edit-queue-item"&&i?.printer_id?[i.printer_id]:[]),[Te]=v.useState(()=>t==="edit-queue-item"&&i?i.plate_id:null),[$,K]=v.useState(!1),[D,j]=v.useState({current:0,total:0}),[B,X]=v.useState(null),[O,ie]=v.useState(new Set),U=w.length,G=w.length>0?w[0]:null,{data:Y}=Ke({queryKey:["settings"],queryFn:se.getSettings}),Q=v.useRef(!1);v.useEffect(()=>{!Y||Q.current||t==="edit-queue-item"||(Q.current=!0,A({bed_levelling:Y.default_bed_levelling??Wc.bed_levelling,flow_cali:Y.default_flow_cali??Wc.flow_cali,vibration_cali:Y.default_vibration_cali??Wc.vibration_cali,layer_inspect:Y.default_layer_inspect??Wc.layer_inspect,timelapse:Y.default_timelapse??Wc.timelapse}))},[Y,t]);const oe=v.useRef(!1);v.useEffect(()=>{!Y||oe.current||t==="edit-queue-item"||(oe.current=!0,S(_t=>({..._t,staggerGroupSize:Y.stagger_group_size??_t.staggerGroupSize,staggerIntervalMinutes:Y.stagger_interval_minutes??_t.staggerIntervalMinutes})))},[Y,t]);const ee=Bo(Y?.currency||"USD"),ge=Y?.default_filament_cost??0,{data:ce,isLoading:le}=Ke({queryKey:["printers"],queryFn:se.getPrinters}),{data:q}=Ke({queryKey:["spool-assignments"],queryFn:()=>se.getAssignments(),staleTime:30*1e3,enabled:(t==="reprint"||t==="add-to-queue")&&L==="printer"||b&&t==="reprint"}),{data:R}=Ke({queryKey:["archive",e],queryFn:()=>se.getArchive(e),enabled:!!e&&!b}),{data:ne}=Ke({queryKey:["library-file",n],queryFn:()=>se.getLibraryFile(n),enabled:b&&!!n}),be=R?.sliced_for_model||ne?.sliced_for_model||null,{data:Se,isError:Ne}=Ke({queryKey:["archive-plates",e],queryFn:()=>se.getArchivePlates(e),enabled:!!e&&!b,retry:!1}),{data:ve}=Ke({queryKey:["library-file-plates",n],queryFn:()=>se.getLibraryFilePlates(n),enabled:b&&!!n}),xe=b?ve:Se,{data:Ee,isError:ze}=Ke({queryKey:["archive-filaments",e,N],queryFn:()=>se.getArchiveFilamentRequirements(e,N??void 0),enabled:!!e&&!b&&(N!==null||!xe?.is_multi_plate),retry:!1}),{data:_e}=Ke({queryKey:["library-file-filaments",n,N],queryFn:()=>se.getLibraryFileFilamentRequirements(n,N??void 0),enabled:b&&!!n&&(N!==null||!xe?.is_multi_plate)}),Oe=!b&&(Ne||ze),Ie=b?_e:Ee,Ve=v.useMemo(()=>{if(!(N===null||!xe?.plates?.length))return xe.plates.find(_t=>_t.index===N)?.name||void 0},[xe,N]),{data:rt}=Ke({queryKey:["available-filaments",re,de],queryFn:()=>se.getAvailableFilaments(re,de??void 0),enabled:L==="model"&&!!re}),{data:st}=Ke({queryKey:["printer-status",G],queryFn:()=>se.getPrinterStatus(G),enabled:!!G}),{amsMapping:Le}=Bie(Ie,st,M,Y?.prefer_lowest_filament),tt=f7e(w,ce,Ie,M,I,H,Y?.prefer_lowest_filament);v.useEffect(()=>{xe?.plates&&xe.plates.length>=1&&x.size===0&&_(new Set([xe.plates[0].index]))},[xe,x.size]),v.useEffect(()=>{if(t==="edit-queue-item")return;const _t=ce?.filter(Ft=>Ft.is_active)||[];_t.length===1&&w.length===0&&g([_t[0].id])},[t,ce,w.length]),v.useEffect(()=>{t==="edit-queue-item"?(JSON.stringify(w.sort())!==JSON.stringify(ye.sort())||N!==Te)&&(z({}),H({}),ie(new Set)):(z({}),H({}),ie(new Set))},[t,w,N,ye,Te]);const[Ce,Ze]=v.useState(re),[Ue,fe]=v.useState(N);v.useEffect(()=>{(re!==Ce||N!==Ue)&&(Ze(re),fe(N),(t!=="edit-queue-item"||Ce!==null)&&(W({}),pe({})))},[re,N,Ce,Ue,t]),v.useEffect(()=>{if(!Y?.per_printer_mapping_expanded||w.length<=1)return;const _t=w.filter(Ft=>{if(O.has(Ft))return!1;const Re=tt.printerResults.find(je=>je.printerId===Ft);return Re&&Re.status&&!Re.isLoading});_t.length>0&&(ie(Ft=>{const Re=new Set(Ft);return _t.forEach(je=>Re.add(je)),Re}),_t.forEach(Ft=>{tt.autoConfigurePrinter(Ft)}))},[Y?.per_printer_mapping_expanded,w,O,tt]),v.useEffect(()=>{const _t=Ft=>{Ft.key==="Escape"&&!$&&o()};return window.addEventListener("keydown",_t),()=>window.removeEventListener("keydown",_t)},[o,$]);const Ae=xe?.is_multi_plate??!1,$e=xe?.plates??[],Be=v.useMemo(()=>{const _t=new Map;return q&&q.forEach(Ft=>{const Re=Ft.ams_id===255,je=Qg(Ft.ams_id,Ft.tray_id,Re),Ge=_t.get(Ft.printer_id)??new Map;Ge.set(je,Ft),_t.set(Ft.printer_id,Ge)}),_t},[q]),nt=v.useMemo(()=>{if(!B||B.length===0)return"";const _t=B.map(Ft=>u("printModal.insufficientFilamentLine",{printer:Ft.printerName,slot:Ft.slotLabel,required:Math.round(Ft.requiredGrams),remaining:Math.round(Ft.remainingGrams)}));return[u("printModal.insufficientFilamentMessage"),..._t].join(` +${l("inventory.assignProfileMismatchMessage",{spoolProfile:T.spoolProfile||l("common.unknown"),trayProfile:T.trayProfile||l("common.unknown"),location:s.location})}`:T.type==="profile"&&(K=l("inventory.assignProfileMismatchMessage",{spoolProfile:T.spoolProfile||l("common.unknown"),trayProfile:T.trayProfile||l("common.unknown"),location:s.location})),r.jsx(vn,{title:l("inventory.assignMismatchTitle"),message:K,confirmText:l("inventory.assignMismatchConfirm"),variant:"warning",isLoading:re.isPending,onConfirm:$,onCancel:()=>{re.isPending||(P(!1),N(null),A(null))}})})()]})}function AK(t,e){if(t===255)return"External";let n,a=!1;t>=128&&t<=135?(n=t-128,a=!0):t>=0&&t<=3?(n=t,a=e===1):n=0,n=Math.max(0,Math.min(n,7));const i=String.fromCharCode(65+n);return a?`HT-${i}`:`AMS-${i}`}function o3(t){const e=t.includes("_")?t.split("_")[0]:t;return e.startsWith("GFS")?"GF"+e.slice(3):(e.startsWith("PFUS")||e.startsWith("PFSP"),e)}const tw=["PLA","PETG","PCTG","ABS","ASA","TPU","PC","PA","NYLON","PVA","HIPS","PP","PET"];function jK(t){const e=t.replace(/@.+$/,"").trim(),n=e.toUpperCase(),a=n.match(/\bSUPPORT\s+FOR\s+/);if(a){const s=n.slice(a.index+a[0].length);for(const o of tw)if(new RegExp(`\\b${o}\\b`).test(s)){const c=e.slice(0,a.index).trim();return{material:o,brand:c,variant:"Support"}}}for(const s of tw){const o=new RegExp(`\\b${s}\\b`,"i");if(o.test(n)){const l=e.split(o),c=l[0]?.trim()||"",d=l[1]?.trim()||"";return{material:s,brand:c,variant:d}}}const i=e.split(/\s+/);return i.length>=2?{material:i[1],brand:i[0],variant:i.slice(2).join(" ")}:{material:e,brand:"",variant:""}}function s7e(t){return!t.startsWith("GF")&&!t.startsWith("P1")}const o7e={white:"FFFFFF",black:"000000",red:"FF0000",green:"00FF00",blue:"0000FF",yellow:"FFFF00",cyan:"00FFFF",magenta:"FF00FF",orange:"FFA500",purple:"800080",pink:"FFC0CB",brown:"8B4513",gray:"808080",grey:"808080","jade white":"FFFEF2",ivory:"FFFFF0",beige:"F5F5DC",cream:"FFFDD0",silver:"C0C0C0",gold:"FFD700",bronze:"CD7F32",copper:"B87333",navy:"000080",teal:"008080",olive:"808000",maroon:"800000",coral:"FF7F50",salmon:"FA8072",lime:"32CD32",mint:"98FF98","forest green":"228B22","sky blue":"87CEEB","royal blue":"4169E1",turquoise:"40E0D0",lavender:"E6E6FA",violet:"EE82EE",plum:"DDA0DD",tan:"D2B48C",chocolate:"D2691E",charcoal:"36454F",slate:"708090",transparent:"000000",natural:"F5F5DC",wood:"DEB887"},MK=[{name:"White",hex:"FFFFFF"},{name:"Black",hex:"000000"},{name:"Red",hex:"FF0000"},{name:"Blue",hex:"0000FF"},{name:"Green",hex:"00AA00"},{name:"Yellow",hex:"FFFF00"},{name:"Orange",hex:"FFA500"},{name:"Gray",hex:"808080"}],EK=[{name:"Cyan",hex:"00FFFF"},{name:"Magenta",hex:"FF00FF"},{name:"Purple",hex:"800080"},{name:"Pink",hex:"FFC0CB"},{name:"Brown",hex:"8B4513"},{name:"Beige",hex:"F5F5DC"},{name:"Navy",hex:"000080"},{name:"Teal",hex:"008080"},{name:"Lime",hex:"32CD32"},{name:"Gold",hex:"FFD700"},{name:"Silver",hex:"C0C0C0"},{name:"Maroon",hex:"800000"},{name:"Olive",hex:"808000"},{name:"Coral",hex:"FF7F50"},{name:"Salmon",hex:"FA8072"},{name:"Turquoise",hex:"40E0D0"},{name:"Violet",hex:"EE82EE"},{name:"Indigo",hex:"4B0082"},{name:"Chocolate",hex:"D2691E"},{name:"Tan",hex:"D2B48C"},{name:"Slate",hex:"708090"},{name:"Charcoal",hex:"36454F"},{name:"Ivory",hex:"FFFFF0"},{name:"Cream",hex:"FFFDD0"}];function DK(t){const e=t.toLowerCase().trim();return o7e[e]||null}function l7e(t){const e=t.indexOf("@");if(e<0)return null;const a=t.slice(e+1).trim().match(/^BBL\s+(.+?)(?:\s+[\d.]+\s*nozzle)?$/i);return a?a[1].trim():null}function Iie({isOpen:t,onClose:e,printerId:n,slotInfo:a,nozzleDiameter:i="0.4",printerModel:s,onSuccess:o,fullScreen:l}){const{t:c}=kt(),[d,u]=v.useState(""),[m,p]=v.useState(null),[f,b]=v.useState(""),[w,g]=v.useState(""),[x,_]=v.useState(""),[N,C]=v.useState(!1),[P,T]=v.useState(!1),A=v.useRef(""),{data:F,isLoading:S,isError:M}=Ke({queryKey:["cloudSettings"],queryFn:()=>se.getCloudSettings(),enabled:t,retry:!1}),{data:z,isLoading:I}=Ke({queryKey:["localPresets"],queryFn:()=>se.getLocalPresets(),enabled:t}),{data:H,isLoading:L}=Ke({queryKey:["builtinFilaments"],queryFn:()=>se.getBuiltinFilaments(),enabled:t,staleTime:1/0}),{data:Z,isLoading:re}=Ke({queryKey:["kprofiles",n,i],queryFn:()=>se.getKProfiles(n,i),enabled:t&&!!n}),{data:J}=Ke({queryKey:["colorCatalog"],queryFn:()=>se.getColorCatalog(),enabled:t,staleTime:1/0}),de=at({mutationFn:async()=>{if(!d)throw new Error("No filament preset selected");const j=d.startsWith("local_"),B=d.startsWith("builtin_"),X=j?parseInt(d.replace("local_",""),10):null,O=B?d.replace("builtin_",""):null,ie=j?z?.filament.find(Ee=>Ee.id===X):null,U=B?H?.find(Ee=>Ee.filament_id===O):null,G=!j&&!B?F?.filament.find(Ee=>Ee.setting_id===d):null;if(!j&&!B&&!G)throw new Error("Selected preset not found");if(j&&!ie)throw new Error("Selected local preset not found");if(B&&!U)throw new Error("Selected builtin preset not found");const Y=j?ie.name:B?U.name:G.name,Q=jK(Y),oe=m?.slot_id??-1,ee=f||a.trayColor?.slice(0,6)||"FFFFFF",ge=Y.replace(/@.+$/,"").trim();let ce,le;const q=Q.material.toUpperCase();if(j){const Ee=(tw.includes(q)?q:ie?.filament_type||Q.material||"").toUpperCase(),ze={PLA:"GFL99","PLA-CF":"GFL98","PLA SILK":"GFL96","PLA HIGH SPEED":"GFL95",PETG:"GFG99","PETG HF":"GFG96","PETG-CF":"GFG98",PCTG:"GFG97",ABS:"GFB99",ASA:"GFB98",PC:"GFC99",PA:"GFN99","PA-CF":"GFN98",NYLON:"GFN99",TPU:"GFU99",PVA:"GFS99",HIPS:"GFS98",PE:"GFP99",PP:"GFP97"};ce=ze[Ee]||ze[Ee.replace(/[-\s]?CF$/,"")]||ze[Ee.replace(/\+$/,"")]||ze[Ee.split(/[-\s]/)[0]]||"",le=""}else if(B)ce=O,le="";else if(ce=o3(d),le=d,!d.startsWith("GFS"))try{const Ee=await se.getCloudSettingDetail(d);Ee.filament_id&&(ce=Ee.filament_id)}catch(Ee){console.warn("Failed to fetch preset detail for filament_id:",Ee)}let R=j&&ie?.nozzle_temp_min?ie.nozzle_temp_min:190,ne=j&&ie?.nozzle_temp_max?ie.nozzle_temp_max:230;if(!j||B||!ie?.nozzle_temp_min&&!ie?.nozzle_temp_max){const Ee=(j?tw.includes(q)?q:ie?.filament_type||Q.material||"":Q.material).toUpperCase();Ee.includes("PLA")?(R=190,ne=230):Ee.includes("PETG")?(R=220,ne=260):Ee.includes("ABS")||Ee.includes("ASA")?(R=240,ne=280):Ee.includes("TPU")?(R=200,ne=240):Ee==="PCTG"?(R=220,ne=260):Ee.includes("PC")?(R=260,ne=300):(Ee.includes("PA")||Ee.includes("NYLON"))&&(R=250,ne=290)}const be=m?.k_value?parseFloat(m.k_value):0,Se=j?tw.includes(q)?q:ie?.filament_type||Q.material||"PLA":Q.material||"PLA",Ne=await se.configureAmsSlot(n,a.amsId,a.trayId,{tray_info_idx:ce,tray_type:Se,tray_sub_brands:ge,tray_color:ee+"FF",nozzle_temp_min:R,nozzle_temp_max:ne,cali_idx:oe,nozzle_diameter:i,setting_id:le,kprofile_filament_id:m?.filament_id,kprofile_setting_id:m?.setting_id||void 0,k_value:be}),ve=j?`local_${X}`:B?`builtin_${O}`:d,xe=j?"local":B?"builtin":"cloud";try{await se.saveSlotPreset(n,a.amsId,a.trayId,ve,ge,xe)}catch(Ee){console.warn("Failed to save slot preset mapping:",Ee)}return Ne},onSuccess:()=>{C(!0),o?.(),setTimeout(()=>{C(!1),e()},1500)}}),me=at({mutationFn:async()=>se.resetAmsSlot(n,a.amsId,a.trayId),onSuccess:()=>{C(!0),o?.(),setTimeout(()=>{C(!1),e()},1500)}}),ue=v.useMemo(()=>{const j=x.toLowerCase(),B=[],X=new Set,O=a.savedPresetId,ie=a.trayInfoIdx;if(F?.filament)for(const U of F.filament){X.add(U.setting_id);const Y=O===U.setting_id||ie&&(U.setting_id===ie||o3(U.setting_id)===ie);if(!(j&&!U.name.toLowerCase().includes(j))){if(!Y&&s){const Q=l7e(U.name);if(Q&&Q.toUpperCase()!==s.toUpperCase())continue}B.push({id:U.setting_id,name:U.name,source:"cloud",isUser:s7e(U.setting_id)})}}if(z?.filament)for(const U of z.filament){const G=`local_${U.id}`;j&&!U.name.toLowerCase().includes(j)||B.push({id:G,name:U.name,source:"local",isUser:!1})}if(H)for(const U of H){if(X.has(U.filament_id))continue;const G=U.filament_id.startsWith("GF")?"GFS"+U.filament_id.slice(2):U.filament_id;X.has(G)||(!j||U.name.toLowerCase().includes(j))&&B.push({id:`builtin_${U.filament_id}`,name:U.name,source:"builtin",isUser:!1})}return B.sort((U,G)=>{const Y={cloud:0,local:1,builtin:2};return U.source!==G.source?Y[U.source]-Y[G.source]:U.isUser&&!G.isUser?-1:!U.isUser&&G.isUser?1:U.name.localeCompare(G.name)})},[F?.filament,z?.filament,H,x,s,a.savedPresetId,a.trayInfoIdx]),W=v.useMemo(()=>{if(!d)return null;let j=null;if(d.startsWith("local_")){const O=parseInt(d.replace("local_",""),10);j=z?.filament.find(U=>U.id===O)?.name||null}else if(d.startsWith("builtin_")){const O=d.replace("builtin_","");j=H?.find(U=>U.filament_id===O)?.name||null}else F?.filament&&(j=F.filament.find(ie=>ie.setting_id===d)?.name||null);if(!j)return null;let B=j.replace(/@.+$/,"").trim();B.startsWith("# ")&&(B=B.slice(2).trim());const X=jK(B);return{fullName:B,material:X.material,brand:X.brand}},[d,F?.filament,z?.filament,H]),ae=W?.fullName||"",pe=v.useMemo(()=>{if(!J||!W)return[];const{fullName:j,brand:B}=W,X=j.replace(/^(Bambu\s*(Lab)?|eSUN|Polymaker|Overture|Sunlu|Hatchbox)\s*/i,"").trim();return J.filter(O=>{const ie=(O.material||"").toUpperCase(),U=O.manufacturer.toUpperCase();if(!(ie===X.toUpperCase()||ie.includes(X.toUpperCase())||X.toUpperCase().includes(ie)))return!1;if(B){const Y=B.toUpperCase();if(!U.includes(Y)&&!Y.includes(U))return!1}return!0})},[J,W]),ye=v.useMemo(()=>{if(!Z?.profiles||!W)return[];const{fullName:j,material:B,brand:X}=W,O=j.toUpperCase(),ie=B.toUpperCase(),U=X.toUpperCase();if(!ie||ie.length<2)return[];const G=Z.profiles.filter(Q=>{const oe=Q.name.toUpperCase();if(U)return!(!oe.includes(U)||!oe.includes(ie));if(oe.includes(O)||oe.includes(ie))return!0;const ge={NYLON:["PA","PA-CF","PA6"],PA:["NYLON"]}[ie]||[];for(const ce of ge)if(oe.includes(ce))return!0;return!1}),Y=new Map;for(const Q of G){const oe=`${Q.name}|${Q.k_value}`,ee=Y.get(oe);ee?a.extruderId!==void 0&&Q.extruder_id===a.extruderId&&ee.extruder_id!==a.extruderId&&Y.set(oe,Q):Y.set(oe,Q)}return Array.from(Y.values())},[Z?.profiles,W,a.extruderId]);v.useEffect(()=>{if(t){if(a.savedPresetId)u(a.savedPresetId);else if(a.trayInfoIdx&&F?.filament){let j=F.filament.find(B=>B.setting_id===a.trayInfoIdx);j||(j=F.filament.find(B=>o3(B.setting_id)===a.trayInfoIdx)),j&&u(j.setting_id)}else if(a.trayInfoIdx&&H?.length){const j=a.trayInfoIdx,B=H.find(X=>X.filament_id===j);B&&u(`builtin_${B.filament_id}`)}if(a.trayColor){const j=a.trayColor.slice(0,6);j&&b(j)}}else u(""),p(null),b(""),g(""),_(""),C(!1),A.current=""},[t,a.savedPresetId,a.trayInfoIdx,a.trayColor,F?.filament,H]),v.useEffect(()=>{if(ye.length>0){if(a.caliIdx!=null&&a.caliIdx>0){const j=ye.find(B=>B.slot_id===a.caliIdx);if(j){p(j);return}}p(ye[0])}else p(null)},[d,ye,a.caliIdx]);const Te=v.useCallback(j=>{j.key==="Escape"&&e()},[e]);v.useEffect(()=>{if(t)return document.addEventListener("keydown",Te),()=>document.removeEventListener("keydown",Te)},[t,Te]);const $=S&&!M||I||L||re;if(v.useEffect(()=>{if(!$&&d&&d!==A.current){const j=requestAnimationFrame(()=>{const X=document.querySelector('[class*="fixed inset-0 z-50"]')?.querySelector(`[data-preset-id="${CSS.escape(d)}"]`);X&&(A.current=d,X.scrollIntoView({block:"nearest"}))});return()=>cancelAnimationFrame(j)}},[d,$]),!t)return null;const K=d&&!de.isPending,D=f||a.trayColor?.slice(0,6)||"FFFFFF";return r.jsxs("div",{className:`fixed inset-0 z-50 flex ${l?"":"items-center justify-center"}`,children:[!l&&r.jsx("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-sm",onClick:e}),r.jsxs("div",{className:l?"relative w-full h-full bg-bambu-dark-secondary flex flex-col":"relative w-full max-w-lg mx-4 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl",children:[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(cu,{className:"w-5 h-5 text-bambu-blue"}),r.jsx("h2",{className:"text-lg font-semibold text-white",children:c("configureAmsSlot.title")}),l&&r.jsxs("div",{className:"flex items-center gap-2 ml-4 text-sm text-bambu-gray",children:[r.jsx("span",{className:"text-white/30",children:"|"}),a.trayColor&&r.jsx("span",{className:"w-4 h-4 rounded-full border border-black/20",style:{backgroundColor:`#${a.trayColor.slice(0,6)}`}}),r.jsx("span",{className:"text-white/70",children:c("configureAmsSlot.slotLabel",{ams:AK(a.amsId,a.trayCount),slot:a.trayId+1})}),a.traySubBrands&&r.jsxs("span",{children:["(",a.traySubBrands,")"]})]})]}),r.jsx("button",{onClick:e,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 overflow-y-auto ${l?"flex-1 min-h-0":"space-y-4 max-h-[60vh]"}`,children:[N&&r.jsx("div",{className:"absolute inset-0 bg-bambu-dark-secondary/95 z-10 flex items-center justify-center rounded-xl",children:r.jsxs("div",{className:"text-center space-y-3",children:[r.jsx(td,{className:"w-16 h-16 text-bambu-green mx-auto"}),r.jsx("p",{className:"text-lg font-semibold text-white",children:c("configureAmsSlot.slotConfigured")}),r.jsx("p",{className:"text-sm text-bambu-gray",children:c("configureAmsSlot.settingsSentToPrinter")})]})}),!l&&r.jsxs("div",{className:"p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[r.jsx("p",{className:"text-xs text-bambu-gray mb-1",children:c("configureAmsSlot.configuringSlot")}),r.jsxs("div",{className:"flex items-center gap-2",children:[a.trayColor&&r.jsx("span",{className:"w-4 h-4 rounded-full border border-black/20",style:{backgroundColor:`#${a.trayColor.slice(0,6)}`}}),r.jsx("span",{className:"text-white font-medium",children:c("configureAmsSlot.slotLabel",{ams:AK(a.amsId,a.trayCount),slot:a.trayId+1})}),a.traySubBrands&&r.jsxs("span",{className:"text-bambu-gray",children:["(",a.traySubBrands,")"]})]})]}),$?r.jsx("div",{className:"flex justify-center py-8",children:r.jsx(mt,{className:"w-6 h-6 text-bambu-green animate-spin"})}):l?r.jsxs("div",{className:"flex gap-4 h-full",children:[r.jsxs("div",{className:"w-1/2 flex flex-col min-h-0",children:[r.jsxs("label",{className:"block text-sm text-bambu-gray mb-2",children:[c("configureAmsSlot.filamentProfile")," ",r.jsx("span",{className:"text-red-400",children:"*"})]}),r.jsx("input",{type:"text",placeholder:c("configureAmsSlot.searchPresets"),value:x,onChange:j=>_(j.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder:text-bambu-gray focus:border-bambu-green focus:outline-none mb-2 shrink-0"}),r.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto space-y-1",children:ue.length===0?r.jsx("p",{className:"text-center py-4 text-bambu-gray",children:F?.filament?.length===0&&!z?.filament?.length?c("configureAmsSlot.noPresetsAvailable"):c("configureAmsSlot.noMatchingPresets")}):ue.map(j=>r.jsx("button",{"data-preset-id":j.id,onClick:()=>u(j.id),className:`group w-full p-2 rounded-lg border text-left transition-colors ${d===j.id?"bg-bambu-green/20 border-bambu-green":"bg-bambu-dark border-bambu-dark-tertiary hover:border-bambu-gray"}`,children:r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsx("span",{className:"text-white text-sm truncate group-hover:whitespace-normal group-hover:break-all",title:j.name,children:j.name}),r.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[j.source==="local"&&r.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded bg-green-500/20 text-green-400",children:c("profiles.localProfiles.badge")}),j.source==="builtin"&&r.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded bg-amber-500/20 text-amber-400",children:c("configureAmsSlot.builtin")}),j.isUser&&r.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded bg-bambu-blue/20 text-bambu-blue",children:c("configureAmsSlot.custom")})]})]})},j.id))})]}),r.jsxs("div",{className:"w-1/2 flex flex-col gap-4 min-h-0 overflow-y-auto",children:[r.jsxs("div",{children:[r.jsxs("label",{className:"block text-sm text-bambu-gray mb-2",children:[c("configureAmsSlot.kProfileLabel"),ae&&r.jsx("span",{className:"ml-2 text-xs text-bambu-blue",children:c("configureAmsSlot.filteringFor",{material:ae})})]}),ye.length>0?r.jsxs("div",{className:"relative",children:[r.jsxs("select",{value:m?.name||"",onChange:j=>{const B=ye.find(X=>X.name===j.target.value);p(B||null)},className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none appearance-none pr-10",children:[r.jsx("option",{value:"",children:c("configureAmsSlot.noKProfile")}),ye.map(j=>r.jsxs("option",{value:j.name,children:[j.name," (K=",j.k_value,")"]},`${j.name}-${j.extruder_id}`))]}),r.jsx(Rn,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]}):d?r.jsx("p",{className:"text-sm text-bambu-gray italic py-2",children:c("configureAmsSlot.noMatchingKProfiles")}):r.jsx("span",{className:"inline-block text-xs px-2 py-1 rounded bg-amber-500/20 text-amber-400 border border-amber-500/30",children:c("configureAmsSlot.selectFilamentFirst")}),m&&r.jsx("p",{className:"text-xs text-bambu-green mt-1",children:c("configureAmsSlot.kFromCalibration",{value:m.k_value})})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-2",children:c("configureAmsSlot.customColorLabel")}),pe.length>0&&r.jsxs("div",{className:"mb-3",children:[r.jsx("p",{className:"text-xs text-bambu-gray mb-1.5",children:c("configureAmsSlot.presetColors",{name:W?.fullName})}),r.jsx("div",{className:"flex flex-wrap gap-1.5",children:pe.map(j=>r.jsxs("button",{onClick:()=>{const B=j.hex_color.replace("#","").toUpperCase();b(B),g(j.color_name)},className:`h-7 px-2 rounded-md border-2 transition-all flex items-center gap-1.5 ${f===j.hex_color.replace("#","").toUpperCase()?"border-bambu-green scale-105":"border-white/20 hover:border-white/40"}`,title:j.color_name,children:[r.jsx("span",{className:"w-4 h-4 rounded-full border border-black/20 flex-shrink-0",style:{backgroundColor:j.hex_color}}),r.jsx("span",{className:"text-xs text-white/80 whitespace-nowrap",children:j.color_name})]},j.id))})]}),r.jsxs("div",{className:"flex flex-wrap gap-1.5 mb-2",children:[MK.map(j=>r.jsx("button",{onClick:()=>{b(j.hex),g(j.name)},className:`w-7 h-7 rounded-md border-2 transition-all ${f===j.hex?"border-bambu-green scale-110":"border-white/20 hover:border-white/40"}`,style:{backgroundColor:`#${j.hex}`},title:j.name},j.hex)),r.jsx("button",{onClick:()=>T(!P),className:"w-7 h-7 rounded-md border-2 border-white/20 hover:border-white/40 flex items-center justify-center text-white/60 hover:text-white/80 transition-all text-xs",title:c(P?"configureAmsSlot.showLessColors":"configureAmsSlot.showMoreColors"),children:P?"−":"+"})]}),P&&r.jsx("div",{className:"flex flex-wrap gap-1.5 mb-2",children:EK.map(j=>r.jsx("button",{onClick:()=>{b(j.hex),g(j.name)},className:`w-7 h-7 rounded-md border-2 transition-all ${f===j.hex?"border-bambu-green scale-110":"border-white/20 hover:border-white/40"}`,style:{backgroundColor:`#${j.hex}`},title:j.name},j.hex))}),r.jsxs("div",{className:"flex gap-2 items-center",children:[r.jsx("div",{className:"w-10 h-10 rounded-lg border-2 border-white/20 flex-shrink-0",style:{backgroundColor:`#${D}`}}),r.jsx("input",{type:"text",placeholder:c("configureAmsSlot.colorPlaceholder"),value:w,onChange:j=>{const B=j.target.value;g(B);const X=DK(B);if(X)b(X);else{const O=B.replace(/[^0-9A-Fa-f]/g,"").toUpperCase();O.length===6?b(O):O.length===3&&b(O.split("").map(ie=>ie+ie).join(""))}},className:"flex-1 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder:text-bambu-gray focus:border-bambu-green focus:outline-none text-sm"}),f&&r.jsx("button",{onClick:()=>{b(""),g("")},className:"px-2 py-1 text-xs text-bambu-gray hover:text-white bg-bambu-dark-tertiary rounded",title:c("configureAmsSlot.clearCustomColor"),children:c("configureAmsSlot.clear")})]}),f&&r.jsx("p",{className:"text-xs text-bambu-gray mt-1.5",children:c("configureAmsSlot.hexLabel",{hex:f})})]})]})]}):r.jsxs(r.Fragment,{children:[r.jsxs("div",{children:[r.jsxs("label",{className:"block text-sm text-bambu-gray mb-2",children:[c("configureAmsSlot.filamentProfile")," ",r.jsx("span",{className:"text-red-400",children:"*"})]}),r.jsxs("div",{className:"relative",children:[r.jsx("input",{type:"text",placeholder:c("configureAmsSlot.searchPresets"),value:x,onChange:j=>_(j.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder:text-bambu-gray focus:border-bambu-green focus:outline-none mb-2"}),r.jsx("div",{className:"max-h-48 overflow-y-auto space-y-1",children:ue.length===0?r.jsx("p",{className:"text-center py-4 text-bambu-gray",children:F?.filament?.length===0&&!z?.filament?.length?c("configureAmsSlot.noPresetsAvailable"):c("configureAmsSlot.noMatchingPresets")}):ue.map(j=>r.jsx("button",{"data-preset-id":j.id,onClick:()=>u(j.id),className:`group w-full p-2 rounded-lg border text-left transition-colors ${d===j.id?"bg-bambu-green/20 border-bambu-green":"bg-bambu-dark border-bambu-dark-tertiary hover:border-bambu-gray"}`,children:r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsx("span",{className:"text-white text-sm truncate group-hover:whitespace-normal group-hover:break-all",title:j.name,children:j.name}),r.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[j.source==="local"&&r.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded bg-green-500/20 text-green-400",children:c("profiles.localProfiles.badge")}),j.source==="builtin"&&r.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded bg-amber-500/20 text-amber-400",children:c("configureAmsSlot.builtin")}),j.isUser&&r.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded bg-bambu-blue/20 text-bambu-blue",children:c("configureAmsSlot.custom")})]})]})},j.id))})]})]}),r.jsxs("div",{children:[r.jsxs("label",{className:"block text-sm text-bambu-gray mb-2",children:[c("configureAmsSlot.kProfileLabel"),ae&&r.jsx("span",{className:"ml-2 text-xs text-bambu-blue",children:c("configureAmsSlot.filteringFor",{material:ae})})]}),ye.length>0?r.jsxs("div",{className:"relative",children:[r.jsxs("select",{value:m?.name||"",onChange:j=>{const B=ye.find(X=>X.name===j.target.value);p(B||null)},className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none appearance-none pr-10",children:[r.jsx("option",{value:"",children:c("configureAmsSlot.noKProfile")}),ye.map(j=>r.jsxs("option",{value:j.name,children:[j.name," (K=",j.k_value,")"]},`${j.name}-${j.extruder_id}`))]}),r.jsx(Rn,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]}):d?r.jsx("p",{className:"text-sm text-bambu-gray italic py-2",children:c("configureAmsSlot.noMatchingKProfiles")}):r.jsx("span",{className:"inline-block text-xs px-2 py-1 rounded bg-amber-500/20 text-amber-400 border border-amber-500/30",children:c("configureAmsSlot.selectFilamentFirst")}),m&&r.jsx("p",{className:"text-xs text-bambu-green mt-1",children:c("configureAmsSlot.kFromCalibration",{value:m.k_value})})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-2",children:c("configureAmsSlot.customColorLabel")}),pe.length>0&&r.jsxs("div",{className:"mb-3",children:[r.jsx("p",{className:"text-xs text-bambu-gray mb-1.5",children:c("configureAmsSlot.presetColors",{name:W?.fullName})}),r.jsx("div",{className:"flex flex-wrap gap-1.5",children:pe.map(j=>r.jsxs("button",{onClick:()=>{const B=j.hex_color.replace("#","").toUpperCase();b(B),g(j.color_name)},className:`h-7 px-2 rounded-md border-2 transition-all flex items-center gap-1.5 ${f===j.hex_color.replace("#","").toUpperCase()?"border-bambu-green scale-105":"border-white/20 hover:border-white/40"}`,title:j.color_name,children:[r.jsx("span",{className:"w-4 h-4 rounded-full border border-black/20 flex-shrink-0",style:{backgroundColor:j.hex_color}}),r.jsx("span",{className:"text-xs text-white/80 whitespace-nowrap",children:j.color_name})]},j.id))})]}),r.jsxs("div",{className:"flex flex-wrap gap-1.5 mb-2",children:[MK.map(j=>r.jsx("button",{onClick:()=>{b(j.hex),g(j.name)},className:`w-7 h-7 rounded-md border-2 transition-all ${f===j.hex?"border-bambu-green scale-110":"border-white/20 hover:border-white/40"}`,style:{backgroundColor:`#${j.hex}`},title:j.name},j.hex)),r.jsx("button",{onClick:()=>T(!P),className:"w-7 h-7 rounded-md border-2 border-white/20 hover:border-white/40 flex items-center justify-center text-white/60 hover:text-white/80 transition-all text-xs",title:c(P?"configureAmsSlot.showLessColors":"configureAmsSlot.showMoreColors"),children:P?"−":"+"})]}),P&&r.jsx("div",{className:"flex flex-wrap gap-1.5 mb-2",children:EK.map(j=>r.jsx("button",{onClick:()=>{b(j.hex),g(j.name)},className:`w-7 h-7 rounded-md border-2 transition-all ${f===j.hex?"border-bambu-green scale-110":"border-white/20 hover:border-white/40"}`,style:{backgroundColor:`#${j.hex}`},title:j.name},j.hex))}),r.jsxs("div",{className:"flex gap-2 items-center",children:[r.jsx("div",{className:"w-10 h-10 rounded-lg border-2 border-white/20 flex-shrink-0",style:{backgroundColor:`#${D}`}}),r.jsx("input",{type:"text",placeholder:c("configureAmsSlot.colorPlaceholder"),value:w,onChange:j=>{const B=j.target.value;g(B);const X=DK(B);if(X)b(X);else{const O=B.replace(/[^0-9A-Fa-f]/g,"").toUpperCase();O.length===6?b(O):O.length===3&&b(O.split("").map(ie=>ie+ie).join(""))}},className:"flex-1 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder:text-bambu-gray focus:border-bambu-green focus:outline-none text-sm"}),f&&r.jsx("button",{onClick:()=>{b(""),g("")},className:"px-2 py-1 text-xs text-bambu-gray hover:text-white bg-bambu-dark-tertiary rounded",title:c("configureAmsSlot.clearCustomColor"),children:c("configureAmsSlot.clear")})]}),f&&r.jsx("p",{className:"text-xs text-bambu-gray mt-1.5",children:c("configureAmsSlot.hexLabel",{hex:f})})]})]})]}),r.jsxs("div",{className:"flex justify-between p-4 border-t border-bambu-dark-tertiary shrink-0",children:[r.jsx(Me,{variant:"secondary",onClick:()=>me.mutate(),disabled:me.isPending||de.isPending,className:"text-red-400 hover:text-red-300 hover:bg-red-500/10",children:me.isPending?r.jsxs(r.Fragment,{children:[r.jsx(mt,{className:"w-4 h-4 animate-spin"}),c("configureAmsSlot.resetting")]}):r.jsxs(r.Fragment,{children:[r.jsx(hs,{className:"w-4 h-4"}),c("configureAmsSlot.resetSlot")]})}),r.jsxs("div",{className:"flex gap-2",children:[r.jsx(Me,{variant:"secondary",onClick:e,children:c("configureAmsSlot.cancel")}),r.jsx(Me,{onClick:()=>de.mutate(),disabled:!K,children:de.isPending?r.jsxs(r.Fragment,{children:[r.jsx(mt,{className:"w-4 h-4 animate-spin"}),c("configureAmsSlot.configuring")]}):r.jsxs(r.Fragment,{children:[r.jsx(cu,{className:"w-4 h-4"}),c("configureAmsSlot.configureSlot")]})})]})]}),(de.isError||me.isError)&&r.jsx("div",{className:"mx-4 mb-4 p-2 bg-red-500/20 border border-red-500/50 rounded text-sm text-red-400",children:de.error?.message||me.error?.message})]})]})}function FK({className:t="w-4 h-4"}){return r.jsx("svg",{viewBox:"0 0 1945 1370",fill:"none",className:t,"aria-hidden":"true",children:r.jsxs("g",{transform:"translate(-754.293 -471.685)",children:[r.jsxs("g",{transform:"translate(0.18191 255.976)",children:[r.jsx("g",{transform:"matrix(1.05469 0 0 0.241063 -153.484 1120.2)",children:r.jsx("rect",{x:"922.048",y:"1195.15",width:"1721.5",height:"470.135",stroke:"currentColor",strokeOpacity:"0.99",strokeWidth:"168.84",strokeLinecap:"round",strokeLinejoin:"round"})}),r.jsx("g",{transform:"matrix(0.983656 0 0 1.0767 -62.2035 141.539)",children:r.jsx("path",{d:"M2741.42,1175.93L895.832,1175.93L1125.16,621.902L2512.09,621.902L2741.42,1175.93Z",fill:"currentColor",fillOpacity:"0.05",stroke:"currentColor",strokeOpacity:"0.99",strokeWidth:"125.26",strokeLinecap:"round",strokeLinejoin:"round"})})]}),r.jsx("g",{transform:"translate(21.1916 0.684817)",children:r.jsx("path",{d:"M1981.31,567.518C1954.86,567.518 1933.39,546.047 1933.39,519.601C1933.39,493.156 1954.86,471.685 1981.31,471.685L2146.61,471.685C2173.07,471.685 2194.53,493.138 2194.53,519.601L2194.53,688.741C2194.53,715.187 2173.05,736.658 2146.61,736.658C2120.16,736.658 2098.69,715.187 2098.69,688.741L2098.69,567.518L1981.31,567.518ZM2098.69,1252.54C2098.69,1226.1 2120.16,1204.62 2146.61,1204.62C2173.05,1204.62 2194.53,1226.1 2194.53,1252.54L2194.53,1421.68C2194.53,1448.14 2173.07,1469.6 2146.61,1469.6L1981.31,1469.6C1954.86,1469.6 1933.39,1448.13 1933.39,1421.68C1933.39,1395.24 1954.86,1373.76 1981.31,1373.76L2098.69,1373.76L2098.69,1252.54ZM1430.29,1373.76C1456.74,1373.76 1478.21,1395.24 1478.21,1421.68C1478.21,1448.13 1456.74,1469.6 1430.29,1469.6L1264.99,1469.6C1238.53,1469.6 1217.07,1448.14 1217.07,1421.68L1217.07,1252.54C1217.07,1226.1 1238.55,1204.62 1264.99,1204.62C1291.44,1204.62 1312.91,1226.1 1312.91,1252.54L1312.91,1373.76L1430.29,1373.76ZM1312.91,688.741C1312.91,715.187 1291.44,736.658 1264.99,736.658C1238.55,736.658 1217.07,715.187 1217.07,688.741L1217.07,519.601C1217.07,493.138 1238.53,471.685 1264.99,471.685L1430.29,471.685C1456.74,471.685 1478.21,493.156 1478.21,519.601C1478.21,546.047 1456.74,567.518 1430.29,567.518L1312.91,567.518L1312.91,688.741Z",fill:"currentColor",fillOpacity:"0.99"})})]})})}function Oie({folderId:t,onClose:e,onUploadComplete:n,onFileUploaded:a,autoUpload:i,validateFile:s,accept:o}){const{t:l}=kt(),[c,d]=v.useState([]),[u,m]=v.useState(!1),[p,f]=v.useState(!1),[b,w]=v.useState(!0),[g,x]=v.useState(!1),[_,N]=v.useState(!0),[C,P]=v.useState(null),T=v.useRef(null),A=ue=>{ue.preventDefault(),m(!0)},F=ue=>{ue.preventDefault(),m(!1)},S=ue=>{ue.preventDefault(),m(!1),H(Array.from(ue.dataTransfer.files))},M=ue=>{ue.target.files&&H(Array.from(ue.target.files))},z=(ue,W)=>{d(ae=>ae.map(pe=>pe.file===ue?{...pe,...W}:pe))},I=async ue=>{f(!0);for(const W of ue)if(W.status==="pending"){z(W.file,{status:"uploading"});try{if(W.isZip){const ae=await se.extractZipFile(W.file,t,b,g,_);z(W.file,{status:ae.errors.length>0&&ae.extracted===0?"error":"success",extractedCount:ae.extracted,error:ae.errors.length>0?l("fileManager.zipFilesFailed","{{count}} files failed",{count:ae.errors.length}):void 0})}else{const ae=await se.uploadLibraryFile(W.file,t,_);z(W.file,{status:"success"});const pe=a?.(ae);if(pe){P(pe),d([]),f(!1);return}}}catch(ae){z(W.file,{status:"error",error:ae instanceof Error?ae.message:l("fileManager.uploadFailed","Upload failed")})}}f(!1),n(),e()},H=ue=>{if(P(null),s)for(const ae of ue){const pe=s(ae);if(pe){P(pe);return}}const W=ue.map(ae=>({file:ae,status:"pending",isZip:ae.name.toLowerCase().endsWith(".zip"),is3mf:ae.name.toLowerCase().endsWith(".3mf")}));d(ae=>[...ae,...W]),i&&ue.length>0&&I(W)},L=ue=>{d(W=>W.filter((ae,pe)=>pe!==ue))},Z=c.some(ue=>ue.isZip&&ue.status==="pending"),re=c.some(ue=>ue.file.name.toLowerCase().endsWith(".stl")&&ue.status==="pending"),J=c.some(ue=>ue.is3mf&&ue.status==="pending"),de=c.filter(ue=>ue.status==="pending").length,me=c.length>0&&de===0&&!p;return r.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:r.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-lg border border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"p-4 border-b border-bambu-dark-tertiary flex items-center justify-between",children:[r.jsx("h2",{className:"text-lg font-semibold text-white",children:l("fileManager.uploadFiles")}),r.jsx("button",{onClick:e,className:"p-1 hover:bg-bambu-dark rounded",children:r.jsx(Ht,{className:"w-5 h-5 text-bambu-gray"})})]}),r.jsxs("div",{className:"p-4 space-y-4",children:[r.jsxs("div",{onDragOver:A,onDragLeave:F,onDrop:S,onClick:()=>T.current?.click(),className:`border-2 border-dashed rounded-lg p-8 text-center cursor-pointer transition-colors ${u?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary hover:border-bambu-green/50"}`,children:[r.jsx(ka,{className:`w-10 h-10 mx-auto mb-3 ${u?"text-bambu-green":"text-bambu-gray"}`}),r.jsx("p",{className:"text-white font-medium",children:l(u?"fileManager.dropFilesHere":"fileManager.dragDropFiles")}),r.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:l("fileManager.orClickToBrowse")}),r.jsx("p",{className:"text-xs text-bambu-gray/70 mt-2",children:l("fileManager.allFileTypesSupported")})]}),r.jsx("input",{ref:T,type:"file",multiple:!0,accept:o,className:"hidden",onChange:M}),Z&&r.jsx("div",{className:"p-3 bg-blue-500/10 border border-blue-500/30 rounded-lg",children:r.jsxs("div",{className:"flex items-start gap-3",children:[r.jsx(yo,{className:"w-5 h-5 text-blue-400 mt-0.5 flex-shrink-0"}),r.jsxs("div",{className:"flex-1",children:[r.jsx("p",{className:"text-sm text-blue-300 font-medium",children:l("fileManager.zipFilesDetected")}),r.jsx("p",{className:"text-xs text-blue-300/70 mt-1",children:l("fileManager.zipExtractOptions")}),r.jsxs("label",{className:"flex items-center gap-2 mt-2 cursor-pointer",children:[r.jsx("input",{type:"checkbox",checked:b,onChange:ue=>w(ue.target.checked),className:"w-4 h-4 rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),r.jsx("span",{className:"text-sm text-white",children:l("fileManager.preserveZipStructure")})]}),r.jsxs("label",{className:"flex items-center gap-2 mt-2 cursor-pointer",children:[r.jsx("input",{type:"checkbox",checked:g,onChange:ue=>x(ue.target.checked),className:"w-4 h-4 rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),r.jsx("span",{className:"text-sm text-white",children:l("fileManager.createFolderFromZip")})]})]})]})}),J&&r.jsx("div",{className:"p-3 bg-purple-500/10 border border-purple-500/30 rounded-lg",children:r.jsxs("div",{className:"flex items-start gap-3",children:[r.jsx(mr,{className:"w-5 h-5 text-purple-400 mt-0.5 flex-shrink-0"}),r.jsxs("div",{className:"flex-1",children:[r.jsx("p",{className:"text-sm text-purple-300 font-medium",children:l("fileManager.threemfDetected")}),r.jsx("p",{className:"text-xs text-purple-300/70 mt-1",children:l("fileManager.threemfExtractionInfo")})]})]})}),(re||Z)&&r.jsx("div",{className:"p-3 bg-bambu-green/10 border border-bambu-green/30 rounded-lg",children:r.jsxs("div",{className:"flex items-start gap-3",children:[r.jsx(lu,{className:"w-5 h-5 text-bambu-green mt-0.5 flex-shrink-0"}),r.jsxs("div",{className:"flex-1",children:[r.jsx("p",{className:"text-sm text-bambu-green font-medium",children:l("fileManager.stlThumbnailGeneration")}),r.jsx("p",{className:"text-xs text-bambu-green/70 mt-1",children:l(Z&&!re?"fileManager.zipMayContainStl":"fileManager.thumbnailsCanBeGenerated")}),r.jsxs("label",{className:"flex items-center gap-2 mt-2 cursor-pointer",children:[r.jsx("input",{type:"checkbox",checked:_,onChange:ue=>N(ue.target.checked),className:"w-4 h-4 rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),r.jsx("span",{className:"text-sm text-white",children:l("fileManager.generateThumbnailsForStl")})]})]})]})}),c.length>0&&r.jsx("div",{className:"max-h-48 overflow-y-auto space-y-2",children:c.map((ue,W)=>r.jsxs("div",{className:"flex items-center gap-3 p-2 bg-bambu-dark rounded-lg",children:[ue.isZip?r.jsx(yo,{className:"w-4 h-4 text-blue-400 flex-shrink-0"}):r.jsx(vT,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"}),r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsx("p",{className:"text-sm text-white truncate",children:ue.file.name}),r.jsxs("p",{className:"text-xs text-bambu-gray",children:[(ue.file.size/1024/1024).toFixed(2)," MB",ue.isZip&&ue.status==="pending"&&r.jsxs("span",{className:"text-blue-400 ml-2",children:["• ",l("fileManager.willBeExtracted")]}),ue.extractedCount!==void 0&&r.jsxs("span",{className:"text-green-400 ml-2",children:["• ",l("fileManager.filesExtracted",{count:ue.extractedCount})]})]})]}),ue.status==="pending"&&r.jsx("button",{onClick:()=>L(W),className:"p-1 hover:bg-bambu-dark-tertiary rounded",children:r.jsx(Ht,{className:"w-4 h-4 text-bambu-gray"})}),ue.status==="uploading"&&r.jsx(mt,{className:"w-4 h-4 text-bambu-green animate-spin"}),ue.status==="success"&&r.jsx(wr,{className:"w-4 h-4 text-green-500"}),ue.status==="error"&&r.jsx("span",{title:ue.error,children:r.jsx(ja,{className:"w-4 h-4 text-red-500"})})]},W))}),C&&r.jsx("div",{className:"p-3 bg-red-500/10 border border-red-500/30 rounded-lg",children:r.jsxs("div",{className:"flex items-start gap-3",children:[r.jsx(ja,{className:"w-5 h-5 text-red-400 mt-0.5 flex-shrink-0"}),r.jsx("p",{className:"text-sm text-red-300",children:C})]})})]}),r.jsxs("div",{className:"p-4 border-t border-bambu-dark-tertiary flex justify-end gap-2",children:[r.jsx(Me,{variant:"secondary",onClick:e,children:l("common.cancel")}),!me&&r.jsx(Me,{onClick:()=>I(c),disabled:de===0||p,children:p?r.jsxs(r.Fragment,{children:[r.jsx(mt,{className:"w-4 h-4 mr-2 animate-spin"}),l("fileManager.uploading")]}):r.jsxs(r.Fragment,{children:[r.jsx(ka,{className:"w-4 h-4 mr-2"}),l("common.upload")," ",de>0?`(${de})`:""]})})]})]})})}function RK(t){return t?`#${t.replace("#","").substring(0,6)}`:"#808080"}function Ia(t){return t?t.replace("#","").toLowerCase().substring(0,6):""}const c7e=[["PA-CF","PA12-CF","PAHT-CF"]],zie={};for(const t of c7e){const e=t[0];for(const n of t)zie[n.toUpperCase()]=e.toUpperCase()}function gP(t){if(!t)return"";const e=t.toUpperCase();return zie[e]??e}function l3(t,e){return gP(t)===gP(e)}function sd(t,e,n=40){const a=Ia(t),i=Ia(e);if(!a||!i||a.length<6||i.length<6)return!1;const s=parseInt(a.substring(0,2),16),o=parseInt(a.substring(2,4),16),l=parseInt(a.substring(4,6),16),c=parseInt(i.substring(0,2),16),d=parseInt(i.substring(2,4),16),u=parseInt(i.substring(4,6),16);return Math.abs(s-c)<=n&&Math.abs(o-d)<=n&&Math.abs(l-u)<=n}function o_(t,e,n,a){if(a)return"Ext";const i=String.fromCharCode(65+(t>=128?t-128:t));return n?`HT-${i}`:`${i}${e+1}`}function Qg(t,e,n){return n?254+e:t>=128?t:t*4+e}function ly(t){return t>50?"#00ae42":t>=15?"#f59e0b":"#ef4444"}function AN(t){return!t?.remaining_weight||!t?.filament_weight||t.filament_weight<=0?null:Math.min(100,Math.round(t.remaining_weight/t.filament_weight*100))}function LK(t,e){return(Number.isFinite(t)?Math.max(0,Math.trunc(t)):0).toString(16).toUpperCase().padStart(e,"0").slice(-e)}function d7e(t){const e=(t||"").trim().toUpperCase();let n=2166136261;for(let a=0;a>>0).toString(16).toUpperCase().padStart(8,"0")}function fm(t,e,n){return`${d7e(t)}${LK(e,4)}${LK(n,4)}`}function IK(t){if(!t)return!1;const e=Date.now()+4320*60*60*1e3;return(Xn(t)?.getTime()??0)>e}function u7e(t,e,n,a){let i=Uie(e,t.nozzle_id);a&&(i=[...i].sort((c,d)=>{const u=(c.remain??-1)>=0?c.remain??-1:101,m=(d.remain??-1)>=0?d.remain??-1:101;return u-m}));const s=i.find(c=>!n.has(c.globalTrayId)&&l3(c.type,t.type)&&Ia(c.color)===Ia(t.color)),o=s?void 0:i.find(c=>!n.has(c.globalTrayId)&&l3(c.type,t.type)&&sd(c.color,t.color)),l=s||o?void 0:i.find(c=>!n.has(c.globalTrayId)&&l3(c.type,t.type));return s??o??l}function Uie(t,e){return t.filter(n=>e==null||n.extruderId===e)}function Ys(t){return t?!!(t.tray_uuid&&t.tray_uuid!=="00000000000000000000000000000000"||t.tag_uid&&t.tag_uid!=="0000000000000000"):!1}function l_(t){const e=[],n=t?.ams_extruder_map,a=(t?.nozzles?.length??0)>1||n&&Object.keys(n).length>0;t?.ams?.forEach(i=>{const s=i.tray.length===1;i.tray.forEach(o=>{if(o.tray_type){const l=RK(o.tray_color);e.push({type:o.tray_type,color:l,colorName:bc(l),amsId:i.id,trayId:o.id,isHt:s,isExternal:!1,label:o_(i.id,o.id,s,!1),globalTrayId:Qg(i.id,o.id,!1),trayInfoIdx:o.tray_info_idx||"",traySubBrands:o.tray_sub_brands||"",extruderId:n?.[String(i.id)],remain:o.remain??-1})}})});for(const i of t?.vt_tray??[])if(i.tray_type){const s=RK(i.tray_color),o=i.id??254,l=(t?.vt_tray?.length??0)>1;e.push({type:i.tray_type,color:s,colorName:bc(s),amsId:-1,trayId:o-254,isHt:!1,isExternal:!0,label:l?o===254?"Ext-L":"Ext-R":"External",globalTrayId:o,trayInfoIdx:i.tray_info_idx||"",traySubBrands:i.tray_sub_brands||"",extruderId:a?255-o:void 0,remain:i.remain??-1})}return e}function OK(t,e,n){if(!t?.filaments||t.filaments.length===0)return;const a=l_(e);if(a.length===0)return;const i=e?.fila_switch?.installed===!0,s=new Set,o=t.filaments.map(d=>{const u=d.tray_info_idx||"";let m=a.filter(x=>!s.has(x.globalTrayId));d.nozzle_id!=null&&!i&&(m=m.filter(x=>x.extruderId===d.nozzle_id)),n&&(m=[...m].sort((x,_)=>{const N=x.remain>=0?x.remain:101,C=_.remain>=0?_.remain:101;return N-C}));let p,f,b,w;if(u){const x=m.filter(_=>_.trayInfoIdx===u);x.length===1?p=x[0]:x.length>1&&(n&&x.sort((_,N)=>{const C=_.remain>=0?_.remain:101,P=N.remain>=0?N.remain:101;return C-P}),f=x.find(_=>_.type?.toUpperCase()===d.type?.toUpperCase()&&Ia(_.color)===Ia(d.color)),f||(b=x.find(_=>_.type?.toUpperCase()===d.type?.toUpperCase()&&sd(_.color,d.color))),!f&&!b&&(w=x.find(_=>_.type?.toUpperCase()===d.type?.toUpperCase())))}!p&&!f&&!b&&!w&&(f=m.find(x=>x.type?.toUpperCase()===d.type?.toUpperCase()&&Ia(x.color)===Ia(d.color)),f||(b=m.find(x=>x.type?.toUpperCase()===d.type?.toUpperCase()&&sd(x.color,d.color))),!f&&!b&&(w=m.find(x=>x.type?.toUpperCase()===d.type?.toUpperCase())));const g=p||f||b||w||void 0;return g&&s.add(g.globalTrayId),{slot_id:d.slot_id,globalTrayId:g?.globalTrayId??-1}}),l=Math.max(...o.map(d=>d.slot_id||0));if(l<=0)return;const c=new Array(l).fill(-1);return o.forEach(d=>{d.slot_id&&d.slot_id>0&&(c[d.slot_id-1]=d.globalTrayId)}),c}function m7e(t){return v.useMemo(()=>l_(t),[t])}function Bie(t,e,n,a){const i=m7e(e),s=e?.fila_switch?.installed===!0,o=v.useMemo(()=>{if(!t?.filaments||t.filaments.length===0)return[];const u=new Set(Object.values(n));return t.filaments.map(m=>{const p=m.slot_id||0;if(p>0&&n[p]!==void 0){const F=n[p],S=i.find(M=>M.globalTrayId===F);if(S){const M=S.type?.toUpperCase()===m.type?.toUpperCase(),z=Ia(S.color)===Ia(m.color)||sd(S.color,m.color);let I;return M&&z?I="match":M?I="type_only":I="mismatch",{...m,loaded:S,hasFilament:!0,typeMatch:M,colorMatch:z,status:I,isManual:!0}}}const f=m.tray_info_idx||"";let b=i.filter(F=>!u.has(F.globalTrayId));m.nozzle_id!=null&&!s&&(b=b.filter(F=>F.extruderId===m.nozzle_id)),a&&(b=[...b].sort((F,S)=>{const M=F.remain>=0?F.remain:101,z=S.remain>=0?S.remain:101;return M-z}));let w,g,x,_;if(f){const F=b.filter(S=>S.trayInfoIdx===f);F.length===1?w=F[0]:F.length>1&&(a&&F.sort((S,M)=>{const z=S.remain>=0?S.remain:101,I=M.remain>=0?M.remain:101;return z-I}),g=F.find(S=>S.type?.toUpperCase()===m.type?.toUpperCase()&&Ia(S.color)===Ia(m.color)),g||(x=F.find(S=>S.type?.toUpperCase()===m.type?.toUpperCase()&&sd(S.color,m.color))),!g&&!x&&(_=F.find(S=>S.type?.toUpperCase()===m.type?.toUpperCase())))}!w&&!g&&!x&&!_&&(g=b.find(F=>F.type?.toUpperCase()===m.type?.toUpperCase()&&Ia(F.color)===Ia(m.color)),g||(x=b.find(F=>F.type?.toUpperCase()===m.type?.toUpperCase()&&sd(F.color,m.color))),!g&&!x&&(_=b.find(F=>F.type?.toUpperCase()===m.type?.toUpperCase())));const N=w||g||x||_||void 0;N&&u.add(N.globalTrayId);const C=!!N,P=C,T=!!w||!!g||!!x;let A;return w||g||x?A="match":_?A="type_only":A="mismatch",{...m,loaded:N,hasFilament:C,typeMatch:P,colorMatch:T,status:A,isManual:!1}})},[t,i,n,a,s]),l=v.useMemo(()=>{if(o.length===0)return;const u=Math.max(...o.map(p=>p.slot_id||0));if(u<=0)return;const m=new Array(u).fill(-1);return o.forEach(p=>{p.slot_id&&p.slot_id>0&&(m[p.slot_id-1]=p.loaded?.globalTrayId??-1)}),m},[o]),c=o.some(u=>u.status==="mismatch"),d=o.some(u=>u.status==="type_only");return{loadedFilaments:i,filamentComparison:o,amsMapping:l,hasTypeMismatch:c,hasColorMismatch:d}}function p7e(t,e,n,a){if(!t||t.length===0)return{exactMatches:0,typeOnlyMatches:0,missingTypes:0,totalSlots:0,status:"full"};let i=0,s=0,o=0;const l=new Set(Object.values(n));for(const u of t){const m=u.slot_id||0;if(m>0&&n[m]!==void 0){const x=n[m],_=e.find(N=>N.globalTrayId===x);if(_){const N=_.type?.toUpperCase()===u.type?.toUpperCase(),C=Ia(_.color)===Ia(u.color)||sd(_.color,u.color);N&&C?i++:N?s++:o++;continue}}let p=e.filter(x=>!l.has(x.globalTrayId));if(u.nozzle_id!=null){const x=p.filter(_=>_.extruderId===u.nozzle_id);x.length>0&&(p=x)}a&&(p=[...p].sort((x,_)=>{const N=x.remain>=0?x.remain:101,C=_.remain>=0?_.remain:101;return N-C}));const f=p.find(x=>x.type?.toUpperCase()===u.type?.toUpperCase()&&Ia(x.color)===Ia(u.color)),b=f?void 0:p.find(x=>x.type?.toUpperCase()===u.type?.toUpperCase()&&sd(x.color,u.color)),w=f||b?void 0:p.find(x=>x.type?.toUpperCase()===u.type?.toUpperCase()),g=f??b??w;g&&l.add(g.globalTrayId),f||b?i++:w?s++:o++}const c=t.length;let d="full";return o>0?d="missing":s>0&&(d="partial"),{exactMatches:i,typeOnlyMatches:s,missingTypes:o,totalSlots:c,status:d}}function h7e(t,e,n,a){if(!t?.filaments||t.filaments.length===0)return;const i=l_(e);if(i.length===0)return;const s=new Set(Object.values(n)),o=[];for(const d of t.filaments){const u=d.slot_id||0;if(u>0&&n[u]!==void 0){o.push({slot_id:u,globalTrayId:n[u]});continue}let m=i.filter(g=>!s.has(g.globalTrayId));if(d.nozzle_id!=null){const g=m.filter(x=>x.extruderId===d.nozzle_id);g.length>0&&(m=g)}a&&(m=[...m].sort((g,x)=>{const _=g.remain>=0?g.remain:101,N=x.remain>=0?x.remain:101;return _-N}));const p=m.find(g=>g.type?.toUpperCase()===d.type?.toUpperCase()&&Ia(g.color)===Ia(d.color)),f=p?void 0:m.find(g=>g.type?.toUpperCase()===d.type?.toUpperCase()&&sd(g.color,d.color)),b=p||f?void 0:m.find(g=>g.type?.toUpperCase()===d.type?.toUpperCase()),w=p??f??b;w&&s.add(w.globalTrayId),o.push({slot_id:u,globalTrayId:w?.globalTrayId??-1})}const l=Math.max(...o.map(d=>d.slot_id||0));if(l<=0)return;const c=new Array(l).fill(-1);return o.forEach(d=>{d.slot_id&&d.slot_id>0&&(c[d.slot_id-1]=d.globalTrayId)}),c}const zK={useDefault:!0,manualMappings:{},autoConfigured:!1};function f7e(t,e,n,a,i,s,o){const l=tf({queries:t.map(w=>({queryKey:["printer-status",w],queryFn:()=>se.getPrinterStatus(w),enabled:t.length>0,staleTime:5e3}))}),c=v.useMemo(()=>t.map((w,g)=>{const x=l[g],_=x?.data,C=e?.find(z=>z.id===w)?.name||`Printer ${w}`,P=l_(_),T=i[w]||zK,A=OK(n,_,o),F=T.useDefault?a:T.manualMappings,S=h7e(n,_,F,o),M=p7e(n?.filaments,P,F,o);return{printerId:w,printerName:C,status:_,isLoading:x?.isLoading??!1,loadedFilaments:P,autoMapping:A,finalMapping:S,matchStatus:M.status,exactMatches:M.exactMatches,typeOnlyMatches:M.typeOnlyMatches,missingTypes:M.missingTypes,totalSlots:M.totalSlots,config:T}}),[t,l,e,n,i,a,o]),d=l.some(w=>w.isLoading),u=(w,g)=>{s(x=>({...x,[w]:{...x[w]||zK,...g}}))},m=w=>{const g=c.find(N=>N.printerId===w);if(!g||!g.status||!n?.filaments)return;const x=OK(n,g.status,o);if(!x)return;const _={};x.forEach((N,C)=>{N!==-1&&(_[C+1]=N)}),u(w,{useDefault:!1,manualMappings:_,autoConfigured:!0})},p=()=>{for(const w of t)m(w)},f=w=>c.find(x=>x.printerId===w)?.finalMapping,b=c.every(w=>w.matchStatus!=="missing");return{printerResults:c,isLoading:d,perPrinterConfigs:i,updatePrinterConfig:u,autoConfigureAll:p,autoConfigurePrinter:m,getFinalMapping:f,allPrintersReady:b}}const Hie={USD:"$",EUR:"€",GBP:"£",CHF:"Fr.",JPY:"¥",CNY:"¥",CAD:"$",AUD:"$",INR:"₹",HKD:"HK$",KRW:"₩",SEK:"kr",NOK:"kr",DKK:"kr",PLN:"zł",BRL:"R$",TWD:"NT$",SGD:"S$",NZD:"NZ$",MXN:"MX$",MYR:"RM",CZK:"Kč",THB:"฿",ZAR:"R",TRY:"₺",RUB:"₽",HUF:"Ft",ILS:"₪",UAH:"₴"};function Bo(t){return Hie[t.toUpperCase()]||t}const g7e=Object.entries(Hie).map(([t,e])=>({code:t,label:`${t} (${e})`}));function b7e({printerId:t,filamentReqs:e,manualMappings:n,onManualMappingChange:a,currencySymbol:i,defaultCostPerKg:s,defaultExpanded:o=!1}){const{t:l}=kt(),c=tn(),[d,u]=v.useState(!1),[m,p]=v.useState(o),{data:f}=Ke({queryKey:["printer-status",t],queryFn:()=>se.getPrinterStatus(t),enabled:!!t}),{data:b}=Ke({queryKey:["spool-assignments",t],queryFn:()=>se.getAssignments(t),enabled:!!t}),{loadedFilaments:w,filamentComparison:g,hasTypeMismatch:x,hasColorMismatch:_}=Bie(e,f,n),N=v.useMemo(()=>{const L=new Map;for(const Z of b||[]){const re=Z.ams_id===255,J=Qg(Z.ams_id,Z.tray_id,re);L.set(J,Z.spool?.cost_per_kg??null)}return L},[b]),C=v.useMemo(()=>{const L=new Map;for(const Z of b||[]){const re=Z.ams_id===255,J=Qg(Z.ams_id,Z.tray_id,re),de=Z.spool;if(!de){L.set(J,null);continue}L.set(J,Math.max(0,Math.round((de.label_weight??0)-(de.weight_used??0))))}return L},[b]),P=v.useMemo(()=>{let L=0;for(const Z of g){const re=Z.loaded?.globalTrayId;if(re==null)continue;const de=N.get(re)??null??s;de>0&&(L+=Z.used_grams/1e3*de)}return L},[g,N,s]),T=v.useMemo(()=>Array.from(N.values()).some(L=>L!=null&&L>0),[N]),A=e?.filaments&&e.filaments.length>0,F=e?.filaments?.some(L=>L.nozzle_id!=null)??!1,S=f?.fila_switch?.installed===!0,M=L=>{const Z=f?.fila_switch;if(!Z?.installed)return null;const re=Z.in_slots.indexOf(L);return re<0?null:Z.out_extruders[re]??null};if(!A||!f)return null;const z=x?"#f97316":_?"#facc15":"#00ae42",I=(L,Z)=>{if(L>0)if(Z===""){const re={...n};delete re[L],a(re)}else a({...n,[L]:parseInt(Z,10)})},H=async()=>{u(!0);try{await se.refreshPrinterStatus(t),await new Promise(L=>setTimeout(L,500)),await c.refetchQueries({queryKey:["printer-status",t]})}finally{u(!1)}};return r.jsxs("div",{className:"mb-4",children:[r.jsxs("button",{type:"button",onClick:()=>p(!m),className:"flex items-center gap-2 text-sm text-bambu-gray hover:text-white transition-colors w-full",children:[r.jsx(Cw,{className:"w-4 h-4",fill:z,stroke:"none"}),r.jsx("span",{children:l("printModal.filamentMapping")}),x?r.jsx("span",{className:"text-xs text-orange-400",children:"(Type not found)"}):_?r.jsx("span",{className:"text-xs text-yellow-400",children:"(Color mismatch)"}):r.jsx("span",{className:"text-xs text-bambu-green",children:"(Ready)"}),m?r.jsx(Qo,{className:"w-4 h-4 ml-auto"}):r.jsx(Rn,{className:"w-4 h-4 ml-auto"})]}),m&&r.jsxs("div",{className:"mt-2 bg-bambu-dark rounded-lg p-3 space-y-2",children:[r.jsxs("div",{className:"flex items-center justify-between mb-2",children:[r.jsx("span",{className:"text-xs text-bambu-gray",children:"Click to change slot assignment"}),r.jsxs("button",{type:"button",onClick:H,className:"flex items-center gap-1 px-2 py-0.5 text-xs rounded border border-bambu-gray/30 hover:border-bambu-gray hover:bg-bambu-dark-tertiary transition-colors text-bambu-gray hover:text-white",disabled:d,children:[r.jsx(sr,{className:`w-3 h-3 ${d?"animate-spin":""}`}),r.jsx("span",{children:"Re-read"})]})]}),g.map((L,Z)=>r.jsxs("div",{className:"grid items-center gap-2 text-xs",style:{gridTemplateColumns:"16px minmax(70px, 1fr) auto 2fr 16px"},children:[r.jsx("span",{title:`Required: ${L.type} - ${bc(L.color)}`,children:r.jsx(Cw,{className:"w-3 h-3",fill:L.color,stroke:L.color})}),r.jsxs("span",{className:"text-white truncate flex items-center gap-1",children:[F&&L.nozzle_id!=null&&r.jsx("span",{className:"inline-flex items-center justify-center w-3.5 h-3.5 rounded text-[9px] font-bold leading-none bg-bambu-gray/20 text-bambu-gray shrink-0",title:L.nozzle_id===1?l("printModal.leftNozzleTooltip"):l("printModal.rightNozzleTooltip"),children:L.nozzle_id===1?l("printModal.leftNozzle"):l("printModal.rightNozzle")}),L.type," ",r.jsxs("span",{className:"text-bambu-gray",children:["(",L.used_grams,"g)"]})]}),r.jsx("span",{className:"text-bambu-gray",children:"→"}),r.jsxs("select",{value:L.loaded?.globalTrayId??"",onChange:re=>I(L.slot_id||0,re.target.value),className:`flex-1 px-2 py-1 rounded border text-xs bg-bambu-dark-secondary focus:outline-none focus:ring-1 focus:ring-bambu-green ${L.status==="match"?"border-bambu-green/50 text-bambu-green":L.status==="type_only"?"border-yellow-400/50 text-yellow-400":"border-orange-400/50 text-orange-400"} ${L.isManual?"ring-1 ring-blue-400/50":""}`,title:L.isManual?"Manually selected":"Auto-matched",children:[r.jsx("option",{value:"",className:"bg-bambu-dark text-bambu-gray",children:"-- Select slot --"}),w.filter(re=>L.nozzle_id==null||S||re.extruderId===L.nozzle_id).map(re=>{const J=C.get(re.globalTrayId),de=J!=null?l("printModal.slotRemainingShort",{grams:J,defaultValue:` - ${J}g left`}):"",me=S?M(re.globalTrayId):null,ue=me==null?"":` [${l(me===1?"printModal.leftNozzle":"printModal.rightNozzle")}]`;return r.jsxs("option",{value:re.globalTrayId,className:"bg-bambu-dark text-white",children:[re.label,": ",re.traySubBrands||re.type," (",re.colorName,")",de,ue]},re.globalTrayId)})]}),L.status==="match"?r.jsx(_r,{className:"w-3 h-3 text-bambu-green"}):L.status==="type_only"?r.jsx("span",{title:"Same type, different color",children:r.jsx(Sn,{className:"w-3 h-3 text-yellow-400"})}):r.jsx("span",{title:"Filament type not loaded",children:r.jsx(Sn,{className:"w-3 h-3 text-orange-400"})})]},Z)),r.jsxs("div",{className:"text-xs text-bambu-gray",children:[l("printModal.totalCost")," ",r.jsx("span",{className:"text-white",children:P>0||T?`${i}${P.toFixed(2)}`:"N/A"})]}),x&&r.jsx("p",{className:"text-xs text-orange-400 mt-2",children:"Required filament type not found in printer."})]})]})}function x7e({filamentReqs:t,availableFilaments:e,overrides:n,onChange:a,forceColorMatch:i,onForceColorMatchChange:s}){const{t:o}=kt(),l=v.useMemo(()=>{const u={};for(const m of e){const p=gP(m.type);u[p]||(u[p]=[]),u[p].push(m)}return u},[e]),c=t?.filaments;if(!c||c.length===0||e.length===0)return null;const d=(u,m)=>{if(m===""){const p={...n};delete p[u],a(p)}else{const[p,f]=m.split("|");a({...n,[u]:{type:p,color:f}})}};return r.jsxs("div",{className:"mb-4",children:[r.jsx("div",{className:"flex items-center gap-2 text-sm text-bambu-gray mb-2",children:r.jsx("span",{children:o("printModal.filamentOverride")})}),r.jsx("p",{className:"text-xs text-bambu-gray mb-2",children:o("printModal.filamentOverrideHint")}),r.jsx("div",{className:"bg-bambu-dark rounded-lg p-3 space-y-2",children:c.map(u=>{const m=n[u.slot_id],p=!!m,f=l[gP(u.type)]||[],b=u.nozzle_id!=null?f.filter(w=>w.extruder_id==null||w.extruder_id===u.nozzle_id):f;return r.jsxs("div",{className:"space-y-1",children:[r.jsxs("div",{className:"grid items-center gap-2 text-xs",style:{gridTemplateColumns:"16px minmax(70px, 1fr) auto 2fr 20px"},children:[r.jsx("span",{title:`${o("printModal.originalFilament")}: ${u.type} - ${bc(u.color)}`,children:r.jsx(Cw,{className:"w-3 h-3",fill:u.color,stroke:u.color})}),r.jsxs("span",{className:"text-white truncate",children:[u.type," ",r.jsxs("span",{className:"text-bambu-gray",children:["(",u.used_grams,"g)"]})]}),r.jsx("span",{className:"text-bambu-gray",children:"→"}),r.jsxs("select",{value:p?`${m.type}|${m.color}`:"",onChange:w=>d(u.slot_id,w.target.value),disabled:b.length===0,className:`flex-1 px-2 py-1 rounded border text-xs bg-bambu-dark-secondary focus:outline-none focus:ring-1 focus:ring-bambu-green ${p?"border-blue-400/50 text-blue-400":"border-bambu-gray/30 text-bambu-gray"}`,children:[r.jsxs("option",{value:"",className:"bg-bambu-dark text-bambu-gray",children:[o("printModal.originalFilament"),": ",u.type," (",bc(u.color),")"]}),b.map((w,g)=>r.jsxs("option",{value:`${w.type}|${w.color}`,className:"bg-bambu-dark text-white",children:[w.tray_sub_brands||w.type," (",bc(w.color),")"]},`${w.type}-${w.color}-${w.tray_sub_brands}-${g}`))]}),p?r.jsx("button",{type:"button",onClick:()=>d(u.slot_id,""),className:"text-bambu-gray hover:text-white transition-colors",title:o("printModal.resetToOriginal"),children:r.jsx(hs,{className:"w-3 h-3"})}):r.jsx("span",{className:"w-3"})]}),r.jsxs("label",{className:"inline-flex items-center gap-1.5 text-xs text-bambu-gray cursor-pointer select-none pl-5",children:[r.jsx("input",{type:"checkbox",checked:i?.[u.slot_id]??!1,onChange:w=>s?.(u.slot_id,w.target.checked),className:"accent-bambu-green w-3 h-3"}),r.jsx(PS,{className:"w-3 h-3"}),o("printModal.forceColorMatch")]})]},u.slot_id)})})]})}function y7e({plates:t,isMultiPlate:e,selectedPlates:n,onToggle:a,onSelectAll:i,onDeselectAll:s,multiSelect:o}){const{t:l}=kt();if(!e||t.length<=1)return null;const c=n.size===t.length;return r.jsxs("div",{className:"mb-4",children:[r.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[r.jsx(da,{className:"w-4 h-4 text-bambu-gray"}),r.jsxs("span",{className:"text-sm text-bambu-gray",children:["Select Plate",o?"s":""," to Print"]}),n.size===0&&r.jsxs("span",{className:"text-xs text-orange-400 flex items-center gap-1",children:[r.jsx(Sn,{className:"w-3 h-3"}),"Selection required"]}),o&&i&&s&&r.jsx("button",{type:"button",onClick:c?s:i,className:`ml-auto text-xs px-2 py-0.5 rounded-full border transition-colors ${c?"border-bambu-green bg-bambu-green/10 text-bambu-green":"border-bambu-dark-tertiary text-bambu-gray hover:border-bambu-gray"}`,children:c?l("queue.deselectAll"):l("queue.selectAllPlates",{count:t.length})})]}),r.jsx("div",{className:"grid grid-cols-2 gap-2",children:t.map(d=>{const u=n.has(d.index);return r.jsxs("button",{type:"button",onClick:()=>a(d.index),className:`flex items-center gap-2 p-2 rounded-lg border transition-colors text-left ${u?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary bg-bambu-dark hover:border-bambu-gray"}`,children:[o&&(u?r.jsx(fs,{className:"w-4 h-4 text-bambu-green flex-shrink-0"}):r.jsx(ro,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"})),d.has_thumbnail&&d.thumbnail_url!=null?r.jsx("img",{src:Ra(d.thumbnail_url),alt:`Plate ${d.index}`,className:"w-10 h-10 rounded object-cover bg-bambu-dark-tertiary"}):r.jsx("div",{className:"w-10 h-10 rounded bg-bambu-dark-tertiary flex items-center justify-center",children:r.jsx(da,{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:d.name||`Plate ${d.index}`}),r.jsxs("p",{className:"text-xs text-bambu-gray truncate",children:[d.objects.length>0?d.objects.slice(0,3).join(", ")+(d.objects.length>3?"...":""):`${d.filaments.length} filament${d.filaments.length!==1?"s":""}`,d.print_time_seconds!=null?` • ${ls(d.print_time_seconds)}`:""]})]}),!o&&u&&r.jsx(_r,{className:"w-4 h-4 text-bambu-green flex-shrink-0"})]},d.index)})})]})}const v7e=new Set(["IDLE","FINISH","FAILED"]);function w7e({printerResult:t,filamentReqs:e,onUpdateConfig:n}){const a=tn(),[i,s]=v.useState(!1),o=(d,u)=>{if(d<=0)return;const m={...t.config.manualMappings};u===""?delete m[d]:m[d]=parseInt(u,10),n({useDefault:!1,manualMappings:m,autoConfigured:!1})},l=async()=>{s(!0);try{await se.refreshPrinterStatus(t.printerId),await new Promise(d=>setTimeout(d,500)),await a.refetchQueries({queryKey:["printer-status",t.printerId]})}finally{s(!1)}},c=e.map(d=>{const u=d.slot_id||0,m=t.config.manualMappings[u];let p,f=!1;if(m!==void 0)p=t.loadedFilaments.find(w=>w.globalTrayId===m),f=!0;else{const w=new Set(Object.values(t.config.manualMappings)),g=a.getQueryData(["settings"]);p=u7e(d,t.loadedFilaments,w,g?.prefer_lowest_filament)}let b="mismatch";if(p){const w=p.type?.toUpperCase()===d.type?.toUpperCase(),g=Ia(p.color)===Ia(d.color)||sd(p.color,d.color);w&&g?b="match":w&&(b="type_only")}return{req:d,loaded:p,status:b,isManual:f}});return r.jsxs("div",{className:"mt-2 bg-bambu-dark rounded-lg p-3 space-y-2",children:[r.jsxs("div",{className:"flex items-center justify-between mb-2",children:[r.jsx("span",{className:"text-xs text-bambu-gray",children:"Custom slot mapping"}),r.jsxs("button",{type:"button",onClick:l,className:"flex items-center gap-1 px-2 py-0.5 text-xs rounded border border-bambu-gray/30 hover:border-bambu-gray hover:bg-bambu-dark-tertiary transition-colors text-bambu-gray hover:text-white",disabled:i,children:[r.jsx(sr,{className:`w-3 h-3 ${i?"animate-spin":""}`}),r.jsx("span",{children:"Re-read"})]})]}),c.map(({req:d,loaded:u,status:m,isManual:p},f)=>r.jsxs("div",{className:"grid items-center gap-2 text-xs",style:{gridTemplateColumns:"16px minmax(70px, 1fr) auto 2fr 16px"},children:[r.jsx("span",{title:`Required: ${d.type} - ${bc(d.color)}`,children:r.jsx(Cw,{className:"w-3 h-3",fill:d.color,stroke:d.color})}),r.jsxs("span",{className:"text-white truncate",children:[d.type," ",r.jsxs("span",{className:"text-bambu-gray",children:["(",d.used_grams,"g)"]})]}),r.jsx("span",{className:"text-bambu-gray",children:"→"}),r.jsxs("select",{value:u?.globalTrayId??"",onChange:b=>o(d.slot_id||0,b.target.value),className:`flex-1 px-2 py-1 rounded border text-xs bg-bambu-dark-secondary focus:outline-none focus:ring-1 focus:ring-bambu-green ${m==="match"?"border-bambu-green/50 text-bambu-green":m==="type_only"?"border-yellow-400/50 text-yellow-400":"border-orange-400/50 text-orange-400"} ${p?"ring-1 ring-blue-400/50":""}`,title:p?"Manually selected":"Auto-matched",children:[r.jsx("option",{value:"",className:"bg-bambu-dark text-bambu-gray",children:"-- Select slot --"}),Uie(t.loadedFilaments,d.nozzle_id).map(b=>r.jsxs("option",{value:b.globalTrayId,className:"bg-bambu-dark text-white",children:[b.label,": ",b.traySubBrands||b.type," (",b.colorName,")"]},b.globalTrayId))]}),m==="match"?r.jsx(_r,{className:"w-3 h-3 text-bambu-green"}):m==="type_only"?r.jsx("span",{title:"Same type, different color",children:r.jsx(Sn,{className:"w-3 h-3 text-yellow-400"})}):r.jsx("span",{title:"Filament type not loaded",children:r.jsx(Sn,{className:"w-3 h-3 text-orange-400"})})]},f))]})}function S7e({printers:t,selectedPrinterIds:e,onMultiSelect:n,isLoading:a=!1,allowMultiple:i=!1,showInactive:s=!1,disableBusy:o=!1,printerMappingResults:l,filamentReqs:c,onAutoConfigurePrinter:d,onUpdatePrinterConfig:u,assignmentMode:m="printer",onAssignmentModeChange:p,targetModel:f,onTargetModelChange:b,targetLocation:w,onTargetLocationChange:g,slicedForModel:x}){const[_,N]=v.useState(!1),C=s?t:t.filter(ae=>ae.is_active),P=tf({queries:C.map(ae=>({queryKey:["printerStatus",ae.id],queryFn:()=>se.getPrinterStatus(ae.id),staleTime:5e3}))}),T=v.useMemo(()=>{const ae=new Map;return C.forEach((pe,ye)=>{const Te=P[ye];Te?.data&&ae.set(pe.id,Te.data)}),ae},[C,P]),A=ae=>{const pe=T.get(ae);return pe?pe.connected?!v7e.has(pe.state??""):!0:!1},F=ae=>{const pe=T.get(ae);if(!pe)return null;if(!pe.connected)return"Offline";const ye=pe.state;return ye?ye==="RUNNING"?pe.stg_cur_name||"Printing":ye==="PREPARE"?"Preparing":ye==="PAUSE"?"Paused":ye==="IDLE"?"Idle":ye==="FINISH"?"Finished":ye==="FAILED"?"Failed":ye:null},S=v.useMemo(()=>{if(m!=="printer"||!x||_)return C;const ae=C.filter(pe=>pe.model===x);return ae.length>0?ae:C},[C,m,x,_]),M=C.length-S.length,z=v.useMemo(()=>{const ae=C.map(pe=>pe.model).filter(pe=>!!pe);return[...new Set(ae)].sort()},[C]),I=v.useMemo(()=>{if(!f)return[];const ae=C.filter(pe=>pe.model===f&&pe.location).map(pe=>pe.location).filter(pe=>!!pe);return[...new Set(ae)].sort()},[C,f]),H=p&&b&&z.length>0,L=i&&e.length>1&&l&&c?.filaments&&c.filaments.length>0&&d&&u;if(a)return r.jsx("div",{className:"flex justify-center py-8",children:r.jsx(mt,{className:"w-6 h-6 text-bambu-green animate-spin"})});if(S.length===0)return r.jsxs("div",{className:"flex items-center gap-2 text-red-400 text-sm mb-4",children:[r.jsx(Ha,{className:"w-4 h-4"}),"No ",s?"":"active ","printers available"]});const Z=ae=>{o&&A(ae)||(i?e.includes(ae)?n(e.filter(pe=>pe!==ae)):n([...e,ae]):n([ae]))},re=()=>{const ae=o?S.filter(pe=>!A(pe.id)):S;n(ae.map(pe=>pe.id))},J=()=>{n([])},de=(ae,pe,ye)=>{ye.stopPropagation(),!(!d||!u)&&(pe?d(ae):u(ae,{useDefault:!0,manualMappings:{},autoConfigured:!1}))},me=ae=>e.includes(ae),ue=e.length,W=ae=>l?.find(pe=>pe.printerId===ae);return r.jsxs("div",{className:"space-y-2 mb-6",children:[H&&r.jsxs("div",{className:"flex gap-2 mb-4",children:[r.jsxs("button",{type:"button",onClick:()=>{p("printer"),b(null)},className:`flex-1 flex items-center justify-center gap-2 px-3 py-2 rounded-lg border transition-colors ${m==="printer"?"border-bambu-green bg-bambu-green/10 text-white":"border-bambu-dark-tertiary bg-bambu-dark text-bambu-gray hover:border-bambu-gray"}`,children:[r.jsx(mr,{className:"w-4 h-4"}),r.jsx("span",{className:"text-sm",children:"Specific Printer"})]}),r.jsxs("button",{type:"button",onClick:()=>{p("model"),n([]);const ae=x&&z.includes(x)?x:z[0];b(ae)},className:`flex-1 flex items-center justify-center gap-2 px-3 py-2 rounded-lg border transition-colors ${m==="model"?"border-bambu-green bg-bambu-green/10 text-white":"border-bambu-dark-tertiary bg-bambu-dark text-bambu-gray hover:border-bambu-gray"}`,children:[r.jsx(gm,{className:"w-4 h-4"}),r.jsxs("span",{className:"text-sm",children:["Any ",x||"Model"]})]})]}),m==="model"&&H&&r.jsxs("div",{className:"space-y-3 mb-4",children:[!x&&r.jsxs("div",{children:[r.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:"Target Model"}),r.jsxs("select",{value:f||"",onChange:ae=>{b(ae.target.value||null),g&&g(null)},className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none text-sm",children:[r.jsx("option",{value:"",children:"Select a model..."}),z.map(ae=>r.jsx("option",{value:ae,children:ae},ae))]})]}),f&&I.length>0&&g&&r.jsxs("div",{children:[r.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:"Location Filter (optional)"}),r.jsxs("select",{value:w||"",onChange:ae=>g(ae.target.value||null),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none text-sm",children:[r.jsx("option",{value:"",children:"Any location"}),I.map(ae=>r.jsx("option",{value:ae,children:ae},ae))]})]}),f&&r.jsxs("p",{className:"text-xs text-bambu-gray",children:["Scheduler will assign to first available idle ",f," printer",w?` in ${w}`:""]})]}),m==="printer"&&i&&S.length>1&&r.jsxs("div",{className:"flex items-center justify-between text-xs text-bambu-gray mb-2",children:[r.jsx("span",{children:ue===0?"Select printers":`${ue} printer${ue!==1?"s":""} selected`}),r.jsxs("div",{className:"flex gap-2",children:[ue0&&r.jsx("button",{type:"button",onClick:J,className:"text-bambu-gray hover:text-white transition-colors",children:"Clear"})]})]}),m==="printer"&&S.map(ae=>{const pe=me(ae.id),ye=W(ae.id),Te=ye&&!ye.config.useDefault,$=A(ae.id),K=o&&$,D=F(ae.id);return r.jsxs("div",{children:[r.jsxs("button",{type:"button",onClick:()=>Z(ae.id),disabled:K,className:`w-full flex items-center gap-3 p-3 rounded-lg border transition-colors ${K?"border-bambu-dark-tertiary bg-bambu-dark opacity-50 cursor-not-allowed":pe?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary bg-bambu-dark hover:border-bambu-gray"} ${ae.is_active?"":"opacity-60"}`,children:[r.jsx("div",{className:`p-2 rounded-lg ${K?"bg-bambu-dark-tertiary":pe?"bg-bambu-green/20":"bg-bambu-dark-tertiary"}`,children:r.jsx(mr,{className:`w-5 h-5 ${K?"text-bambu-gray/50":pe?"text-bambu-green":"text-bambu-gray"}`})}),r.jsxs("div",{className:"text-left flex-1",children:[r.jsxs("p",{className:`font-medium ${K?"text-bambu-gray":"text-white"}`,children:[ae.name,!ae.is_active&&r.jsx("span",{className:"text-bambu-gray text-xs ml-2",children:"(inactive)"})]}),r.jsxs("p",{className:"text-xs text-bambu-gray",children:[ae.model||"Unknown model"," • ",ae.ip_address]})]}),D&&r.jsx("span",{className:`text-xs px-2 py-0.5 rounded-full ${$?"bg-yellow-500/20 text-yellow-400":"bg-bambu-green/20 text-bambu-green"}`,children:D}),i&&r.jsx("div",{className:`w-5 h-5 rounded border-2 flex items-center justify-center transition-colors ${K?"border-bambu-gray/30":pe?"bg-bambu-green border-bambu-green":"border-bambu-gray/50"}`,children:pe&&r.jsx(_r,{className:"w-3 h-3 text-white"})})]}),pe&&L&&ye&&r.jsxs("div",{className:"ml-4 mt-2 mb-3",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",onClick:j=>j.stopPropagation(),children:[r.jsx("input",{type:"checkbox",checked:Te,onChange:j=>de(ae.id,j.target.checked,j),className:"w-3.5 h-3.5 rounded border-bambu-gray/30 bg-bambu-dark-secondary text-bambu-green focus:ring-bambu-green focus:ring-offset-0"}),r.jsx("span",{className:"text-xs text-bambu-gray",children:"Custom mapping"})]}),r.jsxs("span",{className:`text-xs ml-2 ${ye.matchStatus==="full"?"text-bambu-green":ye.matchStatus==="partial"?"text-yellow-400":"text-orange-400"}`,children:["(",ye.exactMatches,"/",ye.totalSlots," matched)"]}),ye.isLoading&&r.jsx(sr,{className:"w-3 h-3 text-bambu-gray animate-spin"}),Te&&r.jsxs("button",{type:"button",onClick:j=>{j.stopPropagation(),d(ae.id)},className:"ml-auto flex items-center gap-1 px-2 py-0.5 text-xs rounded border border-bambu-gray/30 hover:border-bambu-gray hover:bg-bambu-dark-tertiary transition-colors text-bambu-gray hover:text-white",children:[r.jsx(OZ,{className:"w-3 h-3"}),"Auto"]})]}),Te&&r.jsx(w7e,{printerResult:ye,filamentReqs:c.filaments,onUpdateConfig:j=>u(ae.id,j)})]})]},ae.id)}),m==="printer"&&M>0&&!_&&r.jsxs("button",{type:"button",onClick:()=>N(!0),className:"text-xs text-bambu-gray hover:text-white transition-colors mt-2 flex items-center gap-1",children:[r.jsx(Sn,{className:"w-3 h-3 text-yellow-400"}),M," other printer",M>1?"s":""," hidden (different model) —",r.jsx("span",{className:"underline",children:"show all"})]}),m==="printer"&&_&&x&&r.jsx("button",{type:"button",onClick:()=>N(!1),className:"text-xs text-bambu-gray hover:text-white transition-colors mt-2",children:r.jsxs("span",{className:"underline",children:["Show only ",x," printers"]})}),m==="printer"&&ue===0&&r.jsxs("p",{className:"text-xs text-orange-400 mt-1 flex items-center gap-1",children:[r.jsx(Ha,{className:"w-3 h-3"}),"Select at least one printer"]}),m==="model"&&!f&&r.jsxs("p",{className:"text-xs text-orange-400 mt-1 flex items-center gap-1",children:[r.jsx(Ha,{className:"w-3 h-3"}),"Select a target printer model"]})]})}const _7e=[{key:"bed_levelling",label:"Bed Levelling",desc:"Auto-level bed before print"},{key:"flow_cali",label:"Flow Calibration",desc:"Calibrate extrusion flow"},{key:"vibration_cali",label:"Vibration Calibration",desc:"Reduce ringing artifacts"},{key:"layer_inspect",label:"First Layer Inspection",desc:"AI inspection of first layer"},{key:"timelapse",label:"Timelapse",desc:"Record timelapse video"}];function k7e({options:t,onChange:e,defaultExpanded:n=!1}){const[a,i]=v.useState(n),s=o=>{e({...t,[o]:!t[o]})};return r.jsxs("div",{className:"mb-4",children:[r.jsxs("button",{type:"button",onClick:()=>i(!a),className:"flex items-center gap-2 text-sm text-bambu-gray hover:text-white transition-colors w-full",children:[r.jsx(MS,{className:"w-4 h-4"}),r.jsx("span",{children:"Print Options"}),a?r.jsx(Qo,{className:"w-4 h-4 ml-auto"}):r.jsx(Rn,{className:"w-4 h-4 ml-auto"})]}),a&&r.jsx("div",{className:"mt-2 bg-bambu-dark rounded-lg p-3 space-y-2",children:_7e.map(({key:o,label:l,desc:c})=>r.jsxs("label",{className:"flex items-center justify-between cursor-pointer group",children:[r.jsxs("div",{children:[r.jsx("span",{className:"text-sm text-white",children:l}),r.jsx("p",{className:"text-xs text-bambu-gray",children:c})]}),r.jsx("div",{className:`relative w-10 h-5 rounded-full transition-colors ${t[o]?"bg-bambu-green":"bg-bambu-dark-tertiary"}`,onClick:()=>s(o),children:r.jsx("div",{className:`absolute top-0.5 w-4 h-4 rounded-full bg-white transition-transform ${t[o]?"translate-x-5":"translate-x-0.5"}`})})]},o))})]})}function N7e({options:t,onChange:e,dateFormat:n="system",timeFormat:a="system",canControlPrinter:i=!0,showStagger:s=!1,printerCount:o=0,hasGcodeSnippets:l=!1}){const{t:c}=kt(),[d,u]=v.useState(""),[m,p]=v.useState(""),[f,b]=v.useState(!0),[w,g]=v.useState(!0),x=v.useRef(null),_=v.useRef(!1);v.useEffect(()=>{if(t.scheduleType!=="scheduled"){_.current=!1;return}if(!_.current){_.current=!0;let S;t.scheduledTime?(S=new Date(t.scheduledTime),isNaN(S.getTime())&&(S=new Date,S.setHours(S.getHours()+1,0,0,0))):(S=new Date,S.setHours(S.getHours()+1,0,0,0),e({...t,scheduledTime:KF(S)})),u(WF(S,n)),p(x6(S,a)),b(!0),g(!0)}},[t.scheduleType,t.scheduledTime,n,a,e,t]);const N=S=>{e({...t,scheduleType:S})},C=(S,M)=>{const z=Mve(S,n),I=Eve(M);b(!!z),g(!!I),z&&I&&(z.setHours(I.hours,I.minutes,0,0),z>new Date&&e({...t,scheduledTime:KF(z)}))},P=S=>{u(S),C(S,m)},T=S=>{p(S),C(d,S)},A=S=>{const M=S.target.value;if(M){const z=new Date(M);isNaN(z.getTime())||(u(WF(z,n)),p(x6(z,a)),b(!0),g(!0),e({...t,scheduledTime:M}))}},F=()=>{x.current?.showPicker()};return r.jsxs("div",{className:"space-y-4",children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-2",children:"When to print"}),r.jsxs("div",{className:"flex gap-2",children:[r.jsxs("button",{type:"button",className:`flex-1 px-2 py-2 rounded-lg border text-sm flex items-center justify-center gap-1.5 transition-colors ${t.scheduleType==="asap"?"bg-bambu-green border-bambu-green text-white":"bg-bambu-dark border-bambu-dark-tertiary text-bambu-gray hover:text-white"}`,onClick:()=>N("asap"),children:[r.jsx(Zn,{className:"w-4 h-4"}),"ASAP"]}),r.jsxs("button",{type:"button",className:`flex-1 px-2 py-2 rounded-lg border text-sm flex items-center justify-center gap-1.5 transition-colors ${t.scheduleType==="scheduled"?"bg-bambu-green border-bambu-green text-white":"bg-bambu-dark border-bambu-dark-tertiary text-bambu-gray hover:text-white"}`,onClick:()=>N("scheduled"),children:[r.jsx(ya,{className:"w-4 h-4"}),"Scheduled"]}),r.jsxs("button",{type:"button",className:`flex-1 px-2 py-2 rounded-lg border text-sm flex items-center justify-center gap-1.5 transition-colors ${t.scheduleType==="manual"?"bg-bambu-green border-bambu-green text-white":"bg-bambu-dark border-bambu-dark-tertiary text-bambu-gray hover:text-white"}`,onClick:()=>N("manual"),children:[r.jsx(AZ,{className:"w-4 h-4"}),"Queue Only"]})]})]}),t.scheduleType==="scheduled"&&r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Date & Time"}),r.jsxs("div",{className:"flex gap-2",children:[r.jsxs("div",{className:"flex-1 relative",children:[r.jsx("input",{type:"text",className:`w-full px-3 py-2 pr-10 bg-bambu-dark border rounded-lg text-white focus:outline-none ${f?"border-bambu-dark-tertiary focus:border-bambu-green":"border-red-500"}`,value:d,onChange:S=>P(S.target.value),placeholder:Tve(n)}),r.jsx("button",{type:"button",onClick:F,className:"absolute right-2 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white",title:"Open calendar",children:r.jsx(ya,{className:"w-4 h-4"})}),r.jsx("input",{ref:x,type:"datetime-local",className:"absolute top-0 left-0 w-0 h-0 opacity-0 pointer-events-none",value:t.scheduledTime,onChange:A,tabIndex:-1})]}),r.jsx("div",{className:"w-32",children:r.jsx("input",{type:"text",className:`w-full px-3 py-2 bg-bambu-dark border rounded-lg text-white focus:outline-none ${w?"border-bambu-dark-tertiary focus:border-bambu-green":"border-red-500"}`,value:m,onChange:S=>T(S.target.value),placeholder:Ave(a)})})]}),(!f||!w)&&r.jsx("p",{className:"mt-1 text-xs text-red-400",children:"Please enter a valid date and time"})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("input",{type:"checkbox",id:"requirePrevious",checked:t.requirePreviousSuccess,onChange:S=>e({...t,requirePreviousSuccess:S.target.checked}),className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),r.jsx("label",{htmlFor:"requirePrevious",className:"text-sm text-bambu-gray",children:"Only start if previous print succeeded"})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("input",{type:"checkbox",id:"autoOffAfter",checked:t.autoOffAfter,onChange:S=>e({...t,autoOffAfter:S.target.checked}),disabled:!i,className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green disabled:opacity-50"}),r.jsxs("label",{htmlFor:"autoOffAfter",className:`text-sm flex items-center gap-1 ${i?"text-bambu-gray":"text-bambu-gray/50"}`,children:[r.jsx(yu,{className:"w-3.5 h-3.5"}),"Power off printer when done"]})]}),l&&r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("input",{type:"checkbox",id:"gcodeInjection",checked:t.gcodeInjection,onChange:S=>e({...t,gcodeInjection:S.target.checked}),className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),r.jsxs("label",{htmlFor:"gcodeInjection",className:"text-sm flex items-center gap-1 text-bambu-gray",children:[r.jsx(qy,{className:"w-3.5 h-3.5"}),c("printModal.gcodeInjection","Inject auto-print G-code")]})]}),s&&t.scheduleType!=="manual"&&r.jsxs("div",{className:"space-y-3",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("input",{type:"checkbox",id:"staggerEnabled",checked:t.staggerEnabled,onChange:S=>e({...t,staggerEnabled:S.target.checked}),className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),r.jsxs("label",{htmlFor:"staggerEnabled",className:"text-sm flex items-center gap-1 text-bambu-gray",children:[r.jsx(da,{className:"w-3.5 h-3.5"}),c("printModal.staggerPrinterStarts","Stagger printer starts")]})]}),t.staggerEnabled&&r.jsxs("div",{className:"ml-6 space-y-3",children:[r.jsxs("div",{className:"flex gap-3",children:[r.jsxs("div",{className:"flex-1",children:[r.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:c("printModal.staggerGroupSize","Group size")}),r.jsx("input",{type:"number",min:1,max:o,value:t.staggerGroupSize,onChange:S=>e({...t,staggerGroupSize:Math.max(1,parseInt(S.target.value)||1)}),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:outline-none focus:border-bambu-green"})]}),r.jsxs("div",{className:"flex-1",children:[r.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:c("printModal.staggerInterval","Interval (min)")}),r.jsx("input",{type:"number",min:1,max:60,value:t.staggerIntervalMinutes,onChange:S=>e({...t,staggerIntervalMinutes:Math.max(1,parseInt(S.target.value)||1)}),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:outline-none focus:border-bambu-green"})]})]}),o>0&&(()=>{const S=Math.ceil(o/t.staggerGroupSize),M=o%t.staggerGroupSize,z=(S-1)*t.staggerIntervalMinutes;return r.jsxs("p",{className:"text-xs text-bambu-gray",children:[c("printModal.staggerPreview","{{printers}} printers → {{groups}} groups of {{size}}, starting every {{interval}} min",{printers:o,groups:S,size:t.staggerGroupSize,interval:t.staggerIntervalMinutes}),M!==0&&t.staggerGroupSize1?` (${c("printModal.staggerTotal","total: {{minutes}} min",{minutes:z})})`:""]})})()]})]}),r.jsx("p",{className:"text-xs text-bambu-gray",children:t.scheduleType==="asap"?"Print will start as soon as the printer is idle.":t.scheduleType==="scheduled"?"Print will start at the scheduled time if the printer is idle. If busy, it will wait until the printer becomes available.":"Print will be staged but won't start automatically. Use the Start button to release it to the queue."})]})}const Wc={bed_levelling:!0,flow_cali:!1,vibration_cali:!0,layer_inspect:!1,timelapse:!1},c3={scheduleType:"asap",scheduledTime:"",requirePreviousSuccess:!1,autoOffAfter:!1,gcodeInjection:!1,staggerEnabled:!1,staggerGroupSize:2,staggerIntervalMinutes:5};function yc({mode:t,archiveId:e,libraryFileId:n,archiveName:a,queueItem:i,initialSelectedPrinterIds:s,onClose:o,onSuccess:l,projectId:c,cleanupLibraryAfterDispatch:d}){const{t:u}=kt(),m=tn(),{showToast:p}=an(),{hasPermission:f}=cr(),b=!!n&&!e,[w,g]=v.useState(()=>t==="edit-queue-item"&&i?.printer_id?[i.printer_id]:s?.length?s:[]),[x,_]=v.useState(()=>t==="edit-queue-item"&&i?.plate_id!=null?new Set([i.plate_id]):new Set),N=x.size===1?[...x][0]:null,[C,P]=v.useState(1),[T,A]=v.useState(()=>t==="edit-queue-item"&&i?{bed_levelling:i.bed_levelling??Wc.bed_levelling,flow_cali:i.flow_cali??Wc.flow_cali,vibration_cali:i.vibration_cali??Wc.vibration_cali,layer_inspect:i.layer_inspect??Wc.layer_inspect,timelapse:i.timelapse??Wc.timelapse}:Wc),[F,S]=v.useState(()=>{if(t==="edit-queue-item"&&i){let _t="asap";i.manual_start?_t="manual":i.scheduled_time&&!IK(i.scheduled_time)&&(_t="scheduled");let Ft="";if(i.scheduled_time&&!IK(i.scheduled_time)){const Re=Xn(i.scheduled_time)??new Date;Ft=KF(Re)}return{scheduleType:_t,scheduledTime:Ft,requirePreviousSuccess:i.require_previous_success,autoOffAfter:i.auto_off_after,gcodeInjection:i.gcode_injection??!1,staggerEnabled:!1,staggerGroupSize:c3.staggerGroupSize,staggerIntervalMinutes:c3.staggerIntervalMinutes}}return c3}),[M,z]=v.useState(()=>{if(t==="edit-queue-item"&&i?.ams_mapping&&Array.isArray(i.ams_mapping)){const _t={};return i.ams_mapping.forEach((Ft,Re)=>{Ft!==-1&&(_t[Re+1]=Ft)}),_t}return{}}),[I,H]=v.useState({}),[L,Z]=v.useState(()=>t==="edit-queue-item"&&i?.target_model?"model":"printer"),[re,J]=v.useState(()=>t==="edit-queue-item"&&i?.target_model?i.target_model:null),[de,me]=v.useState(()=>t==="edit-queue-item"&&i?.target_location?i.target_location:null),[ue,W]=v.useState(()=>{if(t==="edit-queue-item"&&i?.filament_overrides){const _t={};for(const Ft of i.filament_overrides)_t[Ft.slot_id]={type:Ft.type,color:Ft.color};return _t}return{}}),[ae,pe]=v.useState(()=>{if(t==="edit-queue-item"&&i?.filament_overrides){const _t={};for(const Ft of i.filament_overrides)_t[Ft.slot_id]=Ft.force_color_match===!0;return _t}return{}}),[ye]=v.useState(()=>t==="edit-queue-item"&&i?.printer_id?[i.printer_id]:[]),[Te]=v.useState(()=>t==="edit-queue-item"&&i?i.plate_id:null),[$,K]=v.useState(!1),[D,j]=v.useState({current:0,total:0}),[B,X]=v.useState(null),[O,ie]=v.useState(new Set),U=w.length,G=w.length>0?w[0]:null,{data:Y}=Ke({queryKey:["settings"],queryFn:se.getSettings}),Q=v.useRef(!1);v.useEffect(()=>{!Y||Q.current||t==="edit-queue-item"||(Q.current=!0,A({bed_levelling:Y.default_bed_levelling??Wc.bed_levelling,flow_cali:Y.default_flow_cali??Wc.flow_cali,vibration_cali:Y.default_vibration_cali??Wc.vibration_cali,layer_inspect:Y.default_layer_inspect??Wc.layer_inspect,timelapse:Y.default_timelapse??Wc.timelapse}))},[Y,t]);const oe=v.useRef(!1);v.useEffect(()=>{!Y||oe.current||t==="edit-queue-item"||(oe.current=!0,S(_t=>({..._t,staggerGroupSize:Y.stagger_group_size??_t.staggerGroupSize,staggerIntervalMinutes:Y.stagger_interval_minutes??_t.staggerIntervalMinutes})))},[Y,t]);const ee=Bo(Y?.currency||"USD"),ge=Y?.default_filament_cost??0,{data:ce,isLoading:le}=Ke({queryKey:["printers"],queryFn:se.getPrinters}),{data:q}=Ke({queryKey:["spool-assignments"],queryFn:()=>se.getAssignments(),staleTime:30*1e3,enabled:(t==="reprint"||t==="add-to-queue")&&L==="printer"||b&&t==="reprint"}),{data:R}=Ke({queryKey:["archive",e],queryFn:()=>se.getArchive(e),enabled:!!e&&!b}),{data:ne}=Ke({queryKey:["library-file",n],queryFn:()=>se.getLibraryFile(n),enabled:b&&!!n}),be=R?.sliced_for_model||ne?.sliced_for_model||null,{data:Se,isError:Ne}=Ke({queryKey:["archive-plates",e],queryFn:()=>se.getArchivePlates(e),enabled:!!e&&!b,retry:!1}),{data:ve}=Ke({queryKey:["library-file-plates",n],queryFn:()=>se.getLibraryFilePlates(n),enabled:b&&!!n}),xe=b?ve:Se,{data:Ee,isError:ze}=Ke({queryKey:["archive-filaments",e,N],queryFn:()=>se.getArchiveFilamentRequirements(e,N??void 0),enabled:!!e&&!b&&(N!==null||!xe?.is_multi_plate),retry:!1}),{data:_e}=Ke({queryKey:["library-file-filaments",n,N],queryFn:()=>se.getLibraryFileFilamentRequirements(n,N??void 0),enabled:b&&!!n&&(N!==null||!xe?.is_multi_plate)}),Oe=!b&&(Ne||ze),Ie=b?_e:Ee,Ve=v.useMemo(()=>{if(!(N===null||!xe?.plates?.length))return xe.plates.find(_t=>_t.index===N)?.name||void 0},[xe,N]),{data:rt}=Ke({queryKey:["available-filaments",re,de],queryFn:()=>se.getAvailableFilaments(re,de??void 0),enabled:L==="model"&&!!re}),{data:st}=Ke({queryKey:["printer-status",G],queryFn:()=>se.getPrinterStatus(G),enabled:!!G}),{amsMapping:Le}=Bie(Ie,st,M,Y?.prefer_lowest_filament),tt=f7e(w,ce,Ie,M,I,H,Y?.prefer_lowest_filament);v.useEffect(()=>{xe?.plates&&xe.plates.length>=1&&x.size===0&&_(new Set([xe.plates[0].index]))},[xe,x.size]),v.useEffect(()=>{if(t==="edit-queue-item")return;const _t=ce?.filter(Ft=>Ft.is_active)||[];_t.length===1&&w.length===0&&g([_t[0].id])},[t,ce,w.length]),v.useEffect(()=>{t==="edit-queue-item"?(JSON.stringify(w.sort())!==JSON.stringify(ye.sort())||N!==Te)&&(z({}),H({}),ie(new Set)):(z({}),H({}),ie(new Set))},[t,w,N,ye,Te]);const[Ce,Ze]=v.useState(re),[Ue,fe]=v.useState(N);v.useEffect(()=>{(re!==Ce||N!==Ue)&&(Ze(re),fe(N),(t!=="edit-queue-item"||Ce!==null)&&(W({}),pe({})))},[re,N,Ce,Ue,t]),v.useEffect(()=>{if(!Y?.per_printer_mapping_expanded||w.length<=1)return;const _t=w.filter(Ft=>{if(O.has(Ft))return!1;const Re=tt.printerResults.find(je=>je.printerId===Ft);return Re&&Re.status&&!Re.isLoading});_t.length>0&&(ie(Ft=>{const Re=new Set(Ft);return _t.forEach(je=>Re.add(je)),Re}),_t.forEach(Ft=>{tt.autoConfigurePrinter(Ft)}))},[Y?.per_printer_mapping_expanded,w,O,tt]),v.useEffect(()=>{const _t=Ft=>{Ft.key==="Escape"&&!$&&o()};return window.addEventListener("keydown",_t),()=>window.removeEventListener("keydown",_t)},[o,$]);const Ae=xe?.is_multi_plate??!1,$e=xe?.plates??[],Be=v.useMemo(()=>{const _t=new Map;return q&&q.forEach(Ft=>{const Re=Ft.ams_id===255,je=Qg(Ft.ams_id,Ft.tray_id,Re),Ge=_t.get(Ft.printer_id)??new Map;Ge.set(je,Ft),_t.set(Ft.printer_id,Ge)}),_t},[q]),nt=v.useMemo(()=>{if(!B||B.length===0)return"";const _t=B.map(Ft=>u("printModal.insufficientFilamentLine",{printer:Ft.printerName,slot:Ft.slotLabel,required:Math.round(Ft.requiredGrams),remaining:Math.round(Ft.remainingGrams)}));return[u("printModal.insufficientFilamentMessage"),..._t].join(` `)},[B,u]),ht=at({mutationFn:_t=>se.addToQueue(_t)}),yt=at({mutationFn:_t=>se.updateQueueItem(i.id,_t),onSuccess:()=>{m.invalidateQueries({queryKey:["queue"]}),p("Queue item updated"),l?.(),o()},onError:_t=>{p(_t.message||"Failed to update queue item","error")}}),ot=F.staggerEnabled&&w.length>1,qt=async(_t,Ft)=>{if(_t?.preventDefault(),!Ft?.skipFilamentCheck&&!Y?.disable_filament_warnings&&(t==="reprint"||t==="add-to-queue")&&L==="printer"){const De=[],Je=Ie?.filaments??[];if(Je.length>0&&Be.size>0){const Qe=(We,xt)=>!Number.isFinite(We)||We<=0||!Number.isFinite(xt)||xt<0?null:Math.max(0,We-xt);for(const We of w){const xt=w.length>1?tt.getFinalMapping(We):Le;if(!xt)continue;const et=w.length>1?tt.printerResults.find(Ot=>Ot.printerId===We)?.status:st,Mt=l_(et),wt=new Map(Mt.map(Ot=>[Ot.globalTrayId,Ot.label])),qe=Be.get(We),Lt=ce?.find(Ot=>Ot.id===We)?.name??`Printer ${We}`;qe&&Je.forEach(Ot=>{if(!Ot.slot_id||Ot.slot_id<=0)return;const Xe=xt[Ot.slot_id-1];if(!Number.isFinite(Xe)||Xe<0)return;const Qt=qe.get(Xe)?.spool;if(!Qt)return;const un=Qe(Qt.label_weight,Qt.weight_used);un!==null&&(un>=Ot.used_grams||De.push({printerName:Lt,slotLabel:wt.get(Xe)??`Slot ${Ot.slot_id}`,requiredGrams:Ot.used_grams,remainingGrams:un}))})}}if(De.length>0){X(De);return}}if(L==="printer"&&w.length===0){p("Please select at least one printer","error");return}if(L==="model"&&!re){p("Please select a target printer model","error");return}K(!0);const Re=x.size>1?$e.filter(De=>x.has(De.index)):[null],je=L==="model"?Re.length:w.length*Re.length;j({current:0,total:je});const Ge={success:0,failed:0,errors:[]},Ye=De=>{if(w.length>1){const Je=I[De];if(Je&&!Je.useDefault)return tt.getFinalMapping(De)}return Le},ft=(()=>{const De=[];if(Ie?.filaments)for(const Je of Ie.filaments){const Qe=ue[Je.slot_id],We=ae[Je.slot_id]??!1,xt=Qe?.type??Je.type,et=Qe?.color??Je.color;(Qe||We)&&De.push({slot_id:Je.slot_id,type:xt,color:et,color_name:bc(et),force_color_match:We})}else for(const[Je,{type:Qe,color:We}]of Object.entries(ue)){const xt=parseInt(Je,10),et=ae[xt]??!1;De.push({slot_id:xt,type:Qe,color:We,color_name:bc(We),force_color_match:et})}return De.length>0?De:void 0})(),he=(De,Je)=>({printer_id:L==="printer"?De:null,target_model:L==="model"?re:null,target_location:L==="model"?de:null,filament_overrides:L==="model"?ft:void 0,archive_id:b?void 0:e,library_file_id:b?n:void 0,require_previous_success:F.requirePreviousSuccess,auto_off_after:F.autoOffAfter,gcode_injection:F.gcodeInjection,manual_start:F.scheduleType==="manual",ams_mapping:De?Ye(De):void 0,plate_id:Je!==void 0?Je:N,scheduled_time:F.scheduleType==="scheduled"&&F.scheduledTime?new Date(F.scheduledTime).toISOString():void 0,...T,project_id:c??void 0});if(L==="model"){if(t==="reprint"){p("Model-based assignment only works with queue mode","error"),K(!1);return}let De=0;for(const Je of Re){De++,j({current:De,total:je});const Qe=Je?Je.index:N;try{if(t==="edit-queue-item"&&!Je){const We={printer_id:null,target_model:re,target_location:de,filament_overrides:ft||null,require_previous_success:F.requirePreviousSuccess,auto_off_after:F.autoOffAfter,gcode_injection:F.gcodeInjection,manual_start:F.scheduleType==="manual",ams_mapping:void 0,plate_id:Qe,scheduled_time:F.scheduleType==="scheduled"&&F.scheduledTime?new Date(F.scheduledTime).toISOString():null,...T};await yt.mutateAsync(We)}else{const We=he(null,Qe);Wt>1&&(We.quantity=Wt),await ht.mutateAsync(We)}Ge.success++}catch(We){Ge.failed++;const xt=Je?Je.name||`Plate ${Je.index}`:"";Ge.errors.push(xt?`${xt}: ${We.message}`:We.message)}}}else{const De=F.staggerEnabled&&(t==="add-to-queue"||t==="reprint")&&w.length>1,Je=De?F.scheduleType==="scheduled"&&F.scheduledTime?new Date(F.scheduledTime).getTime():Date.now():0;let Qe=0;for(const We of Re){const xt=We?We.index:N;for(let et=0;et1){const qe=he(Mt,xt);qe.quantity=Wt-1,await ht.mutateAsync(qe)}}else if(t==="edit-queue-item"&&Qe===1){const wt=Ye(Mt),qe={printer_id:Mt,target_model:null,target_location:null,require_previous_success:F.requirePreviousSuccess,auto_off_after:F.autoOffAfter,gcode_injection:F.gcodeInjection,manual_start:F.scheduleType==="manual",ams_mapping:wt,plate_id:xt,scheduled_time:F.scheduleType==="scheduled"&&F.scheduledTime?new Date(F.scheduledTime).toISOString():null,...T};await yt.mutateAsync(qe)}else{const wt=he(Mt,xt);if(Wt>1&&(wt.quantity=Wt),De){const qe=Math.floor(et/F.staggerGroupSize);if(qe>0){const Lt=qe*F.staggerIntervalMinutes*6e4;wt.scheduled_time=new Date(Je+Lt).toISOString()}}await ht.mutateAsync(wt)}Ge.success++}catch(wt){Ge.failed++;const qe=ce?.find(Xe=>Xe.id===Mt)?.name||`Printer ${Mt}`,Lt=We?We.name||`Plate ${We.index}`:"",Ot=Lt?`${qe} (${Lt})`:qe;Ge.errors.push(`${Ot}: ${wt.message}`)}}}}K(!1),Ge.failed===0?(t==="reprint"&&ot?p(u("queue.itemsQueued",{count:Ge.success})):t!=="reprint"&&(t==="edit-queue-item"?p("Queue item updated"):Ge.success===1?p(L==="model"?`Queued for any ${re}`:u("queue.printQueued")):p(u("queue.itemsQueued",{count:Ge.success}))),m.invalidateQueries({queryKey:["queue"]}),l?.(),o()):Ge.success===0?p(`Failed: ${Ge.errors[0]}`,"error"):(p(`${Ge.success} succeeded, ${Ge.failed} failed`,"error"),m.invalidateQueries({queryKey:["queue"]}))},Gt=$||yt.isPending,Jt=v.useMemo(()=>!(Gt||L==="printer"&&w.length===0||L==="model"&&!re||L==="model"&&t==="reprint"||Ae&&x.size===0),[w.length,L,re,t,Ae,x.size,Gt]),Wt=L==="printer"&&w.length>1?1:C,ln=(()=>{const _t=w.length;if(t==="reprint"){const Ft=ot&&_t>1;let Re=Ft?u("printModal.staggerToPrinters",{count:_t,defaultValue:"Stagger to {{count}} printers"}):_t>1?u("queue.printToPrinters",{count:_t}):u("queue.print");return Wt>1&&(Re=`${Re} ×${Wt}`),{title:u(b?"queue.print":"queue.reprint"),icon:mr,submitText:Re,submitIcon:Ft?ya:mr,loadingText:D.total>1?u("queue.sendingProgress",{current:D.current,total:D.total}):u("queue.sending")}}if(t==="add-to-queue"){let Ft=u("queue.addToQueue");return x.size>1?Ft=u("queue.queueSelectedPlates",{count:x.size}):_t>1&&(Ft=u("queue.queueToPrinters",{count:_t})),Wt>1&&(Ft=`${Ft} ×${Wt}`),{title:u("queue.schedulePrint"),icon:ya,submitText:Ft,submitIcon:ya,loadingText:D.total>1?u("queue.addingProgress",{current:D.current,total:D.total}):u("queue.adding")}}return{title:u("queue.editQueueItem"),icon:ii,submitText:u("common.save"),submitIcon:ii,loadingText:D.total>1?u("queue.savingProgress",{current:D.current,total:D.total}):u("common.saving")}})(),ut=ln.icon,it=ln.submitIcon,vt=G&&x.size<=1&&(b||(Ae?N!==null:!0));return r.jsxs("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:$?void 0:o,children:[r.jsx(Ct,{className:"w-full max-w-2xl max-h-[90vh] overflow-y-auto",onClick:_t=>_t.stopPropagation(),children:r.jsxs(At,{className:t==="reprint"?"":"p-0",children:[r.jsxs("div",{className:`flex items-center justify-between ${t==="reprint"?"mb-4":"p-4 border-b border-bambu-dark-tertiary"}`,children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(ut,{className:"w-5 h-5 text-bambu-green"}),r.jsx("h2",{className:"text-lg font-semibold text-white",children:ln.title})]}),r.jsx(Me,{variant:"ghost",size:"sm",onClick:o,disabled:$,children:r.jsx(Ht,{className:"w-5 h-5"})})]}),r.jsxs("form",{onSubmit:qt,className:t==="reprint"?"":"p-4 space-y-4",children:[r.jsx("p",{className:`text-sm text-bambu-gray ${t==="reprint"?"mb-4":""}`,children:t==="reprint"?r.jsxs(r.Fragment,{children:["Send ",r.jsx("span",{className:"text-white",children:a})," to"," ",s?.length===1&&ce?r.jsx("span",{className:"text-white",children:ce.find(_t=>_t.id===s[0])?.name??"printer(s)"}):"printer(s)"]}):r.jsxs(r.Fragment,{children:[r.jsx("span",{className:"block text-bambu-gray mb-1",children:"Print Job"}),r.jsx("span",{className:"text-white font-medium truncate block",children:a})]})}),r.jsx(y7e,{plates:$e,isMultiPlate:Ae,selectedPlates:x,onToggle:_t=>{_(Ft=>{const Re=new Set(Ft);return t==="add-to-queue"?Re.has(_t)?Re.delete(_t):Re.add(_t):(Re.clear(),Re.add(_t)),Re})},onSelectAll:t==="add-to-queue"?()=>_(new Set($e.map(_t=>_t.index))):void 0,onDeselectAll:t==="add-to-queue"?()=>_(new Set):void 0,multiSelect:t==="add-to-queue"}),!s?.length&&r.jsx(S7e,{printers:ce||[],selectedPrinterIds:w,onMultiSelect:g,isLoading:le,allowMultiple:!0,showInactive:t==="edit-queue-item",disableBusy:t==="reprint",printerMappingResults:tt.printerResults,filamentReqs:Ie,onAutoConfigurePrinter:tt.autoConfigurePrinter,onUpdatePrinterConfig:tt.updatePrinterConfig,assignmentMode:t==="reprint"?"printer":L,onAssignmentModeChange:t!=="reprint"?Z:void 0,targetModel:re,onTargetModelChange:t!=="reprint"?J:void 0,targetLocation:de,onTargetLocationChange:t!=="reprint"?me:void 0,slicedForModel:be}),L==="model"&&re&&Ie&&rt&&rt.length>0&&r.jsx(x7e,{filamentReqs:Ie,availableFilaments:rt,overrides:ue,onChange:W,forceColorMatch:ae,onForceColorMatchChange:(_t,Ft)=>pe(Re=>({...Re,[_t]:Ft}))}),be&&L==="printer"&&w.length===1&&(()=>{const _t=ce?.find(Ft=>Ft.id===w[0]);return _t&&_t.model&&be!==_t.model?r.jsxs("div",{className:"p-3 mb-2 bg-yellow-500/10 border border-yellow-500/30 rounded-lg flex items-center gap-2",children:[r.jsx(Sn,{className:"w-4 h-4 text-yellow-400 flex-shrink-0"}),r.jsxs("span",{className:"text-sm text-yellow-400",children:["File was sliced for ",be,", but printing on ",_t.model]})]}):null})(),Oe&&r.jsxs("div",{className:"flex items-start gap-2 p-3 mb-2 bg-orange-500/10 border border-orange-500/30 rounded-lg text-sm",children:[r.jsx(Ha,{className:"w-4 h-4 text-orange-400 mt-0.5 flex-shrink-0"}),r.jsx("p",{className:"text-orange-400",children:"Archive data unavailable. The source file may have been deleted. Filament mapping is disabled."})]}),vt&&!Oe&&w.length===1&&r.jsx(b7e,{printerId:G,filamentReqs:Ie,manualMappings:M,onManualMappingChange:z,defaultExpanded:!!s?.length||(Y?.per_printer_mapping_expanded??!1),currencySymbol:ee,defaultCostPerKg:ge}),(t==="reprint"||U>0||L==="model"&&re)&&r.jsx(k7e,{options:T,onChange:A,defaultExpanded:!!s?.length}),t!=="edit-queue-item"&&(L==="model"||w.length<=1)&&r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("label",{htmlFor:"printQuantity",className:"text-sm text-bambu-gray whitespace-nowrap",children:u("queue.quantity","Quantity")}),r.jsx("input",{id:"printQuantity",type:"number",min:1,max:999,value:C,onChange:_t=>P(Math.max(1,Math.min(999,parseInt(_t.target.value)||1))),className:"w-20 px-2 py-1 text-sm bg-bambu-dark border border-bambu-dark-tertiary rounded text-white focus:outline-none focus:ring-1 focus:ring-bambu-green"}),C>1&&r.jsx("span",{className:"text-xs text-bambu-gray",children:u("queue.quantityHint","Creates {{count}} queue items",{count:C})})]}),t==="reprint"&&L==="printer"&&w.length>1&&r.jsxs("div",{className:"space-y-2 pb-2",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("input",{type:"checkbox",id:"staggerEnabledReprint",checked:F.staggerEnabled,onChange:_t=>S({...F,staggerEnabled:_t.target.checked}),className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),r.jsxs("label",{htmlFor:"staggerEnabledReprint",className:"text-sm flex items-center gap-1 text-bambu-gray",children:[r.jsx(da,{className:"w-3.5 h-3.5"}),u("printModal.staggerPrinterStarts","Stagger printer starts")]})]}),F.staggerEnabled&&(()=>{const _t=F.staggerGroupSize,Ft=F.staggerIntervalMinutes,Re=Math.ceil(w.length/_t),je=(Re-1)*Ft;return r.jsxs("p",{className:"ml-6 text-xs text-bambu-gray",children:[u("printModal.staggerPreview","{{printers}} printers → {{groups}} groups of {{size}}, starting every {{interval}} min",{printers:w.length,groups:Re,size:_t,interval:Ft}),Re>1?` (${u("printModal.staggerTotal","total: {{minutes}} min",{minutes:je})})`:""]})})()]}),t!=="reprint"&&r.jsx(N7e,{options:F,onChange:S,dateFormat:Y?.date_format||"system",timeFormat:Y?.time_format||"system",canControlPrinter:f("printers:control"),showStagger:t==="add-to-queue"&&L==="printer"&&w.length>1,printerCount:w.length,hasGcodeSnippets:!!Y?.gcode_snippets}),t==="reprint"&&!!Y?.gcode_snippets&&Wt>1&&r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("input",{type:"checkbox",id:"gcodeInjectionReprint",checked:F.gcodeInjection,onChange:_t=>S({...F,gcodeInjection:_t.target.checked}),className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),r.jsxs("label",{htmlFor:"gcodeInjectionReprint",className:"text-sm flex items-center gap-1 text-bambu-gray",children:[r.jsx(qy,{className:"w-3.5 h-3.5"}),u("printModal.gcodeInjection","Inject auto-print G-code")]})]}),yt.isError&&r.jsx("div",{className:"mb-4 p-3 bg-red-500/20 border border-red-500/50 rounded-lg text-sm text-red-400",children:yt.error?.message||"Failed to complete operation"}),r.jsxs("div",{className:`flex gap-3 ${t==="reprint"?"":"pt-2"}`,children:[r.jsx(Me,{type:"button",variant:"secondary",onClick:o,className:"flex-1",disabled:$,children:"Cancel"}),r.jsx(Me,{type:"submit",disabled:!Jt,className:"flex-1",children:Gt?r.jsxs(r.Fragment,{children:[r.jsx(mt,{className:"w-4 h-4 animate-spin"}),ln.loadingText]}):r.jsxs(r.Fragment,{children:[r.jsx(it,{className:"w-4 h-4"}),ln.submitText]})})]})]})]})}),B&&B.length>0&&r.jsx(vn,{title:u("printModal.insufficientFilamentTitle"),message:nt,confirmText:u("printModal.printAnyway"),cancelText:u("common.cancel"),variant:"warning",onConfirm:()=>{X(null),qt(void 0,{skipFilamentCheck:!0})},onCancel:()=>X(null)})]})}function UK({value:t}){const{t:e}=kt(),[n,a]=v.useState(!1),i=async()=>{try{if(navigator.clipboard&&window.isSecureContext)await navigator.clipboard.writeText(t);else{const s=document.createElement("textarea");s.value=t,s.style.position="fixed",s.style.opacity="0",document.body.appendChild(s);try{if(s.select(),!document.execCommand("copy"))return}finally{document.body.removeChild(s)}}a(!0),setTimeout(()=>a(!1),2e3)}catch{}};return r.jsx("button",{onClick:i,className:"ml-2 p-1 rounded hover:bg-bambu-dark-tertiary text-bambu-gray hover:text-white transition-colors",title:e(n?"printers.copied":"printers.copyToClipboard"),children:n?r.jsx(_r,{className:"w-3.5 h-3.5 text-bambu-green"}):r.jsx(Ai,{className:"w-3.5 h-3.5"})})}function C7e({printer:t,status:e,totalPrintHours:n,onClose:a}){const{t:i}=kt();v.useEffect(()=>{const o=l=>{l.key==="Escape"&&a()};return window.addEventListener("keydown",o),()=>window.removeEventListener("keydown",o)},[a]);const s=[];if(s.push({label:i("printers.model"),value:t.model??"—"}),s.push({label:i("common.status"),value:r.jsxs("span",{className:`inline-flex items-center gap-1.5 px-2 py-0.5 rounded-full text-xs font-medium ${e?.connected?"bg-bambu-green/20 text-bambu-green":"bg-red-500/20 text-red-400"}`,children:[r.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${e?.connected?"bg-bambu-green":"bg-red-400"}`}),e?.connected?i("printers.status.available"):i("printers.status.offline")]})}),e?.state){const o={IDLE:"printers.status.idle",RUNNING:"printers.status.printing",PAUSE:"printers.status.paused",FINISH:"printers.status.finished",FAILED:"printers.status.error"};s.push({label:i("printers.state"),value:i(o[e.state]??"printers.status.unknown")})}if(s.push({label:i("printers.ipAddress"),value:r.jsxs("span",{className:"flex items-center",children:[r.jsx("span",{className:"font-mono",children:t.ip_address}),r.jsx(UK,{value:t.ip_address})]})}),s.push({label:i("printers.serialNumber"),value:r.jsxs("span",{className:"flex items-center",children:[r.jsx("span",{className:"font-mono truncate",children:t.serial_number}),r.jsx(UK,{value:t.serial_number})]})}),e?.wired_network)s.push({label:i("printers.networkLabel","Network"),value:r.jsxs("span",{className:"flex items-center gap-2",children:[r.jsx(mO,{className:"w-4 h-4 text-bambu-green"}),r.jsx("span",{className:"text-bambu-green",children:i("printers.connection.ethernet","Ethernet")})]})});else if(e?.wifi_signal!=null){const o=See(e.wifi_signal);s.push({label:i("printers.wifiSignalLabel"),value:r.jsxs("span",{className:"flex items-center gap-2",children:[r.jsx(FZ,{className:`w-4 h-4 ${o.color}`}),r.jsx("span",{className:o.color,children:i(o.labelKey)}),r.jsxs("span",{className:"text-bambu-gray text-xs",children:["(",e.wifi_signal," dBm)"]})]})})}return s.push({label:i("printers.firmware"),value:e?.firmware_version??"—"}),e?.developer_mode!=null&&s.push({label:i("printers.developerMode"),value:r.jsx("span",{className:`inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium ${e.developer_mode?"bg-bambu-green/20 text-bambu-green":"bg-bambu-dark-tertiary text-bambu-gray"}`,children:e.developer_mode?i("printers.enabled"):i("printers.disabled")})}),s.push({label:i("printers.nozzleCount"),value:t.nozzle_count}),s.push({label:i("printers.autoArchive"),value:r.jsx("span",{className:`inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium ${t.auto_archive?"bg-bambu-green/20 text-bambu-green":"bg-bambu-dark-tertiary text-bambu-gray"}`,children:t.auto_archive?i("printers.enabled"):i("printers.disabled")})}),n!=null&&n>0&&s.push({label:i("printers.totalPrintHours"),value:`${Math.round(n)}h`}),t.location&&s.push({label:i("printers.sort.location"),value:t.location}),s.push({label:i("printers.addedOn"),value:Rg(t.created_at)}),r.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",role:"dialog","aria-modal":"true",onClick:a,children:r.jsx(Ct,{className:"w-full max-w-md",onClick:o=>o.stopPropagation(),children:r.jsxs(At,{children:[r.jsxs("div",{className:"flex items-center justify-between mb-4",children:[r.jsx("h2",{className:"text-lg font-semibold text-white",children:t.name}),r.jsx("button",{onClick:a,className:"p-1 hover:bg-bambu-dark rounded flex-shrink-0",children:r.jsx(Ht,{className:"w-5 h-5 text-bambu-gray"})})]}),r.jsx("div",{className:"flex justify-center mb-4",children:r.jsx("img",{src:wee(t.model),alt:t.model??t.name,className:"h-24 object-contain"})}),r.jsx("div",{className:"space-y-0",children:s.map((o,l)=>r.jsxs("div",{className:"flex items-center justify-between gap-4 py-2.5 border-b border-bambu-dark-tertiary last:border-0",children:[r.jsx("span",{className:"text-sm text-bambu-gray whitespace-nowrap",children:o.label}),r.jsx("span",{className:"text-sm text-white text-right",children:o.value})]},l))})]})})})}function P7e(t){if(!t||t.length<6)return!1;const e=parseInt(t.slice(0,2),16),n=parseInt(t.slice(2,4),16),a=parseInt(t.slice(4,6),16);return(.299*e+.587*n+.114*a)/255>.6}function d3({trayColor:t,trayType:e,isEmpty:n,slotNumber:a}){return r.jsx("div",{className:"w-3.5 h-3.5 rounded-full mx-auto mb-0.5 border-2 flex items-center justify-center",style:{backgroundColor:t?`#${t}`:e?"#333":"transparent",borderColor:n?"#666":"rgba(255,255,255,0.1)",borderStyle:n?"dashed":"solid"},children:r.jsx("span",{className:"text-[6px] font-bold leading-none select-none",style:{color:t&&P7e(t)?"#000":"#fff"},children:a})})}function i5({summary:t,children:e,defaultOpen:n=!1,className:a="",summaryClassName:i="",open:s,onToggle:o}){const[l,c]=v.useState(n),d=s!==void 0,u=d?s:l,m=()=>{const p=!u;d||c(p),o?.(p)};return r.jsxs("div",{className:a,children:[r.jsxs("div",{role:"button",tabIndex:0,onClick:m,onKeyDown:p=>{(p.key==="Enter"||p.key===" ")&&(p.preventDefault(),m())},className:`w-full flex items-center justify-between gap-2 text-left cursor-pointer ${i}`,"aria-expanded":u,children:[r.jsx("div",{className:"flex-1 min-w-0",children:t}),r.jsx(Rn,{className:`w-4 h-4 text-bambu-gray flex-shrink-0 transition-transform ${u?"rotate-180":""}`})]}),u&&r.jsx("div",{className:"mt-3",children:e})]})}function u3(t){return(t??.02).toFixed(3)}function BK({side:t}){const{mode:e}=db(),n=e==="dark"?"#1a4d2e":"#e7f5e9";return r.jsx("span",{className:"inline-flex items-center justify-center w-4 h-4 text-[10px] font-bold rounded",style:{backgroundColor:n,color:"#00ae42"},children:t})}function qie(t,e){if(!t)return"";if(t.includes("hardened"))return e("printers.nozzleHardenedSteel");if(t.includes("stainless"))return e("printers.nozzleStainlessSteel");if(t.includes("tungsten"))return e("printers.nozzleTungstenCarbide");if(t.length>=4){const n=t.slice(2,4);if(n==="00")return e("printers.nozzleStainlessSteel");if(n==="01")return e("printers.nozzleHardenedSteel");if(n==="05")return e("printers.nozzleTungstenCarbide")}return t==="00"?e("printers.nozzleStainlessSteel"):t==="01"?e("printers.nozzleHardenedSteel"):t==="05"?e("printers.nozzleTungstenCarbide"):t.startsWith("H")?e("printers.nozzleHardenedSteel"):t}function $ie(t,e){return t?t.startsWith("HH")?e("printers.nozzleHighFlow"):t.startsWith("HS")?e("printers.nozzleStandardFlow"):"":""}function Vie({slot:t,index:e,activeStatus:n,filamentName:a,children:i}){const{t:s}=kt(),[o,l]=v.useState(!1),[c,d]=v.useState("top"),u=v.useRef(null),m=v.useRef(null),p=v.useRef(null),f=!t.nozzle_diameter&&!t.nozzle_type,b=t.stat===1;v.useEffect(()=>{if(o&&u.current&&m.current){const C=u.current.getBoundingClientRect(),P=m.current.offsetHeight,A=C.top-56,F=window.innerHeight-C.bottom;AA?d("bottom"):d("top")}},[o]);const w=()=>{p.current&&clearTimeout(p.current),p.current=setTimeout(()=>l(!0),80)},g=()=>{p.current&&clearTimeout(p.current),p.current=setTimeout(()=>l(!1),100)};v.useEffect(()=>()=>{p.current&&clearTimeout(p.current)},[]);const x=_O(t.filament_color),_=qie(t.nozzle_type,s),N=$ie(t.nozzle_type,s);return r.jsxs("div",{ref:u,className:"relative",onMouseEnter:w,onMouseLeave:g,children:[i,o&&r.jsxs("div",{ref:m,className:` absolute left-1/2 -translate-x-1/2 z-50 ${c==="top"?"bottom-full mb-2":"top-full mt-2"} diff --git a/static/index.html b/static/index.html index aff20538f..81a432afc 100644 --- a/static/index.html +++ b/static/index.html @@ -26,7 +26,7 @@ - +