diff --git a/CHANGELOG.md b/CHANGELOG.md index 8f716a903..e1d48159e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,7 +4,12 @@ All notable changes to Bambuddy will be documented in this file. ## [0.2.5b1] - Unreleased +### Added +- **Currency: Belize Dollars (BZD) added to the Settings → Cost currency dropdown (#1454, requested by @PLGuerraDesigns)** — Reporter accurately tracks 3D-printing filament costs in his local currency and BZD wasn't selectable, forcing a manual 2:1 mental conversion from USD. Added `BZD: 'BZ$'` to `frontend/src/utils/currency.ts` next to MXN (Americas dollar-prefix grouping); `getCurrencySymbol('BZD')` returns `'BZ$'` and the SUPPORTED_CURRENCIES list now has 30 entries. Unit test added in `frontend/src/__tests__/utils/currency.test.ts` covering the symbol lookup and presence in SUPPORTED_CURRENCIES; entry-count assertion bumped to 30 so any future additions/removals are caught immediately. 14 currency tests green; frontend build clean. + ### Fixed +- **Scheduler: queue items with `force_color_match` filament overrides now produce a correct AMS mapping at dispatch (#1437, fixed by external PR #1440 from @Person2099)** — Contributor's own bug report and fix. He had a queue item with `filament_overrides: [{slot_id: 1, type: "PLA", color: "#CBC6B8", force_color_match: true}]` and `ams_mapping: null`, expecting Bambuddy to translate the override into a slot mapping at dispatch time. Instead the scheduler dispatched with `ams_mapping: null` and the P1S fell back to type-only AMS matching, picking the wrong-colour slot. **Two-layer root cause** he traced end-to-end. **(1) `backend/app/services/filament_requirements.py:69`**: `extract_filament_requirements(file_path, plate_id=None)` fell through to `_collect_filaments(root, filaments)` whose XPath `./filament` only matches direct children of ``. Modern BambuStudio 3MFs wrap filaments inside `` elements, so this XPath returned `[]` on every modern multi-plate 3MF when no specific plate was targeted — which is the standard scheduler call shape for queue items without a pinned plate. The downstream "no AMS mapping" cascade ALL flowed from this empty filament_reqs result. Fix walks `` elements first, dedupes by `slot_id` (highest `used_grams` wins on ties — sane because BambuStudio slots are project-wide and the entry that extruded the most is the most representative for AMS planning), and preserves the old `./filament` XPath as a fallback when no `` elements are present, so legacy 3MFs continue to parse unchanged. **(2) `backend/app/services/print_scheduler.py:792` — defence in depth**: even with (1) in place, edge cases exist where `_get_filament_requirements` can still return None (3MF missing `slice_info.config` entirely, IO failure during ZIP extraction, etc). New `_build_override_direct_mapping(force_overrides, status)` helper kicks in at exactly that moment when `force_color_match` overrides are present — builds the requirement list directly from the overrides (`slot_id`, `type`, `color`, empty `tray_info_idx`) and delegates to the existing `_match_filaments_to_slots()` cascade against the printer's loaded AMS state. Wrong-colour slot credit via the cascade's type-only fallback is impossible-by-construction because the upstream `_get_missing_force_color_slots()` printer-eligibility gate at `:590` already requires an exact `(type, normalised colour)` pair to be loaded *before* the printer is even considered for the job, so by the time `_build_override_direct_mapping` runs the exact match is guaranteed in the loaded set and the cascade's `exact_match` branch wins (colour normalisation is identical on both sides — `tray_color.replace("#", "").lower()[:6]`). Pref-only overrides (without `force_color_match`) intentionally do NOT trigger the fallback — they keep the pre-PR "no mapping, printer picks defaults" behaviour, so the new fallback is strictly opt-in via `force_color_match: true`. **Backwards-compat triple-checked**: legacy 3MF format unchanged (preserved fallback path); `plate_id != None` branch untouched (entire fix is inside the `else` of `if plate_id is not None`); `filament_overrides=None` / `[]` / no-force-entries all preserve the existing `return None` path; malformed JSON in `filament_overrides` is caught by the existing try/except, logged, and still returns None. **Tests** (22 new across two files; all pass on `pytest -n 30`): `backend/tests/unit/services/test_filament_requirements.py` — 4 tests covering the `plate_id=None` modern-format path, multi-plate collection, slot-dedup-by-highest-grams, and single-plate-modern-format. `backend/tests/unit/test_scheduler_force_color_ams_fallback.py` — 18 tests across `TestBuildOverrideDirectMapping` (single override matches AMS slot, empty AMS returns None, no colour match still produces a mapping length, multi-override produces multi-element mapping, external spool match yields global_tray_id 254, `tray_info_idx` is cleared) and `TestComputeAmsMappingFallback` (fallback used when reqs empty + force overrides present, fallback NOT used when no force_color flag, fallback NOT used when overrides None, normal path still used when reqs available, printer-status-unavailable returns None gracefully). 5079 backend tests + ruff + frontend build all clean post-merge; #1457/#1459/#1440 verified non-interacting (different services, different code paths, different timings). External-PR-checklist (per [[feedback_pr_changelog_required]]): contributor doesn't add CHANGELOG, this entry added by Martin post-merge. + - **Spoolman: per-print weight reporting now works for tag-less spools assigned via the Bambuddy UI (#1459, reported by @Moskito99 — follow-up to #1119)** — Reporter on Postgres + Postgres-backed Spoolman noticed that prints finished cleanly but the spool's remaining weight in Spoolman was never decremented. He correctly traced it: Spoolman's `extra.tag` on his spool was empty, and writing a value in there by hand made weight tracking start working. **Root cause** is one missing fallback path. After #1119 introduced the local `spoolman_slot_assignments` table as the authoritative binding for tag-less spools (RFID is the binding for Bambu Lab spools, slot-assignment is the binding for generic / non-RFID spools), the Assign UI deliberately leaves Spoolman's `extra.tag` field empty for those spools — and after the #1457 cleanup we now actively *clear* it on re-binding to stop ghost links resurfacing in the hover card. That's the correct write-side behaviour. But the per-print weight tracker (`backend/app/services/spoolman_tracking.py:_report_spool_usage_for_slots`) only resolved the bound spool via `client.find_spool_by_tag(spool_tag)` — a single tag-lookup against Spoolman's `extra.tag`. For tag-less spools that returns None and the tracker silently skipped the slot. The tracker **never consulted the local `spoolman_slot_assignments` table** that has the answer (verified: `grep -n SpoolmanSlotAssignment backend/app/services/spoolman_tracking.py` returned zero hits before this fix). So Bambu Lab RFID users got correct weight reporting (their `extra.tag` is auto-populated by the AMS-sync `create_spool` path at `backend/app/services/spoolman.py:1076`), and generic-spool users on Spoolman saw weight tracking silently no-op — exactly the symptom Moskito99 saw. **Fix** adds a two-stage resolver inside `_report_spool_usage_for_slots`: stage 1 is the existing `client.find_spool_by_tag(spool_tag)` (RFID and any RFID-equivalent `extra.tag` value), stage 2 is the new `_resolve_spool_id_via_slot_assignment(printer_id, ams_id, tray_id)` helper that queries the `SpoolmanSlotAssignment` table for `(printer_id, ams_id, tray_id) → spoolman_spool_id`. The (ams_id, tray_id) pair is derived from the slot's global_tray_id via the existing `_global_tray_id_to_ams_slot` helper — same translation used for fallback-tag generation, so external slots (global 254/255 → ams_id=255, tray_id=0/1) and AMS-HT slots (global 128+ → ams_id=global, tray_id=0) all resolve correctly. Stage-1-wins ordering is deliberate: when an RFID-bound spool is in the slot, `extra.tag` is the authoritative binding, even if the slot-assignment table happens to point at a different spool (legacy state). The resulting `[SPOOLMAN] … via tag` vs `… via slot-assignment` suffix in the success log makes it obvious which path resolved each slot, which support bundles will use to confirm the fix is live. `printer_id` threaded through the three callers (`_report_partial_usage` G-code path, `_report_partial_usage` linear path, `report_usage`) — they all already had `printer_id` in scope. Crucially, **`extra.tag` is NOT auto-populated** by this fix — that would re-introduce exactly the pollution #1457 cleaned up (deterministic fallback tags surviving across spool changes and surfacing stale spools in the hover card). The slot-assignment table is the source of truth for non-RFID bindings; Spoolman's `extra.tag` is reserved for hardware RFID identifiers. **Tests:** 5 new in `backend/tests/integration/test_spoolman_tracking_slot_fallback.py`: the bug repro (tag missing + slot-assignment present → use_spool by the slot-assignment's id); tag-match wins when both present (a regression that flips the resolution order would credit the wrong spool); skip-when-neither (no spool resolution attempted); skip-when-printer_id-not-supplied (legacy call shape stays inert); external-slot translation (global 254 → ams_id=255 tray_id=0 lookup works). New `patch_async_session` fixture routes the tracker's module-level `async_session` to the test engine so the in-test `SpoolmanSlotAssignment` insert is visible to the lookup. **Postgres compatibility:** verified — the lookup uses a plain `select(...where...).scalar_one_or_none()`, no SQLite-only syntax. 642 spoolman/tracking tests + 5 new = 647 green; full backend suite 5065 green; ruff clean. - **Spoolman: AMS hover card and SpoolBuddy fill-bar no longer surface a stale spool after re-assigning a non-RFID slot (#1457, reported by @Menthe11)** — Reporter on a P1S with generic (non-RFID) PLA saw two different spools rendered in the AMS hover card: the top "Spulen-ID / Im Inventar öffnen" link pointed at an almost-empty black PLA spool that had been in the slot weeks earlier, while the bottom "Zugewiesen" block correctly showed the full spool the user had just assigned via Spoolman. **Root cause is two-layered.** For non-RFID slots Bambuddy falls back to a deterministic per-slot tag (`hash(printer_serial) + ams_id + tray_id`, 16 hex chars; see `frontend/src/utils/amsHelpers.ts:176`). When a user runs Link UI on such a slot, that fallback tag is written to the Spoolman spool's `extra.tag` — and the existing Link / Assign routes never cleared it from the previous holder when the user re-bound the slot to a different spool. The frontend's hover-card resolver at `frontend/src/pages/PrintersPage.tsx:3736` (and the matching sites at `:4137` / `:4452` for HT and external slots) then preferred that stale tag-link over the user's explicit slot-assignment: `linkedSpoolId: (trayTag ? linkedSpools?.[trayTag]?.id : undefined) ?? slotAssignmentForFill?.spoolman_spool_id`. So when both layers existed and they disagreed, the *stale* spool won, and FilamentHoverCard's dedupe at line 377 couldn't collapse the two buttons because the IDs didn't match → two "Im Inventar öffnen" buttons pointing at different spools. The SpoolBuddy AMS page had the identical bug shape in two more spots: `getSpoolmanFillForSlot()` (the per-slot fill-percentage resolver, line 138) walked tag-link before slot-assignment, so the fill bar reported the *old* spool's remaining grams instead of the freshly assigned full one; and the slot-action picker's "Linked spool" / "Assigned spool" branches (line 760) showed "Linked spool" whenever a tag-link existed, regardless of whether a (more recent) slot-assignment also existed. **Fix has two parts.** (1) Frontend precedence swap at all five sites: slot-assignment is the user's most explicit, most recent action — it must outrank the tag-link, which is auto-populated and can be silently stale. With the swap, FilamentHoverCard's existing match-dedupe collapses both buttons into one pointing at the correct spool; SpoolBuddy's fill bar reads from the assigned spool's weight first; and SpoolBuddy's slot-action picker drops the stale "Linked spool" line entirely when a slot-assignment exists. (2) Backend hygiene so the stale state is never written in the first place: a new `_clear_stale_tag_links(client, tag, keep_spool_id, log_context)` helper in `backend/app/api/routes/spoolman_inventory.py` enumerates Spoolman spools and PATCHes `extra.tag` to JSON-empty (`'""'`, the same wire shape `unlink_spool` already uses so the read-side `.strip('"')` filter in `get_linked_spools` skips it) on any spool *other than* the one being bound that still claims the same tag. Wired into `POST /spoolman/inventory/slot-assignments` (computes the slot's deterministic fallback tag via the existing `get_fallback_spool_tag_for_slot` helper in `spoolman_tracking.py` — newly promoted to a public symbol that mirrors the frontend's `getFallbackSpoolTag(serial, amsId, trayId)` signature) and `POST /spoolman/spools/{id}/link` (passes the literal `spool_tag` being bound — works for both RFID tags and fallback tags). Both are best-effort: per-spool patch failures and Spoolman enumeration failures are logged and skipped, never raised, so the assign/link path never wedges on a Spoolman hiccup. Existing assign-route tests stay green because their fixtures' Spoolman client mock already had `get_spools` returning `[]` (or now does — fixture updated in `test_spoolman_slot_assignments.py`, `test_spoolman_slot_concurrency.py`, `test_spoolman_slot_assignment_mqtt.py`, and the link-route test fixture in `test_spoolman_api.py`). **Tests** (8 new in `backend/tests/unit/test_spoolman_stale_tag_cleanup.py`): clears one other-spool while keeping the bound spool and unrelated-tag spool intact; case-insensitive match (the helper uppercases both sides because `get_linked_spools` already does); empty-tag short-circuits without enumerating spools; `keep_spool_id` guards against clearing the spool being bound; Spoolman 5xx during enumeration is swallowed and the call returns 0; one per-spool patch failure doesn't abort the rest of the cleanup; the slot-fallback wrapper computes the right tag and clears it; empty serial returns 0 without enumerating. Backend: ruff clean, 581 spoolman tests + 8 new = 589 green. Frontend build clean. diff --git a/frontend/src/__tests__/utils/currency.test.ts b/frontend/src/__tests__/utils/currency.test.ts index f0bc9a060..fbcdee904 100644 --- a/frontend/src/__tests__/utils/currency.test.ts +++ b/frontend/src/__tests__/utils/currency.test.ts @@ -30,6 +30,10 @@ describe('getCurrencySymbol', () => { expect(getCurrencySymbol('UAH')).toBe('₴'); }); + it('returns BZ$ for BZD', () => { + expect(getCurrencySymbol('BZD')).toBe('BZ$'); + }); + it('returns the code itself for unknown currencies', () => { expect(getCurrencySymbol('XYZ')).toBe('XYZ'); }); @@ -49,7 +53,11 @@ describe('SUPPORTED_CURRENCIES', () => { expect(SUPPORTED_CURRENCIES.find((c) => c.code === 'MYR')).toBeDefined(); }); - it('has 28 entries', () => { - expect(SUPPORTED_CURRENCIES).toHaveLength(29); + it('contains BZD', () => { + expect(SUPPORTED_CURRENCIES.find((c) => c.code === 'BZD')).toBeDefined(); + }); + + it('has 30 entries', () => { + expect(SUPPORTED_CURRENCIES).toHaveLength(30); }); }); diff --git a/frontend/src/utils/currency.ts b/frontend/src/utils/currency.ts index ab3d87e38..45d99d60f 100644 --- a/frontend/src/utils/currency.ts +++ b/frontend/src/utils/currency.ts @@ -19,6 +19,7 @@ const CURRENCY_SYMBOLS: Record = { SGD: 'S$', NZD: 'NZ$', MXN: 'MX$', + BZD: 'BZ$', MYR: 'RM', CZK: 'Kč', THB: '฿', diff --git a/static/assets/index-CMHVQrcW.js b/static/assets/index-BIzFPmFB.js similarity index 99% rename from static/assets/index-CMHVQrcW.js rename to static/assets/index-BIzFPmFB.js index 4fb9d7fc2..315bd744c 100644 --- a/static/assets/index-CMHVQrcW.js +++ b/static/assets/index-BIzFPmFB.js @@ -8503,7 +8503,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"?j=`${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"&&(j=l("inventory.assignProfileMismatchMessage",{spoolProfile:T.spoolProfile||l("common.unknown"),trayProfile:T.trayProfile||l("common.unknown"),location:s.location})),r.jsx(wn,{title:l("inventory.assignMismatchTitle"),message:j,confirmText:l("inventory.assignMismatchConfirm"),variant:"warning",overlayZIndex:"z-[110]",isLoading:Y.isPending,onConfirm:J,onCancel:()=>{Y.isPending||(P(!1),k(null),A(null))}})})()]})}function RK(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 m3(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 sw=["PLA","PETG","PCTG","ABS","ASA","TPU","PC","PA","NYLON","PVA","HIPS","PP","PET"];function IK(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 sw)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 sw){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 A7e(t){return!t.startsWith("GF")&&!t.startsWith("P1")}const j7e={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"},OK=[{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"}],zK=[{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 UK(t){const e=t.toLowerCase().trim();return j7e[e]||null}function M7e(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 Xie({isOpen:t,onClose:e,printerId:n,slotInfo:a,nozzleDiameter:i="0.4",printerModel:s,onSuccess:o,fullScreen:l}){const{t:c}=_t(),[d,u]=y.useState(""),[m,p]=y.useState(null),[f,g]=y.useState(""),[w,b]=y.useState(""),[x,S]=y.useState(""),[k,C]=y.useState(!1),[P,T]=y.useState(!1),A=y.useRef(""),{data:F,isLoading:_,isError:M}=Xe({queryKey:["cloudSettings"],queryFn:()=>ae.getCloudSettings(),enabled:t,retry:!1}),{data:H,isLoading:I}=Xe({queryKey:["localPresets"],queryFn:()=>ae.getLocalPresets(),enabled:t}),{data:z,isLoading:L}=Xe({queryKey:["builtinFilaments"],queryFn:()=>ae.getBuiltinFilaments(),enabled:t,staleTime:1/0}),{data:Z,isLoading:ne}=Xe({queryKey:["kprofiles",n,i],queryFn:()=>ae.getKProfiles(n,i),enabled:t&&!!n}),{data:Y}=Xe({queryKey:["colorCatalog"],queryFn:()=>ae.getColorCatalog(),enabled:t,staleTime:1/0}),le=lt({mutationFn:async()=>{if(!d)throw new Error("No filament preset selected");const E=d.startsWith("local_"),B=d.startsWith("builtin_"),W=E?parseInt(d.replace("local_",""),10):null,O=B?d.replace("builtin_",""):null,ie=E?H?.filament.find(Me=>Me.id===W):null,U=B?z?.find(Me=>Me.filament_id===O):null,G=!E&&!B?F?.filament.find(Me=>Me.setting_id===d):null;if(!E&&!B&&!G)throw new Error("Selected preset not found");if(E&&!ie)throw new Error("Selected local preset not found");if(B&&!U)throw new Error("Selected builtin preset not found");const K=E?ie.name:B?U.name:G.name,X=IK(K),se=m?.slot_id??-1,te=f||a.trayColor?.slice(0,6)||"FFFFFF",fe=K.replace(/@.+$/,"").trim();let ce,he;const q=X.material.toUpperCase();if(E){const Me=(sw.includes(q)?q:ie?.filament_type||X.material||"").toUpperCase(),Be={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=Be[Me]||Be[Me.replace(/[-\s]?CF$/,"")]||Be[Me.replace(/\+$/,"")]||Be[Me.split(/[-\s]/)[0]]||"",he=""}else if(B)ce=O,he="";else if(ce=m3(d),he=d,!d.startsWith("GFS"))try{const Me=await ae.getCloudSettingDetail(d);Me.filament_id&&(ce=Me.filament_id)}catch(Me){console.warn("Failed to fetch preset detail for filament_id:",Me)}let R=E&&ie?.nozzle_temp_min?ie.nozzle_temp_min:190,re=E&&ie?.nozzle_temp_max?ie.nozzle_temp_max:230;if(!E||B||!ie?.nozzle_temp_min&&!ie?.nozzle_temp_max){const Me=(E?sw.includes(q)?q:ie?.filament_type||X.material||"":X.material).toUpperCase();Me.includes("PLA")?(R=190,re=230):Me.includes("PETG")?(R=220,re=260):Me.includes("ABS")||Me.includes("ASA")?(R=240,re=280):Me.includes("TPU")?(R=200,re=240):Me==="PCTG"?(R=220,re=260):Me.includes("PC")?(R=260,re=300):(Me.includes("PA")||Me.includes("NYLON"))&&(R=250,re=290)}const be=m?.k_value?parseFloat(m.k_value):0,ye=E?sw.includes(q)?q:ie?.filament_type||X.material||"PLA":X.material||"PLA",_e=await ae.configureAmsSlot(n,a.amsId,a.trayId,{tray_info_idx:ce,tray_type:ye,tray_sub_brands:fe,tray_color:te+"FF",nozzle_temp_min:R,nozzle_temp_max:re,cali_idx:se,nozzle_diameter:i,setting_id:he,kprofile_filament_id:m?.filament_id,kprofile_setting_id:m?.setting_id||void 0,k_value:be}),xe=E?`local_${W}`:B?`builtin_${O}`:d,ge=E?"local":B?"builtin":"cloud";try{await ae.saveSlotPreset(n,a.amsId,a.trayId,xe,fe,ge)}catch(Me){console.warn("Failed to save slot preset mapping:",Me)}return _e},onSuccess:()=>{C(!0),o?.(),setTimeout(()=>{C(!1),e()},1500)}}),ue=lt({mutationFn:async()=>ae.resetAmsSlot(n,a.amsId,a.trayId),onSuccess:()=>{C(!0),o?.(),setTimeout(()=>{C(!1),e()},1500)}}),de=y.useMemo(()=>{const E=x.toLowerCase(),B=[],W=new Set,O=a.savedPresetId,ie=a.trayInfoIdx;if(F?.filament)for(const U of F.filament){W.add(U.setting_id);const K=O===U.setting_id||ie&&(U.setting_id===ie||m3(U.setting_id)===ie);if(!(E&&!U.name.toLowerCase().includes(E))){if(!K&&s){const X=M7e(U.name);if(X&&X.toUpperCase()!==s.toUpperCase())continue}B.push({id:U.setting_id,name:U.name,source:"cloud",isUser:A7e(U.setting_id)})}}if(H?.filament)for(const U of H.filament){const G=`local_${U.id}`;E&&!U.name.toLowerCase().includes(E)||B.push({id:G,name:U.name,source:"local",isUser:!1})}if(z)for(const U of z){if(W.has(U.filament_id))continue;const G=U.filament_id.startsWith("GF")?"GFS"+U.filament_id.slice(2):U.filament_id;W.has(G)||(!E||U.name.toLowerCase().includes(E))&&B.push({id:`builtin_${U.filament_id}`,name:U.name,source:"builtin",isUser:!1})}return B.sort((U,G)=>{const K={cloud:0,local:1,builtin:2};return U.source!==G.source?K[U.source]-K[G.source]:U.isUser&&!G.isUser?-1:!U.isUser&&G.isUser?1:U.name.localeCompare(G.name)})},[F?.filament,H?.filament,z,x,s,a.savedPresetId,a.trayInfoIdx]),Q=y.useMemo(()=>{if(!d)return null;let E=null;if(d.startsWith("local_")){const O=parseInt(d.replace("local_",""),10);E=H?.filament.find(U=>U.id===O)?.name||null}else if(d.startsWith("builtin_")){const O=d.replace("builtin_","");E=z?.find(U=>U.filament_id===O)?.name||null}else F?.filament&&(E=F.filament.find(ie=>ie.setting_id===d)?.name||null);if(!E)return null;let B=E.replace(/@.+$/,"").trim();B.startsWith("# ")&&(B=B.slice(2).trim());const W=IK(B);return{fullName:B,material:W.material,brand:W.brand}},[d,F?.filament,H?.filament,z]),oe=Q?.fullName||"",me=y.useMemo(()=>{if(!Y||!Q)return[];const{fullName:E,brand:B}=Q,W=E.replace(/^(Bambu\s*(Lab)?|eSUN|Polymaker|Overture|Sunlu|Hatchbox)\s*/i,"").trim();return Y.filter(O=>{const ie=(O.material||"").toUpperCase(),U=O.manufacturer.toUpperCase();if(!(ie===W.toUpperCase()||ie.includes(W.toUpperCase())||W.toUpperCase().includes(ie)))return!1;if(B){const K=B.toUpperCase();if(!U.includes(K)&&!K.includes(U))return!1}return!0})},[Y,Q]),pe=y.useMemo(()=>{if(!Z?.profiles||!Q)return[];const{fullName:E,material:B,brand:W}=Q,O=E.toUpperCase(),ie=B.toUpperCase(),U=W.toUpperCase();if(!ie||ie.length<2)return[];const G=Z.profiles.filter(X=>{const se=X.name.toUpperCase();if(U)return!(!se.includes(U)||!se.includes(ie));if(se.includes(O)||se.includes(ie))return!0;const fe={NYLON:["PA","PA-CF","PA6"],PA:["NYLON"]}[ie]||[];for(const ce of fe)if(se.includes(ce))return!0;return!1}),K=new Map;for(const X of G){const se=`${X.name}|${X.k_value}`,te=K.get(se);te?a.extruderId!==void 0&&X.extruder_id===a.extruderId&&te.extruder_id!==a.extruderId&&K.set(se,X):K.set(se,X)}return Array.from(K.values())},[Z?.profiles,Q,a.extruderId]);y.useEffect(()=>{if(t){if(a.savedPresetId)u(a.savedPresetId);else if(a.trayInfoIdx&&F?.filament){let E=F.filament.find(B=>B.setting_id===a.trayInfoIdx);E||(E=F.filament.find(B=>m3(B.setting_id)===a.trayInfoIdx)),E&&u(E.setting_id)}else if(a.trayInfoIdx&&z?.length){const E=a.trayInfoIdx,B=z.find(W=>W.filament_id===E);B&&u(`builtin_${B.filament_id}`)}if(a.trayColor){const E=a.trayColor.slice(0,6);E&&g(E)}}else u(""),p(null),g(""),b(""),S(""),C(!1),A.current=""},[t,a.savedPresetId,a.trayInfoIdx,a.trayColor,F?.filament,z]),y.useEffect(()=>{if(pe.length>0){if(a.caliIdx!=null&&a.caliIdx>0){const E=pe.find(B=>B.slot_id===a.caliIdx);if(E){p(E);return}}p(pe[0])}else p(null)},[d,pe,a.caliIdx]);const we=y.useCallback(E=>{E.key==="Escape"&&e()},[e]);y.useEffect(()=>{if(t)return document.addEventListener("keydown",we),()=>document.removeEventListener("keydown",we)},[t,we]);const $=_&&!M||I||L||ne;if(y.useEffect(()=>{if(!$&&d&&d!==A.current){const E=requestAnimationFrame(()=>{const W=document.querySelector('[class*="fixed inset-0 z-50"]')?.querySelector(`[data-preset-id="${CSS.escape(d)}"]`);W&&(A.current=d,W.scrollIntoView({block:"nearest"}))});return()=>cancelAnimationFrame(E)}},[d,$]),!t)return null;const J=d&&!le.isPending,j=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(pu,{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:RK(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(Vt,{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:[k&&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(yl,{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:RK(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(ft,{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:E=>S(E.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder:text-bambu-gray focus:border-bambu-green focus:outline-none mb-2 shrink-0"}),r.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto space-y-1",children:de.length===0?r.jsx("p",{className:"text-center py-4 text-bambu-gray",children:F?.filament?.length===0&&!H?.filament?.length?c("configureAmsSlot.noPresetsAvailable"):c("configureAmsSlot.noMatchingPresets")}):de.map(E=>r.jsx("button",{"data-preset-id":E.id,onClick:()=>u(E.id),className:`group w-full p-2 rounded-lg border text-left transition-colors ${d===E.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:E.name,children:E.name}),r.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[E.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")}),E.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")}),E.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")})]})]})},E.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"),oe&&r.jsx("span",{className:"ml-2 text-xs text-bambu-blue",children:c("configureAmsSlot.filteringFor",{material:oe})})]}),pe.length>0?r.jsxs("div",{className:"relative",children:[r.jsxs("select",{value:m?.name||"",onChange:E=>{const B=pe.find(W=>W.name===E.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")}),pe.map(E=>r.jsxs("option",{value:E.name,children:[E.name," (K=",E.k_value,")"]},`${E.name}-${E.extruder_id}`))]}),r.jsx(Ln,{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")}),me.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:Q?.fullName})}),r.jsx("div",{className:"flex flex-wrap gap-1.5",children:me.map(E=>r.jsxs("button",{onClick:()=>{const B=E.hex_color.replace("#","").toUpperCase();g(B),b(E.color_name)},className:`h-7 px-2 rounded-md border-2 transition-all flex items-center gap-1.5 ${f===E.hex_color.replace("#","").toUpperCase()?"border-bambu-green scale-105":"border-white/20 hover:border-white/40"}`,title:E.color_name,children:[r.jsx("span",{className:"w-4 h-4 rounded-full border border-black/20 flex-shrink-0",style:{backgroundColor:E.hex_color}}),r.jsx("span",{className:"text-xs text-white/80 whitespace-nowrap",children:E.color_name})]},E.id))})]}),r.jsxs("div",{className:"flex flex-wrap gap-1.5 mb-2",children:[OK.map(E=>r.jsx("button",{onClick:()=>{g(E.hex),b(E.name)},className:`w-7 h-7 rounded-md border-2 transition-all ${f===E.hex?"border-bambu-green scale-110":"border-white/20 hover:border-white/40"}`,style:{backgroundColor:`#${E.hex}`},title:E.name},E.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:zK.map(E=>r.jsx("button",{onClick:()=>{g(E.hex),b(E.name)},className:`w-7 h-7 rounded-md border-2 transition-all ${f===E.hex?"border-bambu-green scale-110":"border-white/20 hover:border-white/40"}`,style:{backgroundColor:`#${E.hex}`},title:E.name},E.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:`#${j}`}}),r.jsx("input",{type:"text",placeholder:c("configureAmsSlot.colorPlaceholder"),value:w,onChange:E=>{const B=E.target.value;b(B);const W=UK(B);if(W)g(W);else{const O=B.replace(/[^0-9A-Fa-f]/g,"").toUpperCase();O.length===6?g(O):O.length===3&&g(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:()=>{g(""),b("")},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:E=>S(E.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder:text-bambu-gray focus:border-bambu-green focus:outline-none mb-2"}),r.jsx("div",{className:"max-h-48 overflow-y-auto space-y-1",children:de.length===0?r.jsx("p",{className:"text-center py-4 text-bambu-gray",children:F?.filament?.length===0&&!H?.filament?.length?c("configureAmsSlot.noPresetsAvailable"):c("configureAmsSlot.noMatchingPresets")}):de.map(E=>r.jsx("button",{"data-preset-id":E.id,onClick:()=>u(E.id),className:`group w-full p-2 rounded-lg border text-left transition-colors ${d===E.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:E.name,children:E.name}),r.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[E.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")}),E.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")}),E.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")})]})]})},E.id))})]})]}),r.jsxs("div",{children:[r.jsxs("label",{className:"block text-sm text-bambu-gray mb-2",children:[c("configureAmsSlot.kProfileLabel"),oe&&r.jsx("span",{className:"ml-2 text-xs text-bambu-blue",children:c("configureAmsSlot.filteringFor",{material:oe})})]}),pe.length>0?r.jsxs("div",{className:"relative",children:[r.jsxs("select",{value:m?.name||"",onChange:E=>{const B=pe.find(W=>W.name===E.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")}),pe.map(E=>r.jsxs("option",{value:E.name,children:[E.name," (K=",E.k_value,")"]},`${E.name}-${E.extruder_id}`))]}),r.jsx(Ln,{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")}),me.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:Q?.fullName})}),r.jsx("div",{className:"flex flex-wrap gap-1.5",children:me.map(E=>r.jsxs("button",{onClick:()=>{const B=E.hex_color.replace("#","").toUpperCase();g(B),b(E.color_name)},className:`h-7 px-2 rounded-md border-2 transition-all flex items-center gap-1.5 ${f===E.hex_color.replace("#","").toUpperCase()?"border-bambu-green scale-105":"border-white/20 hover:border-white/40"}`,title:E.color_name,children:[r.jsx("span",{className:"w-4 h-4 rounded-full border border-black/20 flex-shrink-0",style:{backgroundColor:E.hex_color}}),r.jsx("span",{className:"text-xs text-white/80 whitespace-nowrap",children:E.color_name})]},E.id))})]}),r.jsxs("div",{className:"flex flex-wrap gap-1.5 mb-2",children:[OK.map(E=>r.jsx("button",{onClick:()=>{g(E.hex),b(E.name)},className:`w-7 h-7 rounded-md border-2 transition-all ${f===E.hex?"border-bambu-green scale-110":"border-white/20 hover:border-white/40"}`,style:{backgroundColor:`#${E.hex}`},title:E.name},E.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:zK.map(E=>r.jsx("button",{onClick:()=>{g(E.hex),b(E.name)},className:`w-7 h-7 rounded-md border-2 transition-all ${f===E.hex?"border-bambu-green scale-110":"border-white/20 hover:border-white/40"}`,style:{backgroundColor:`#${E.hex}`},title:E.name},E.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:`#${j}`}}),r.jsx("input",{type:"text",placeholder:c("configureAmsSlot.colorPlaceholder"),value:w,onChange:E=>{const B=E.target.value;b(B);const W=UK(B);if(W)g(W);else{const O=B.replace(/[^0-9A-Fa-f]/g,"").toUpperCase();O.length===6?g(O):O.length===3&&g(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:()=>{g(""),b("")},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(je,{variant:"secondary",onClick:()=>ue.mutate(),disabled:ue.isPending||le.isPending,className:"text-red-400 hover:text-red-300 hover:bg-red-500/10",children:ue.isPending?r.jsxs(r.Fragment,{children:[r.jsx(ft,{className:"w-4 h-4 animate-spin"}),c("configureAmsSlot.resetting")]}):r.jsxs(r.Fragment,{children:[r.jsx(fs,{className:"w-4 h-4"}),c("configureAmsSlot.resetSlot")]})}),r.jsxs("div",{className:"flex gap-2",children:[r.jsx(je,{variant:"secondary",onClick:e,children:c("configureAmsSlot.cancel")}),r.jsx(je,{onClick:()=>le.mutate(),disabled:!J,children:le.isPending?r.jsxs(r.Fragment,{children:[r.jsx(ft,{className:"w-4 h-4 animate-spin"}),c("configureAmsSlot.configuring")]}):r.jsxs(r.Fragment,{children:[r.jsx(pu,{className:"w-4 h-4"}),c("configureAmsSlot.configureSlot")]})})]})]}),(le.isError||ue.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:le.error?.message||ue.error?.message})]})]})}function BK({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 Zie({folderId:t,onClose:e,onUploadComplete:n,onFileUploaded:a,autoUpload:i,validateFile:s,accept:o}){const{t:l}=_t(),[c,d]=y.useState([]),[u,m]=y.useState(!1),[p,f]=y.useState(!1),[g,w]=y.useState(!0),[b,x]=y.useState(!1),[S,k]=y.useState(!0),[C,P]=y.useState(null),T=y.useRef(null),A=de=>{de.preventDefault(),m(!0)},F=de=>{de.preventDefault(),m(!1)},_=de=>{de.preventDefault(),m(!1),z(Array.from(de.dataTransfer.files))},M=de=>{de.target.files&&z(Array.from(de.target.files))},H=(de,Q)=>{d(oe=>oe.map(me=>me.file===de?{...me,...Q}:me))},I=async de=>{f(!0);for(const Q of de)if(Q.status==="pending"){H(Q.file,{status:"uploading"});try{if(Q.isZip){const oe=await ae.extractZipFile(Q.file,t,g,b,S);H(Q.file,{status:oe.errors.length>0&&oe.extracted===0?"error":"success",extractedCount:oe.extracted,error:oe.errors.length>0?l("fileManager.zipFilesFailed","{{count}} files failed",{count:oe.errors.length}):void 0})}else{const oe=await ae.uploadLibraryFile(Q.file,t,S);H(Q.file,{status:"success"});const me=a?.(oe);if(me){P(me),d([]),f(!1);return}}}catch(oe){H(Q.file,{status:"error",error:oe instanceof Error?oe.message:l("fileManager.uploadFailed","Upload failed")})}}f(!1),n(),d(Q=>(Q.some(me=>me.status==="error")||e(),Q))},z=de=>{if(P(null),s)for(const oe of de){const me=s(oe);if(me){P(me);return}}const Q=de.map(oe=>({file:oe,status:"pending",isZip:oe.name.toLowerCase().endsWith(".zip"),is3mf:oe.name.toLowerCase().endsWith(".3mf")}));d(oe=>[...oe,...Q]),i&&de.length>0&&I(Q)},L=de=>{d(Q=>Q.filter((oe,me)=>me!==de))},Z=c.some(de=>de.isZip&&de.status==="pending"),ne=c.some(de=>de.file.name.toLowerCase().endsWith(".stl")&&de.status==="pending"),Y=c.some(de=>de.is3mf&&de.status==="pending"),le=c.filter(de=>de.status==="pending").length,ue=c.length>0&&le===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(Vt,{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:_,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(_a,{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(eo,{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:g,onChange:de=>w(de.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:b,onChange:de=>x(de.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")})]})]})]})}),Y&&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(hr,{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")})]})]})}),(ne||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(mu,{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&&!ne?"fileManager.zipMayContainStl":"fileManager.thumbnailsCanBeGenerated")}),r.jsxs("label",{className:"flex items-center gap-2 mt-2 cursor-pointer",children:[r.jsx("input",{type:"checkbox",checked:S,onChange:de=>k(de.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((de,Q)=>r.jsxs("div",{className:"flex items-center gap-3 p-2 bg-bambu-dark rounded-lg",children:[de.isZip?r.jsx(eo,{className:"w-4 h-4 text-blue-400 flex-shrink-0"}):r.jsx(NT,{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:de.file.name}),r.jsxs("p",{className:"text-xs text-bambu-gray",children:[(de.file.size/1024/1024).toFixed(2)," MB",de.isZip&&de.status==="pending"&&r.jsxs("span",{className:"text-blue-400 ml-2",children:["• ",l("fileManager.willBeExtracted")]}),de.extractedCount!==void 0&&r.jsxs("span",{className:"text-green-400 ml-2",children:["• ",l("fileManager.filesExtracted",{count:de.extractedCount})]})]}),de.status==="error"&&de.error&&r.jsx("p",{className:"text-xs text-red-400 mt-1 break-words",children:de.error})]}),de.status==="pending"&&r.jsx("button",{onClick:()=>L(Q),className:"p-1 hover:bg-bambu-dark-tertiary rounded",children:r.jsx(Vt,{className:"w-4 h-4 text-bambu-gray"})}),de.status==="uploading"&&r.jsx(ft,{className:"w-4 h-4 text-bambu-green animate-spin"}),de.status==="success"&&r.jsx(xr,{className:"w-4 h-4 text-green-500"}),de.status==="error"&&r.jsx("span",{title:de.error,children:r.jsx($r,{className:"w-4 h-4 text-red-500"})})]},Q))}),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($r,{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(je,{variant:"secondary",onClick:e,children:l("common.cancel")}),!ue&&r.jsx(je,{onClick:()=>I(c),disabled:le===0||p,children:p?r.jsxs(r.Fragment,{children:[r.jsx(ft,{className:"w-4 h-4 mr-2 animate-spin"}),l("fileManager.uploading")]}):r.jsxs(r.Fragment,{children:[r.jsx(_a,{className:"w-4 h-4 mr-2"}),l("common.upload")," ",le>0?`(${le})`:""]})})]})]})})}function HK(t){return t?`#${t.replace("#","").substring(0,6)}`:"#808080"}function Ia(t){return t?t.replace("#","").toLowerCase().substring(0,6):""}const E7e=[["PA-CF","PA12-CF","PAHT-CF"]],Jie={};for(const t of E7e){const e=t[0];for(const n of t)Jie[n.toUpperCase()]=e.toUpperCase()}function wP(t){if(!t)return"";const e=t.toUpperCase();return Jie[e]??e}function p3(t,e){return wP(t)===wP(e)}function md(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 u_(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 my(t){return t>50?"#00ae42":t>=15?"#f59e0b":"#ef4444"}function LN(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 qK(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 gm(t,e,n){return`${D7e(t)}${qK(e,4)}${qK(n,4)}`}function $K(t){if(!t)return!1;const e=Date.now()+4320*60*60*1e3;return(Yn(t)?.getTime()??0)>e}function F7e(t,e,n,a){let i=ese(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)&&p3(c.type,t.type)&&Ia(c.color)===Ia(t.color)),o=s?void 0:i.find(c=>!n.has(c.globalTrayId)&&p3(c.type,t.type)&&md(c.color,t.color)),l=s||o?void 0:i.find(c=>!n.has(c.globalTrayId)&&p3(c.type,t.type));return s??o??l}function ese(t,e){return t.filter(n=>e==null||n.extruderId===e)}function Ks(t){return t?!!(t.tray_uuid&&t.tray_uuid!=="00000000000000000000000000000000"||t.tag_uid&&t.tag_uid!=="0000000000000000"):!1}function m_(t){const e=[],n=t?.ams_extruder_map,a=!!t?.nozzles?.[1]?.nozzle_diameter||n&&Object.keys(n).length>0||(t?.vt_tray?.length??0)>1;t?.ams?.forEach(i=>{const s=i.tray.length===1;i.tray.forEach(o=>{if(o.tray_type){const l=HK(o.tray_color);e.push({type:o.tray_type,color:l,colorName:fc(l),amsId:i.id,trayId:o.id,isHt:s,isExternal:!1,label:u_(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=HK(i.tray_color),o=i.id??254,l=(t?.vt_tray?.length??0)>1;e.push({type:i.tray_type,color:s,colorName:fc(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 VK(t,e,n){if(!t?.filaments||t.filaments.length===0)return;const a=m_(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,S)=>{const k=x.remain>=0?x.remain:101,C=S.remain>=0?S.remain:101;return k-C}));let p,f,g,w;if(u){const x=m.filter(S=>S.trayInfoIdx===u);x.length===1?p=x[0]:x.length>1&&(n&&x.sort((S,k)=>{const C=S.remain>=0?S.remain:101,P=k.remain>=0?k.remain:101;return C-P}),f=x.find(S=>S.type?.toUpperCase()===d.type?.toUpperCase()&&Ia(S.color)===Ia(d.color)),f||(g=x.find(S=>S.type?.toUpperCase()===d.type?.toUpperCase()&&md(S.color,d.color))),!f&&!g&&(w=x.find(S=>S.type?.toUpperCase()===d.type?.toUpperCase())))}!p&&!f&&!g&&!w&&(f=m.find(x=>x.type?.toUpperCase()===d.type?.toUpperCase()&&Ia(x.color)===Ia(d.color)),f||(g=m.find(x=>x.type?.toUpperCase()===d.type?.toUpperCase()&&md(x.color,d.color))),!f&&!g&&(w=m.find(x=>x.type?.toUpperCase()===d.type?.toUpperCase())));const b=p||f||g||w||void 0;return b&&s.add(b.globalTrayId),{slot_id:d.slot_id,globalTrayId:b?.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 L7e(t){return y.useMemo(()=>m_(t),[t])}function tse(t,e,n,a){const i=L7e(e),s=e?.fila_switch?.installed===!0,o=y.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],_=i.find(M=>M.globalTrayId===F);if(_){const M=_.type?.toUpperCase()===m.type?.toUpperCase(),H=Ia(_.color)===Ia(m.color)||md(_.color,m.color);let I;return M&&H?I="match":M?I="type_only":I="mismatch",{...m,loaded:_,hasFilament:!0,typeMatch:M,colorMatch:H,status:I,isManual:!0}}}const f=m.tray_info_idx||"";let g=i.filter(F=>!u.has(F.globalTrayId));m.nozzle_id!=null&&!s&&(g=g.filter(F=>F.extruderId===m.nozzle_id)),a&&(g=[...g].sort((F,_)=>{const M=F.remain>=0?F.remain:101,H=_.remain>=0?_.remain:101;return M-H}));let w,b,x,S;if(f){const F=g.filter(_=>_.trayInfoIdx===f);F.length===1?w=F[0]:F.length>1&&(a&&F.sort((_,M)=>{const H=_.remain>=0?_.remain:101,I=M.remain>=0?M.remain:101;return H-I}),b=F.find(_=>_.type?.toUpperCase()===m.type?.toUpperCase()&&Ia(_.color)===Ia(m.color)),b||(x=F.find(_=>_.type?.toUpperCase()===m.type?.toUpperCase()&&md(_.color,m.color))),!b&&!x&&(S=F.find(_=>_.type?.toUpperCase()===m.type?.toUpperCase())))}!w&&!b&&!x&&!S&&(b=g.find(F=>F.type?.toUpperCase()===m.type?.toUpperCase()&&Ia(F.color)===Ia(m.color)),b||(x=g.find(F=>F.type?.toUpperCase()===m.type?.toUpperCase()&&md(F.color,m.color))),!b&&!x&&(S=g.find(F=>F.type?.toUpperCase()===m.type?.toUpperCase())));const k=w||b||x||S||void 0;k&&u.add(k.globalTrayId);const C=!!k,P=C,T=!!w||!!b||!!x;let A;return w||b||x?A="match":S?A="type_only":A="mismatch",{...m,loaded:k,hasFilament:C,typeMatch:P,colorMatch:T,status:A,isManual:!1}})},[t,i,n,a,s]),l=y.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 R7e(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],S=e.find(k=>k.globalTrayId===x);if(S){const k=S.type?.toUpperCase()===u.type?.toUpperCase(),C=Ia(S.color)===Ia(u.color)||md(S.color,u.color);k&&C?i++:k?s++:o++;continue}}let p=e.filter(x=>!l.has(x.globalTrayId));if(u.nozzle_id!=null){const x=p.filter(S=>S.extruderId===u.nozzle_id);x.length>0&&(p=x)}a&&(p=[...p].sort((x,S)=>{const k=x.remain>=0?x.remain:101,C=S.remain>=0?S.remain:101;return k-C}));const f=p.find(x=>x.type?.toUpperCase()===u.type?.toUpperCase()&&Ia(x.color)===Ia(u.color)),g=f?void 0:p.find(x=>x.type?.toUpperCase()===u.type?.toUpperCase()&&md(x.color,u.color)),w=f||g?void 0:p.find(x=>x.type?.toUpperCase()===u.type?.toUpperCase()),b=f??g??w;b&&l.add(b.globalTrayId),f||g?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 I7e(t,e,n,a){if(!t?.filaments||t.filaments.length===0)return;const i=m_(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(b=>!s.has(b.globalTrayId));if(d.nozzle_id!=null){const b=m.filter(x=>x.extruderId===d.nozzle_id);b.length>0&&(m=b)}a&&(m=[...m].sort((b,x)=>{const S=b.remain>=0?b.remain:101,k=x.remain>=0?x.remain:101;return S-k}));const p=m.find(b=>b.type?.toUpperCase()===d.type?.toUpperCase()&&Ia(b.color)===Ia(d.color)),f=p?void 0:m.find(b=>b.type?.toUpperCase()===d.type?.toUpperCase()&&md(b.color,d.color)),g=p||f?void 0:m.find(b=>b.type?.toUpperCase()===d.type?.toUpperCase()),w=p??f??g;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 GK={useDefault:!0,manualMappings:{},autoConfigured:!1};function O7e(t,e,n,a,i,s,o){const l=rf({queries:t.map(w=>({queryKey:["printer-status",w],queryFn:()=>ae.getPrinterStatus(w),enabled:t.length>0,staleTime:5e3}))}),c=y.useMemo(()=>t.map((w,b)=>{const x=l[b],S=x?.data,C=e?.find(H=>H.id===w)?.name||`Printer ${w}`,P=m_(S),T=i[w]||GK,A=VK(n,S,o),F=T.useDefault?a:T.manualMappings,_=I7e(n,S,F,o),M=R7e(n?.filaments,P,F,o);return{printerId:w,printerName:C,status:S,isLoading:x?.isLoading??!1,loadedFilaments:P,autoMapping:A,finalMapping:_,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,b)=>{s(x=>({...x,[w]:{...x[w]||GK,...b}}))},m=w=>{const b=c.find(k=>k.printerId===w);if(!b||!b.status||!n?.filaments)return;const x=VK(n,b.status,o);if(!x)return;const S={};x.forEach((k,C)=>{k!==-1&&(S[C+1]=k)}),u(w,{useDefault:!1,manualMappings:S,autoConfigured:!0})},p=()=>{for(const w of t)m(w)},f=w=>c.find(x=>x.printerId===w)?.finalMapping,g=c.every(w=>w.matchStatus!=="missing");return{printerResults:c,isLoading:d,perPrinterConfigs:i,updatePrinterConfig:u,autoConfigureAll:p,autoConfigurePrinter:m,getFinalMapping:f,allPrintersReady:g}}const nse={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 Ho(t){return nse[t.toUpperCase()]||t}const z7e=Object.entries(nse).map(([t,e])=>({code:t,label:`${t} (${e})`}));function U7e({printerId:t,filamentReqs:e,manualMappings:n,onManualMappingChange:a,currencySymbol:i,defaultCostPerKg:s,defaultExpanded:o=!1}){const{t:l}=_t(),c=tn(),[d,u]=y.useState(!1),[m,p]=y.useState(o),{data:f}=Xe({queryKey:["printer-status",t],queryFn:()=>ae.getPrinterStatus(t),enabled:!!t}),{data:g}=Xe({queryKey:["spool-assignments",t],queryFn:()=>ae.getAssignments(t),enabled:!!t}),{loadedFilaments:w,filamentComparison:b,hasTypeMismatch:x,hasColorMismatch:S}=tse(e,f,n),k=y.useMemo(()=>{const L=new Map;for(const Z of g||[]){const ne=Z.ams_id===255,Y=Qg(Z.ams_id,Z.tray_id,ne);L.set(Y,Z.spool?.cost_per_kg??null)}return L},[g]),C=y.useMemo(()=>{const L=new Map;for(const Z of g||[]){const ne=Z.ams_id===255,Y=Qg(Z.ams_id,Z.tray_id,ne),le=Z.spool;if(!le){L.set(Y,null);continue}L.set(Y,Math.max(0,Math.round((le.label_weight??0)-(le.weight_used??0))))}return L},[g]),P=y.useMemo(()=>{let L=0;for(const Z of b){const ne=Z.loaded?.globalTrayId;if(ne==null)continue;const le=k.get(ne)??null??s;le>0&&(L+=Z.used_grams/1e3*le)}return L},[b,k,s]),T=y.useMemo(()=>Array.from(k.values()).some(L=>L!=null&&L>0),[k]),A=e?.filaments&&e.filaments.length>0,F=e?.filaments?.some(L=>L.nozzle_id!=null)??!1,_=f?.fila_switch?.installed===!0,M=L=>{const Z=f?.fila_switch;if(!Z?.installed)return null;const ne=Z.in_slots.indexOf(L);return ne<0?null:Z.out_extruders[ne]??null};if(!A||!f)return null;const H=x?"#f97316":S?"#facc15":"#00ae42",I=(L,Z)=>{if(L>0)if(Z===""){const ne={...n};delete ne[L],a(ne)}else a({...n,[L]:parseInt(Z,10)})},z=async()=>{u(!0);try{await ae.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(Mw,{className:"w-4 h-4",fill:H,stroke:"none"}),r.jsx("span",{children:l("printModal.filamentMapping")}),x?r.jsx("span",{className:"text-xs text-orange-400",children:"(Type not found)"}):S?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(Zo,{className:"w-4 h-4 ml-auto"}):r.jsx(Ln,{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:z,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(tr,{className:`w-3 h-3 ${d?"animate-spin":""}`}),r.jsx("span",{children:"Re-read"})]})]}),b.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} - ${fc(L.color)}`,children:r.jsx(Mw,{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:ne=>I(L.slot_id||0,ne.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(ne=>L.nozzle_id==null||_||ne.extruderId===L.nozzle_id).map(ne=>{const Y=C.get(ne.globalTrayId),le=Y!=null?l("printModal.slotRemainingShort",{grams:Y,defaultValue:` - ${Y}g left`}):"",ue=_?M(ne.globalTrayId):null,de=ue==null?"":` [${l(ue===1?"printModal.leftNozzle":"printModal.rightNozzle")}]`;return r.jsxs("option",{value:ne.globalTrayId,className:"bg-bambu-dark text-white",children:[ne.label,": ",ne.traySubBrands||ne.type," (",ne.colorName,")",le,de]},ne.globalTrayId)})]}),L.status==="match"?r.jsx(Ar,{className:"w-3 h-3 text-bambu-green"}):L.status==="type_only"?r.jsx("span",{title:"Same type, different color",children:r.jsx(Nn,{className:"w-3 h-3 text-yellow-400"})}):r.jsx("span",{title:"Filament type not loaded",children:r.jsx(Nn,{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 B7e({filamentReqs:t,availableFilaments:e,overrides:n,onChange:a,forceColorMatch:i,onForceColorMatchChange:s}){const{t:o}=_t(),l=y.useMemo(()=>{const u={};for(const m of e){const p=wP(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[wP(u.type)]||[],g=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} - ${fc(u.color)}`,children:r.jsx(Mw,{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:g.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," (",fc(u.color),")"]}),g.map((w,b)=>r.jsxs("option",{value:`${w.type}|${w.color}`,className:"bg-bambu-dark text-white",children:[w.tray_sub_brands||w.type," (",fc(w.color),")"]},`${w.type}-${w.color}-${w.tray_sub_brands}-${b}`))]}),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(fs,{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(ES,{className:"w-3 h-3"}),o("printModal.forceColorMatch")]})]},u.slot_id)})})]})}function H7e({plates:t,isMultiPlate:e,selectedPlates:n,onToggle:a,onSelectAll:i,onDeselectAll:s,multiSelect:o}){const{t:l}=_t();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(ca,{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(Nn,{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(gs,{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:La(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(ca,{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?` • ${cs(d.print_time_seconds)}`:""]})]}),!o&&u&&r.jsx(Ar,{className:"w-4 h-4 text-bambu-green flex-shrink-0"})]},d.index)})})]})}const q7e=new Set(["IDLE","FINISH","FAILED"]);function $7e({printerResult:t,filamentReqs:e,onUpdateConfig:n}){const a=tn(),[i,s]=y.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 ae.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)),b=a.getQueryData(["settings"]);p=F7e(d,t.loadedFilaments,w,b?.prefer_lowest_filament)}let g="mismatch";if(p){const w=p.type?.toUpperCase()===d.type?.toUpperCase(),b=Ia(p.color)===Ia(d.color)||md(p.color,d.color);w&&b?g="match":w&&(g="type_only")}return{req:d,loaded:p,status:g,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(tr,{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} - ${fc(d.color)}`,children:r.jsx(Mw,{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:g=>o(d.slot_id||0,g.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 --"}),ese(t.loadedFilaments,d.nozzle_id).map(g=>r.jsxs("option",{value:g.globalTrayId,className:"bg-bambu-dark text-white",children:[g.label,": ",g.traySubBrands||g.type," (",g.colorName,")"]},g.globalTrayId))]}),m==="match"?r.jsx(Ar,{className:"w-3 h-3 text-bambu-green"}):m==="type_only"?r.jsx("span",{title:"Same type, different color",children:r.jsx(Nn,{className:"w-3 h-3 text-yellow-400"})}):r.jsx("span",{title:"Filament type not loaded",children:r.jsx(Nn,{className:"w-3 h-3 text-orange-400"})})]},f))]})}function V7e({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:g,targetLocation:w,onTargetLocationChange:b,slicedForModel:x}){const[S,k]=y.useState(!1),C=s?t:t.filter(oe=>oe.is_active),P=rf({queries:C.map(oe=>({queryKey:["printerStatus",oe.id],queryFn:()=>ae.getPrinterStatus(oe.id),staleTime:5e3}))}),T=y.useMemo(()=>{const oe=new Map;return C.forEach((me,pe)=>{const we=P[pe];we?.data&&oe.set(me.id,we.data)}),oe},[C,P]),A=oe=>{const me=T.get(oe);return me?me.connected?!q7e.has(me.state??""):!0:!1},F=oe=>{const me=T.get(oe);if(!me)return null;if(!me.connected)return"Offline";const pe=me.state;return pe?pe==="RUNNING"?me.stg_cur_name||"Printing":pe==="PREPARE"?"Preparing":pe==="PAUSE"?"Paused":pe==="IDLE"?"Idle":pe==="FINISH"?"Finished":pe==="FAILED"?"Failed":pe:null},_=y.useMemo(()=>{if(m!=="printer"||!x||S)return C;const oe=C.filter(me=>me.model===x);return oe.length>0?oe:C},[C,m,x,S]),M=C.length-_.length,H=y.useMemo(()=>{const oe=C.map(me=>me.model).filter(me=>!!me);return[...new Set(oe)].sort()},[C]),I=y.useMemo(()=>{if(!f)return[];const oe=C.filter(me=>me.model===f&&me.location).map(me=>me.location).filter(me=>!!me);return[...new Set(oe)].sort()},[C,f]),z=p&&g&&H.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(ft,{className:"w-6 h-6 text-bambu-green animate-spin"})});if(_.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=oe=>{o&&A(oe)||(i?e.includes(oe)?n(e.filter(me=>me!==oe)):n([...e,oe]):n([oe]))},ne=()=>{const oe=o?_.filter(me=>!A(me.id)):_;n(oe.map(me=>me.id))},Y=()=>{n([])},le=(oe,me,pe)=>{pe.stopPropagation(),!(!d||!u)&&(me?d(oe):u(oe,{useDefault:!0,manualMappings:{},autoConfigured:!1}))},ue=oe=>e.includes(oe),de=e.length,Q=oe=>l?.find(me=>me.printerId===oe);return r.jsxs("div",{className:"space-y-2 mb-6",children:[z&&r.jsxs("div",{className:"flex gap-2 mb-4",children:[r.jsxs("button",{type:"button",onClick:()=>{p("printer"),g(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(hr,{className:"w-4 h-4"}),r.jsx("span",{className:"text-sm",children:"Specific Printer"})]}),r.jsxs("button",{type:"button",onClick:()=>{p("model"),n([]);const oe=x&&H.includes(x)?x:H[0];g(oe)},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(bm,{className:"w-4 h-4"}),r.jsxs("span",{className:"text-sm",children:["Any ",x||"Model"]})]})]}),m==="model"&&z&&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:oe=>{g(oe.target.value||null),b&&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 text-sm",children:[r.jsx("option",{value:"",children:"Select a model..."}),H.map(oe=>r.jsx("option",{value:oe,children:oe},oe))]})]}),f&&I.length>0&&b&&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:oe=>b(oe.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(oe=>r.jsx("option",{value:oe,children:oe},oe))]})]}),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&&_.length>1&&r.jsxs("div",{className:"flex items-center justify-between text-xs text-bambu-gray mb-2",children:[r.jsx("span",{children:de===0?"Select printers":`${de} printer${de!==1?"s":""} selected`}),r.jsxs("div",{className:"flex gap-2",children:[de<_.length&&r.jsx("button",{type:"button",onClick:ne,className:"text-bambu-green hover:text-bambu-green/80 transition-colors",children:"Select all"}),de>0&&r.jsx("button",{type:"button",onClick:Y,className:"text-bambu-gray hover:text-white transition-colors",children:"Clear"})]})]}),m==="printer"&&_.map(oe=>{const me=ue(oe.id),pe=Q(oe.id),we=pe&&!pe.config.useDefault,$=A(oe.id),J=o&&$,j=F(oe.id);return r.jsxs("div",{children:[r.jsxs("button",{type:"button",onClick:()=>Z(oe.id),disabled:J,className:`w-full flex items-center gap-3 p-3 rounded-lg border transition-colors ${J?"border-bambu-dark-tertiary bg-bambu-dark opacity-50 cursor-not-allowed":me?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary bg-bambu-dark hover:border-bambu-gray"} ${oe.is_active?"":"opacity-60"}`,children:[r.jsx("div",{className:`p-2 rounded-lg ${J?"bg-bambu-dark-tertiary":me?"bg-bambu-green/20":"bg-bambu-dark-tertiary"}`,children:r.jsx(hr,{className:`w-5 h-5 ${J?"text-bambu-gray/50":me?"text-bambu-green":"text-bambu-gray"}`})}),r.jsxs("div",{className:"text-left flex-1",children:[r.jsxs("p",{className:`font-medium ${J?"text-bambu-gray":"text-white"}`,children:[oe.name,!oe.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:[oe.model||"Unknown model"," • ",oe.ip_address]})]}),j&&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:j}),i&&r.jsx("div",{className:`w-5 h-5 rounded border-2 flex items-center justify-center transition-colors ${J?"border-bambu-gray/30":me?"bg-bambu-green border-bambu-green":"border-bambu-gray/50"}`,children:me&&r.jsx(Ar,{className:"w-3 h-3 text-white"})})]}),me&&L&&pe&&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:E=>E.stopPropagation(),children:[r.jsx("input",{type:"checkbox",checked:we,onChange:E=>le(oe.id,E.target.checked,E),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 ${pe.matchStatus==="full"?"text-bambu-green":pe.matchStatus==="partial"?"text-yellow-400":"text-orange-400"}`,children:["(",pe.exactMatches,"/",pe.totalSlots," matched)"]}),pe.isLoading&&r.jsx(tr,{className:"w-3 h-3 text-bambu-gray animate-spin"}),we&&r.jsxs("button",{type:"button",onClick:E=>{E.stopPropagation(),d(oe.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(YZ,{className:"w-3 h-3"}),"Auto"]})]}),we&&r.jsx($7e,{printerResult:pe,filamentReqs:c.filaments,onUpdateConfig:E=>u(oe.id,E)})]})]},oe.id)}),m==="printer"&&M>0&&!S&&r.jsxs("button",{type:"button",onClick:()=>k(!0),className:"text-xs text-bambu-gray hover:text-white transition-colors mt-2 flex items-center gap-1",children:[r.jsx(Nn,{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"&&S&&x&&r.jsx("button",{type:"button",onClick:()=>k(!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"&&de===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 G7e=[{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 W7e({options:t,onChange:e,defaultExpanded:n=!1}){const[a,i]=y.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(xy,{className:"w-4 h-4"}),r.jsx("span",{children:"Print Options"}),a?r.jsx(Zo,{className:"w-4 h-4 ml-auto"}):r.jsx(Ln,{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:G7e.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 K7e({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}=_t(),[d,u]=y.useState(""),[m,p]=y.useState(""),[f,g]=y.useState(!0),[w,b]=y.useState(!0),x=y.useRef(null),S=y.useRef(!1);y.useEffect(()=>{if(t.scheduleType!=="scheduled"){S.current=!1;return}if(!S.current){S.current=!0;let _;t.scheduledTime?(_=new Date(t.scheduledTime),isNaN(_.getTime())&&(_=new Date,_.setHours(_.getHours()+1,0,0,0))):(_=new Date,_.setHours(_.getHours()+1,0,0,0),e({...t,scheduledTime:eL(_)})),u(JF(_,n)),p(k6(_,a)),g(!0),b(!0)}},[t.scheduleType,t.scheduledTime,n,a,e,t]);const k=_=>{e({...t,scheduleType:_})},C=(_,M)=>{const H=Zve(_,n),I=Jve(M);g(!!H),b(!!I),H&&I&&(H.setHours(I.hours,I.minutes,0,0),H>new Date&&e({...t,scheduledTime:eL(H)}))},P=_=>{u(_),C(_,m)},T=_=>{p(_),C(d,_)},A=_=>{const M=_.target.value;if(M){const H=new Date(M);isNaN(H.getTime())||(u(JF(H,n)),p(k6(H,a)),g(!0),b(!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:()=>k("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:()=>k("scheduled"),children:[r.jsx(wa,{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:()=>k("manual"),children:[r.jsx(UZ,{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:_=>P(_.target.value),placeholder:Qve(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(wa,{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:_=>T(_.target.value),placeholder:Yve(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:_=>e({...t,requirePreviousSuccess:_.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:_=>e({...t,autoOffAfter:_.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(_u,{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:_=>e({...t,gcodeInjection:_.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(Ky,{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:_=>e({...t,staggerEnabled:_.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(ca,{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:_=>e({...t,staggerGroupSize:Math.max(1,parseInt(_.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:_=>e({...t,staggerIntervalMinutes:Math.max(1,parseInt(_.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 _=Math.ceil(o/t.staggerGroupSize),M=o%t.staggerGroupSize,H=(_-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:_,size:t.staggerGroupSize,interval:t.staggerIntervalMinutes}),M!==0&&t.staggerGroupSize1?` (${c("printModal.staggerTotal","total: {{minutes}} min",{minutes:H})})`:""]})})()]})]}),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 ed={bed_levelling:!0,flow_cali:!1,vibration_cali:!0,layer_inspect:!1,timelapse:!1},h3={scheduleType:"asap",scheduledTime:"",requirePreviousSuccess:!1,autoOffAfter:!1,gcodeInjection:!1,staggerEnabled:!1,staggerGroupSize:2,staggerIntervalMinutes:5};function bc({mode:t,archiveId:e,libraryFileId:n,archiveName:a,queueItem:i,initialSelectedPrinterIds:s,onClose:o,onSuccess:l,projectId:c,cleanupLibraryAfterDispatch:d}){const{t:u}=_t(),m=tn(),{showToast:p}=on(),{hasPermission:f}=dr(),g=!!n&&!e,[w,b]=y.useState(()=>t==="edit-queue-item"&&i?.printer_id?[i.printer_id]:s?.length?s:[]),[x,S]=y.useState(()=>t==="edit-queue-item"&&i?.plate_id!=null?new Set([i.plate_id]):new Set),k=x.size===1?[...x][0]:null,[C,P]=y.useState(1),[T,A]=y.useState(()=>t==="edit-queue-item"&&i?{bed_levelling:i.bed_levelling??ed.bed_levelling,flow_cali:i.flow_cali??ed.flow_cali,vibration_cali:i.vibration_cali??ed.vibration_cali,layer_inspect:i.layer_inspect??ed.layer_inspect,timelapse:i.timelapse??ed.timelapse}:ed),[F,_]=y.useState(()=>{if(t==="edit-queue-item"&&i){let ut="asap";i.manual_start?ut="manual":i.scheduled_time&&!$K(i.scheduled_time)&&(ut="scheduled");let Ct="";if(i.scheduled_time&&!$K(i.scheduled_time)){const Le=Yn(i.scheduled_time)??new Date;Ct=eL(Le)}return{scheduleType:ut,scheduledTime:Ct,requirePreviousSuccess:i.require_previous_success,autoOffAfter:i.auto_off_after,gcodeInjection:i.gcode_injection??!1,staggerEnabled:!1,staggerGroupSize:h3.staggerGroupSize,staggerIntervalMinutes:h3.staggerIntervalMinutes}}return h3}),[M,H]=y.useState(()=>{if(t==="edit-queue-item"&&i?.ams_mapping&&Array.isArray(i.ams_mapping)){const ut={};return i.ams_mapping.forEach((Ct,Le)=>{Ct!==-1&&(ut[Le+1]=Ct)}),ut}return{}}),[I,z]=y.useState({}),[L,Z]=y.useState(()=>t==="edit-queue-item"&&i?.target_model?"model":"printer"),[ne,Y]=y.useState(()=>t==="edit-queue-item"&&i?.target_model?i.target_model:null),[le,ue]=y.useState(()=>t==="edit-queue-item"&&i?.target_location?i.target_location:null),[de,Q]=y.useState(()=>{if(t==="edit-queue-item"&&i?.filament_overrides){const ut={};for(const Ct of i.filament_overrides)ut[Ct.slot_id]={type:Ct.type,color:Ct.color};return ut}return{}}),[oe,me]=y.useState(()=>{if(t==="edit-queue-item"&&i?.filament_overrides){const ut={};for(const Ct of i.filament_overrides)ut[Ct.slot_id]=Ct.force_color_match===!0;return ut}return{}}),[pe]=y.useState(()=>t==="edit-queue-item"&&i?.printer_id?[i.printer_id]:[]),[we]=y.useState(()=>t==="edit-queue-item"&&i?i.plate_id:null),[$,J]=y.useState(!1),[j,E]=y.useState({current:0,total:0}),[B,W]=y.useState(null),[O,ie]=y.useState(new Set),U=w.length,G=w.length>0?w[0]:null,{data:K}=Xe({queryKey:["settings"],queryFn:ae.getSettings}),X=y.useRef(!1);y.useEffect(()=>{!K||X.current||t==="edit-queue-item"||(X.current=!0,A({bed_levelling:K.default_bed_levelling??ed.bed_levelling,flow_cali:K.default_flow_cali??ed.flow_cali,vibration_cali:K.default_vibration_cali??ed.vibration_cali,layer_inspect:K.default_layer_inspect??ed.layer_inspect,timelapse:K.default_timelapse??ed.timelapse}))},[K,t]);const se=y.useRef(!1);y.useEffect(()=>{!K||se.current||t==="edit-queue-item"||(se.current=!0,_(ut=>({...ut,staggerGroupSize:K.stagger_group_size??ut.staggerGroupSize,staggerIntervalMinutes:K.stagger_interval_minutes??ut.staggerIntervalMinutes})))},[K,t]);const te=Ho(K?.currency||"USD"),fe=K?.default_filament_cost??0,{data:ce,isLoading:he}=Xe({queryKey:["printers"],queryFn:ae.getPrinters}),{data:q}=Xe({queryKey:["spool-assignments"],queryFn:()=>ae.getAssignments(),staleTime:30*1e3,enabled:(t==="reprint"||t==="add-to-queue")&&L==="printer"||g&&t==="reprint"}),{data:R}=Xe({queryKey:["archive",e],queryFn:()=>ae.getArchive(e),enabled:!!e&&!g}),{data:re}=Xe({queryKey:["library-file",n],queryFn:()=>ae.getLibraryFile(n),enabled:g&&!!n}),be=R?.sliced_for_model||re?.sliced_for_model||null,{data:ye,isError:_e}=Xe({queryKey:["archive-plates",e],queryFn:()=>ae.getArchivePlates(e),enabled:!!e&&!g,retry:!1}),{data:xe}=Xe({queryKey:["library-file-plates",n],queryFn:()=>ae.getLibraryFilePlates(n),enabled:g&&!!n}),ge=g?xe:ye,{data:Me,isError:Be}=Xe({queryKey:["archive-filaments",e,k],queryFn:()=>ae.getArchiveFilamentRequirements(e,k??void 0),enabled:!!e&&!g&&(k!==null||!ge?.is_multi_plate),retry:!1}),{data:Fe}=Xe({queryKey:["library-file-filaments",n,k],queryFn:()=>ae.getLibraryFileFilamentRequirements(n,k??void 0),enabled:g&&!!n&&(k!==null||!ge?.is_multi_plate)}),Oe=!g&&(_e||Be),Re=g?Fe:Me,We=y.useMemo(()=>{if(!(k===null||!ge?.plates?.length))return ge.plates.find(ut=>ut.index===k)?.name||void 0},[ge,k]),{data:ze}=Xe({queryKey:["available-filaments",ne,le],queryFn:()=>ae.getAvailableFilaments(ne,le??void 0),enabled:L==="model"&&!!ne}),{data:st}=Xe({queryKey:["printer-status",G],queryFn:()=>ae.getPrinterStatus(G),enabled:!!G}),{amsMapping:Ee}=tse(Re,st,M,K?.prefer_lowest_filament),it=O7e(w,ce,Re,M,I,z,K?.prefer_lowest_filament);y.useEffect(()=>{ge?.plates&&ge.plates.length>=1&&x.size===0&&S(new Set([ge.plates[0].index]))},[ge,x.size]),y.useEffect(()=>{if(t==="edit-queue-item")return;const ut=ce?.filter(Ct=>Ct.is_active)||[];ut.length===1&&w.length===0&&b([ut[0].id])},[t,ce,w.length]),y.useEffect(()=>{t==="edit-queue-item"?(JSON.stringify(w.sort())!==JSON.stringify(pe.sort())||k!==we)&&(H({}),z({}),ie(new Set)):(H({}),z({}),ie(new Set))},[t,w,k,pe,we]);const[Ce,Ze]=y.useState(ne),[Ie,ke]=y.useState(k);y.useEffect(()=>{(ne!==Ce||k!==Ie)&&(Ze(ne),ke(k),(t!=="edit-queue-item"||Ce!==null)&&(Q({}),me({})))},[ne,k,Ce,Ie,t]),y.useEffect(()=>{if(!K?.per_printer_mapping_expanded||w.length<=1)return;const ut=w.filter(Ct=>{if(O.has(Ct))return!1;const Le=it.printerResults.find(Ae=>Ae.printerId===Ct);return Le&&Le.status&&!Le.isLoading});ut.length>0&&(ie(Ct=>{const Le=new Set(Ct);return ut.forEach(Ae=>Le.add(Ae)),Le}),ut.forEach(Ct=>{it.autoConfigurePrinter(Ct)}))},[K?.per_printer_mapping_expanded,w,O,it]),y.useEffect(()=>{const ut=Ct=>{Ct.key==="Escape"&&!$&&o()};return window.addEventListener("keydown",ut),()=>window.removeEventListener("keydown",ut)},[o,$]);const Ve=ge?.is_multi_plate??!1,rt=ge?.plates??[],Qe=y.useMemo(()=>{const ut=new Map;return q&&q.forEach(Ct=>{const Le=Ct.ams_id===255,Ae=Qg(Ct.ams_id,Ct.tray_id,Le),Ge=ut.get(Ct.printer_id)??new Map;Ge.set(Ae,Ct),ut.set(Ct.printer_id,Ge)}),ut},[q]),Te=y.useMemo(()=>{if(!B||B.length===0)return"";const ut=B.map(Ct=>u("printModal.insufficientFilamentLine",{printer:Ct.printerName,slot:Ct.slotLabel,required:Math.round(Ct.requiredGrams),remaining:Math.round(Ct.remainingGrams)}));return[u("printModal.insufficientFilamentMessage"),...ut].join(` +${l("inventory.assignProfileMismatchMessage",{spoolProfile:T.spoolProfile||l("common.unknown"),trayProfile:T.trayProfile||l("common.unknown"),location:s.location})}`:T.type==="profile"&&(j=l("inventory.assignProfileMismatchMessage",{spoolProfile:T.spoolProfile||l("common.unknown"),trayProfile:T.trayProfile||l("common.unknown"),location:s.location})),r.jsx(wn,{title:l("inventory.assignMismatchTitle"),message:j,confirmText:l("inventory.assignMismatchConfirm"),variant:"warning",overlayZIndex:"z-[110]",isLoading:Y.isPending,onConfirm:J,onCancel:()=>{Y.isPending||(P(!1),k(null),A(null))}})})()]})}function RK(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 m3(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 sw=["PLA","PETG","PCTG","ABS","ASA","TPU","PC","PA","NYLON","PVA","HIPS","PP","PET"];function IK(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 sw)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 sw){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 A7e(t){return!t.startsWith("GF")&&!t.startsWith("P1")}const j7e={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"},OK=[{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"}],zK=[{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 UK(t){const e=t.toLowerCase().trim();return j7e[e]||null}function M7e(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 Xie({isOpen:t,onClose:e,printerId:n,slotInfo:a,nozzleDiameter:i="0.4",printerModel:s,onSuccess:o,fullScreen:l}){const{t:c}=_t(),[d,u]=y.useState(""),[m,p]=y.useState(null),[f,g]=y.useState(""),[w,b]=y.useState(""),[x,S]=y.useState(""),[k,C]=y.useState(!1),[P,T]=y.useState(!1),A=y.useRef(""),{data:F,isLoading:_,isError:M}=Xe({queryKey:["cloudSettings"],queryFn:()=>ae.getCloudSettings(),enabled:t,retry:!1}),{data:H,isLoading:I}=Xe({queryKey:["localPresets"],queryFn:()=>ae.getLocalPresets(),enabled:t}),{data:z,isLoading:L}=Xe({queryKey:["builtinFilaments"],queryFn:()=>ae.getBuiltinFilaments(),enabled:t,staleTime:1/0}),{data:Z,isLoading:ne}=Xe({queryKey:["kprofiles",n,i],queryFn:()=>ae.getKProfiles(n,i),enabled:t&&!!n}),{data:Y}=Xe({queryKey:["colorCatalog"],queryFn:()=>ae.getColorCatalog(),enabled:t,staleTime:1/0}),le=lt({mutationFn:async()=>{if(!d)throw new Error("No filament preset selected");const E=d.startsWith("local_"),B=d.startsWith("builtin_"),W=E?parseInt(d.replace("local_",""),10):null,O=B?d.replace("builtin_",""):null,ie=E?H?.filament.find(Me=>Me.id===W):null,U=B?z?.find(Me=>Me.filament_id===O):null,G=!E&&!B?F?.filament.find(Me=>Me.setting_id===d):null;if(!E&&!B&&!G)throw new Error("Selected preset not found");if(E&&!ie)throw new Error("Selected local preset not found");if(B&&!U)throw new Error("Selected builtin preset not found");const K=E?ie.name:B?U.name:G.name,X=IK(K),se=m?.slot_id??-1,te=f||a.trayColor?.slice(0,6)||"FFFFFF",fe=K.replace(/@.+$/,"").trim();let ce,he;const q=X.material.toUpperCase();if(E){const Me=(sw.includes(q)?q:ie?.filament_type||X.material||"").toUpperCase(),Be={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=Be[Me]||Be[Me.replace(/[-\s]?CF$/,"")]||Be[Me.replace(/\+$/,"")]||Be[Me.split(/[-\s]/)[0]]||"",he=""}else if(B)ce=O,he="";else if(ce=m3(d),he=d,!d.startsWith("GFS"))try{const Me=await ae.getCloudSettingDetail(d);Me.filament_id&&(ce=Me.filament_id)}catch(Me){console.warn("Failed to fetch preset detail for filament_id:",Me)}let R=E&&ie?.nozzle_temp_min?ie.nozzle_temp_min:190,re=E&&ie?.nozzle_temp_max?ie.nozzle_temp_max:230;if(!E||B||!ie?.nozzle_temp_min&&!ie?.nozzle_temp_max){const Me=(E?sw.includes(q)?q:ie?.filament_type||X.material||"":X.material).toUpperCase();Me.includes("PLA")?(R=190,re=230):Me.includes("PETG")?(R=220,re=260):Me.includes("ABS")||Me.includes("ASA")?(R=240,re=280):Me.includes("TPU")?(R=200,re=240):Me==="PCTG"?(R=220,re=260):Me.includes("PC")?(R=260,re=300):(Me.includes("PA")||Me.includes("NYLON"))&&(R=250,re=290)}const be=m?.k_value?parseFloat(m.k_value):0,ye=E?sw.includes(q)?q:ie?.filament_type||X.material||"PLA":X.material||"PLA",_e=await ae.configureAmsSlot(n,a.amsId,a.trayId,{tray_info_idx:ce,tray_type:ye,tray_sub_brands:fe,tray_color:te+"FF",nozzle_temp_min:R,nozzle_temp_max:re,cali_idx:se,nozzle_diameter:i,setting_id:he,kprofile_filament_id:m?.filament_id,kprofile_setting_id:m?.setting_id||void 0,k_value:be}),xe=E?`local_${W}`:B?`builtin_${O}`:d,ge=E?"local":B?"builtin":"cloud";try{await ae.saveSlotPreset(n,a.amsId,a.trayId,xe,fe,ge)}catch(Me){console.warn("Failed to save slot preset mapping:",Me)}return _e},onSuccess:()=>{C(!0),o?.(),setTimeout(()=>{C(!1),e()},1500)}}),ue=lt({mutationFn:async()=>ae.resetAmsSlot(n,a.amsId,a.trayId),onSuccess:()=>{C(!0),o?.(),setTimeout(()=>{C(!1),e()},1500)}}),de=y.useMemo(()=>{const E=x.toLowerCase(),B=[],W=new Set,O=a.savedPresetId,ie=a.trayInfoIdx;if(F?.filament)for(const U of F.filament){W.add(U.setting_id);const K=O===U.setting_id||ie&&(U.setting_id===ie||m3(U.setting_id)===ie);if(!(E&&!U.name.toLowerCase().includes(E))){if(!K&&s){const X=M7e(U.name);if(X&&X.toUpperCase()!==s.toUpperCase())continue}B.push({id:U.setting_id,name:U.name,source:"cloud",isUser:A7e(U.setting_id)})}}if(H?.filament)for(const U of H.filament){const G=`local_${U.id}`;E&&!U.name.toLowerCase().includes(E)||B.push({id:G,name:U.name,source:"local",isUser:!1})}if(z)for(const U of z){if(W.has(U.filament_id))continue;const G=U.filament_id.startsWith("GF")?"GFS"+U.filament_id.slice(2):U.filament_id;W.has(G)||(!E||U.name.toLowerCase().includes(E))&&B.push({id:`builtin_${U.filament_id}`,name:U.name,source:"builtin",isUser:!1})}return B.sort((U,G)=>{const K={cloud:0,local:1,builtin:2};return U.source!==G.source?K[U.source]-K[G.source]:U.isUser&&!G.isUser?-1:!U.isUser&&G.isUser?1:U.name.localeCompare(G.name)})},[F?.filament,H?.filament,z,x,s,a.savedPresetId,a.trayInfoIdx]),Q=y.useMemo(()=>{if(!d)return null;let E=null;if(d.startsWith("local_")){const O=parseInt(d.replace("local_",""),10);E=H?.filament.find(U=>U.id===O)?.name||null}else if(d.startsWith("builtin_")){const O=d.replace("builtin_","");E=z?.find(U=>U.filament_id===O)?.name||null}else F?.filament&&(E=F.filament.find(ie=>ie.setting_id===d)?.name||null);if(!E)return null;let B=E.replace(/@.+$/,"").trim();B.startsWith("# ")&&(B=B.slice(2).trim());const W=IK(B);return{fullName:B,material:W.material,brand:W.brand}},[d,F?.filament,H?.filament,z]),oe=Q?.fullName||"",me=y.useMemo(()=>{if(!Y||!Q)return[];const{fullName:E,brand:B}=Q,W=E.replace(/^(Bambu\s*(Lab)?|eSUN|Polymaker|Overture|Sunlu|Hatchbox)\s*/i,"").trim();return Y.filter(O=>{const ie=(O.material||"").toUpperCase(),U=O.manufacturer.toUpperCase();if(!(ie===W.toUpperCase()||ie.includes(W.toUpperCase())||W.toUpperCase().includes(ie)))return!1;if(B){const K=B.toUpperCase();if(!U.includes(K)&&!K.includes(U))return!1}return!0})},[Y,Q]),pe=y.useMemo(()=>{if(!Z?.profiles||!Q)return[];const{fullName:E,material:B,brand:W}=Q,O=E.toUpperCase(),ie=B.toUpperCase(),U=W.toUpperCase();if(!ie||ie.length<2)return[];const G=Z.profiles.filter(X=>{const se=X.name.toUpperCase();if(U)return!(!se.includes(U)||!se.includes(ie));if(se.includes(O)||se.includes(ie))return!0;const fe={NYLON:["PA","PA-CF","PA6"],PA:["NYLON"]}[ie]||[];for(const ce of fe)if(se.includes(ce))return!0;return!1}),K=new Map;for(const X of G){const se=`${X.name}|${X.k_value}`,te=K.get(se);te?a.extruderId!==void 0&&X.extruder_id===a.extruderId&&te.extruder_id!==a.extruderId&&K.set(se,X):K.set(se,X)}return Array.from(K.values())},[Z?.profiles,Q,a.extruderId]);y.useEffect(()=>{if(t){if(a.savedPresetId)u(a.savedPresetId);else if(a.trayInfoIdx&&F?.filament){let E=F.filament.find(B=>B.setting_id===a.trayInfoIdx);E||(E=F.filament.find(B=>m3(B.setting_id)===a.trayInfoIdx)),E&&u(E.setting_id)}else if(a.trayInfoIdx&&z?.length){const E=a.trayInfoIdx,B=z.find(W=>W.filament_id===E);B&&u(`builtin_${B.filament_id}`)}if(a.trayColor){const E=a.trayColor.slice(0,6);E&&g(E)}}else u(""),p(null),g(""),b(""),S(""),C(!1),A.current=""},[t,a.savedPresetId,a.trayInfoIdx,a.trayColor,F?.filament,z]),y.useEffect(()=>{if(pe.length>0){if(a.caliIdx!=null&&a.caliIdx>0){const E=pe.find(B=>B.slot_id===a.caliIdx);if(E){p(E);return}}p(pe[0])}else p(null)},[d,pe,a.caliIdx]);const we=y.useCallback(E=>{E.key==="Escape"&&e()},[e]);y.useEffect(()=>{if(t)return document.addEventListener("keydown",we),()=>document.removeEventListener("keydown",we)},[t,we]);const $=_&&!M||I||L||ne;if(y.useEffect(()=>{if(!$&&d&&d!==A.current){const E=requestAnimationFrame(()=>{const W=document.querySelector('[class*="fixed inset-0 z-50"]')?.querySelector(`[data-preset-id="${CSS.escape(d)}"]`);W&&(A.current=d,W.scrollIntoView({block:"nearest"}))});return()=>cancelAnimationFrame(E)}},[d,$]),!t)return null;const J=d&&!le.isPending,j=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(pu,{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:RK(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(Vt,{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:[k&&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(yl,{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:RK(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(ft,{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:E=>S(E.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder:text-bambu-gray focus:border-bambu-green focus:outline-none mb-2 shrink-0"}),r.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto space-y-1",children:de.length===0?r.jsx("p",{className:"text-center py-4 text-bambu-gray",children:F?.filament?.length===0&&!H?.filament?.length?c("configureAmsSlot.noPresetsAvailable"):c("configureAmsSlot.noMatchingPresets")}):de.map(E=>r.jsx("button",{"data-preset-id":E.id,onClick:()=>u(E.id),className:`group w-full p-2 rounded-lg border text-left transition-colors ${d===E.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:E.name,children:E.name}),r.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[E.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")}),E.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")}),E.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")})]})]})},E.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"),oe&&r.jsx("span",{className:"ml-2 text-xs text-bambu-blue",children:c("configureAmsSlot.filteringFor",{material:oe})})]}),pe.length>0?r.jsxs("div",{className:"relative",children:[r.jsxs("select",{value:m?.name||"",onChange:E=>{const B=pe.find(W=>W.name===E.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")}),pe.map(E=>r.jsxs("option",{value:E.name,children:[E.name," (K=",E.k_value,")"]},`${E.name}-${E.extruder_id}`))]}),r.jsx(Ln,{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")}),me.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:Q?.fullName})}),r.jsx("div",{className:"flex flex-wrap gap-1.5",children:me.map(E=>r.jsxs("button",{onClick:()=>{const B=E.hex_color.replace("#","").toUpperCase();g(B),b(E.color_name)},className:`h-7 px-2 rounded-md border-2 transition-all flex items-center gap-1.5 ${f===E.hex_color.replace("#","").toUpperCase()?"border-bambu-green scale-105":"border-white/20 hover:border-white/40"}`,title:E.color_name,children:[r.jsx("span",{className:"w-4 h-4 rounded-full border border-black/20 flex-shrink-0",style:{backgroundColor:E.hex_color}}),r.jsx("span",{className:"text-xs text-white/80 whitespace-nowrap",children:E.color_name})]},E.id))})]}),r.jsxs("div",{className:"flex flex-wrap gap-1.5 mb-2",children:[OK.map(E=>r.jsx("button",{onClick:()=>{g(E.hex),b(E.name)},className:`w-7 h-7 rounded-md border-2 transition-all ${f===E.hex?"border-bambu-green scale-110":"border-white/20 hover:border-white/40"}`,style:{backgroundColor:`#${E.hex}`},title:E.name},E.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:zK.map(E=>r.jsx("button",{onClick:()=>{g(E.hex),b(E.name)},className:`w-7 h-7 rounded-md border-2 transition-all ${f===E.hex?"border-bambu-green scale-110":"border-white/20 hover:border-white/40"}`,style:{backgroundColor:`#${E.hex}`},title:E.name},E.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:`#${j}`}}),r.jsx("input",{type:"text",placeholder:c("configureAmsSlot.colorPlaceholder"),value:w,onChange:E=>{const B=E.target.value;b(B);const W=UK(B);if(W)g(W);else{const O=B.replace(/[^0-9A-Fa-f]/g,"").toUpperCase();O.length===6?g(O):O.length===3&&g(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:()=>{g(""),b("")},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:E=>S(E.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder:text-bambu-gray focus:border-bambu-green focus:outline-none mb-2"}),r.jsx("div",{className:"max-h-48 overflow-y-auto space-y-1",children:de.length===0?r.jsx("p",{className:"text-center py-4 text-bambu-gray",children:F?.filament?.length===0&&!H?.filament?.length?c("configureAmsSlot.noPresetsAvailable"):c("configureAmsSlot.noMatchingPresets")}):de.map(E=>r.jsx("button",{"data-preset-id":E.id,onClick:()=>u(E.id),className:`group w-full p-2 rounded-lg border text-left transition-colors ${d===E.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:E.name,children:E.name}),r.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[E.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")}),E.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")}),E.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")})]})]})},E.id))})]})]}),r.jsxs("div",{children:[r.jsxs("label",{className:"block text-sm text-bambu-gray mb-2",children:[c("configureAmsSlot.kProfileLabel"),oe&&r.jsx("span",{className:"ml-2 text-xs text-bambu-blue",children:c("configureAmsSlot.filteringFor",{material:oe})})]}),pe.length>0?r.jsxs("div",{className:"relative",children:[r.jsxs("select",{value:m?.name||"",onChange:E=>{const B=pe.find(W=>W.name===E.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")}),pe.map(E=>r.jsxs("option",{value:E.name,children:[E.name," (K=",E.k_value,")"]},`${E.name}-${E.extruder_id}`))]}),r.jsx(Ln,{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")}),me.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:Q?.fullName})}),r.jsx("div",{className:"flex flex-wrap gap-1.5",children:me.map(E=>r.jsxs("button",{onClick:()=>{const B=E.hex_color.replace("#","").toUpperCase();g(B),b(E.color_name)},className:`h-7 px-2 rounded-md border-2 transition-all flex items-center gap-1.5 ${f===E.hex_color.replace("#","").toUpperCase()?"border-bambu-green scale-105":"border-white/20 hover:border-white/40"}`,title:E.color_name,children:[r.jsx("span",{className:"w-4 h-4 rounded-full border border-black/20 flex-shrink-0",style:{backgroundColor:E.hex_color}}),r.jsx("span",{className:"text-xs text-white/80 whitespace-nowrap",children:E.color_name})]},E.id))})]}),r.jsxs("div",{className:"flex flex-wrap gap-1.5 mb-2",children:[OK.map(E=>r.jsx("button",{onClick:()=>{g(E.hex),b(E.name)},className:`w-7 h-7 rounded-md border-2 transition-all ${f===E.hex?"border-bambu-green scale-110":"border-white/20 hover:border-white/40"}`,style:{backgroundColor:`#${E.hex}`},title:E.name},E.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:zK.map(E=>r.jsx("button",{onClick:()=>{g(E.hex),b(E.name)},className:`w-7 h-7 rounded-md border-2 transition-all ${f===E.hex?"border-bambu-green scale-110":"border-white/20 hover:border-white/40"}`,style:{backgroundColor:`#${E.hex}`},title:E.name},E.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:`#${j}`}}),r.jsx("input",{type:"text",placeholder:c("configureAmsSlot.colorPlaceholder"),value:w,onChange:E=>{const B=E.target.value;b(B);const W=UK(B);if(W)g(W);else{const O=B.replace(/[^0-9A-Fa-f]/g,"").toUpperCase();O.length===6?g(O):O.length===3&&g(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:()=>{g(""),b("")},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(je,{variant:"secondary",onClick:()=>ue.mutate(),disabled:ue.isPending||le.isPending,className:"text-red-400 hover:text-red-300 hover:bg-red-500/10",children:ue.isPending?r.jsxs(r.Fragment,{children:[r.jsx(ft,{className:"w-4 h-4 animate-spin"}),c("configureAmsSlot.resetting")]}):r.jsxs(r.Fragment,{children:[r.jsx(fs,{className:"w-4 h-4"}),c("configureAmsSlot.resetSlot")]})}),r.jsxs("div",{className:"flex gap-2",children:[r.jsx(je,{variant:"secondary",onClick:e,children:c("configureAmsSlot.cancel")}),r.jsx(je,{onClick:()=>le.mutate(),disabled:!J,children:le.isPending?r.jsxs(r.Fragment,{children:[r.jsx(ft,{className:"w-4 h-4 animate-spin"}),c("configureAmsSlot.configuring")]}):r.jsxs(r.Fragment,{children:[r.jsx(pu,{className:"w-4 h-4"}),c("configureAmsSlot.configureSlot")]})})]})]}),(le.isError||ue.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:le.error?.message||ue.error?.message})]})]})}function BK({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 Zie({folderId:t,onClose:e,onUploadComplete:n,onFileUploaded:a,autoUpload:i,validateFile:s,accept:o}){const{t:l}=_t(),[c,d]=y.useState([]),[u,m]=y.useState(!1),[p,f]=y.useState(!1),[g,w]=y.useState(!0),[b,x]=y.useState(!1),[S,k]=y.useState(!0),[C,P]=y.useState(null),T=y.useRef(null),A=de=>{de.preventDefault(),m(!0)},F=de=>{de.preventDefault(),m(!1)},_=de=>{de.preventDefault(),m(!1),z(Array.from(de.dataTransfer.files))},M=de=>{de.target.files&&z(Array.from(de.target.files))},H=(de,Q)=>{d(oe=>oe.map(me=>me.file===de?{...me,...Q}:me))},I=async de=>{f(!0);for(const Q of de)if(Q.status==="pending"){H(Q.file,{status:"uploading"});try{if(Q.isZip){const oe=await ae.extractZipFile(Q.file,t,g,b,S);H(Q.file,{status:oe.errors.length>0&&oe.extracted===0?"error":"success",extractedCount:oe.extracted,error:oe.errors.length>0?l("fileManager.zipFilesFailed","{{count}} files failed",{count:oe.errors.length}):void 0})}else{const oe=await ae.uploadLibraryFile(Q.file,t,S);H(Q.file,{status:"success"});const me=a?.(oe);if(me){P(me),d([]),f(!1);return}}}catch(oe){H(Q.file,{status:"error",error:oe instanceof Error?oe.message:l("fileManager.uploadFailed","Upload failed")})}}f(!1),n(),d(Q=>(Q.some(me=>me.status==="error")||e(),Q))},z=de=>{if(P(null),s)for(const oe of de){const me=s(oe);if(me){P(me);return}}const Q=de.map(oe=>({file:oe,status:"pending",isZip:oe.name.toLowerCase().endsWith(".zip"),is3mf:oe.name.toLowerCase().endsWith(".3mf")}));d(oe=>[...oe,...Q]),i&&de.length>0&&I(Q)},L=de=>{d(Q=>Q.filter((oe,me)=>me!==de))},Z=c.some(de=>de.isZip&&de.status==="pending"),ne=c.some(de=>de.file.name.toLowerCase().endsWith(".stl")&&de.status==="pending"),Y=c.some(de=>de.is3mf&&de.status==="pending"),le=c.filter(de=>de.status==="pending").length,ue=c.length>0&&le===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(Vt,{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:_,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(_a,{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(eo,{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:g,onChange:de=>w(de.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:b,onChange:de=>x(de.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")})]})]})]})}),Y&&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(hr,{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")})]})]})}),(ne||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(mu,{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&&!ne?"fileManager.zipMayContainStl":"fileManager.thumbnailsCanBeGenerated")}),r.jsxs("label",{className:"flex items-center gap-2 mt-2 cursor-pointer",children:[r.jsx("input",{type:"checkbox",checked:S,onChange:de=>k(de.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((de,Q)=>r.jsxs("div",{className:"flex items-center gap-3 p-2 bg-bambu-dark rounded-lg",children:[de.isZip?r.jsx(eo,{className:"w-4 h-4 text-blue-400 flex-shrink-0"}):r.jsx(NT,{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:de.file.name}),r.jsxs("p",{className:"text-xs text-bambu-gray",children:[(de.file.size/1024/1024).toFixed(2)," MB",de.isZip&&de.status==="pending"&&r.jsxs("span",{className:"text-blue-400 ml-2",children:["• ",l("fileManager.willBeExtracted")]}),de.extractedCount!==void 0&&r.jsxs("span",{className:"text-green-400 ml-2",children:["• ",l("fileManager.filesExtracted",{count:de.extractedCount})]})]}),de.status==="error"&&de.error&&r.jsx("p",{className:"text-xs text-red-400 mt-1 break-words",children:de.error})]}),de.status==="pending"&&r.jsx("button",{onClick:()=>L(Q),className:"p-1 hover:bg-bambu-dark-tertiary rounded",children:r.jsx(Vt,{className:"w-4 h-4 text-bambu-gray"})}),de.status==="uploading"&&r.jsx(ft,{className:"w-4 h-4 text-bambu-green animate-spin"}),de.status==="success"&&r.jsx(xr,{className:"w-4 h-4 text-green-500"}),de.status==="error"&&r.jsx("span",{title:de.error,children:r.jsx($r,{className:"w-4 h-4 text-red-500"})})]},Q))}),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($r,{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(je,{variant:"secondary",onClick:e,children:l("common.cancel")}),!ue&&r.jsx(je,{onClick:()=>I(c),disabled:le===0||p,children:p?r.jsxs(r.Fragment,{children:[r.jsx(ft,{className:"w-4 h-4 mr-2 animate-spin"}),l("fileManager.uploading")]}):r.jsxs(r.Fragment,{children:[r.jsx(_a,{className:"w-4 h-4 mr-2"}),l("common.upload")," ",le>0?`(${le})`:""]})})]})]})})}function HK(t){return t?`#${t.replace("#","").substring(0,6)}`:"#808080"}function Ia(t){return t?t.replace("#","").toLowerCase().substring(0,6):""}const E7e=[["PA-CF","PA12-CF","PAHT-CF"]],Jie={};for(const t of E7e){const e=t[0];for(const n of t)Jie[n.toUpperCase()]=e.toUpperCase()}function wP(t){if(!t)return"";const e=t.toUpperCase();return Jie[e]??e}function p3(t,e){return wP(t)===wP(e)}function md(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 u_(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 my(t){return t>50?"#00ae42":t>=15?"#f59e0b":"#ef4444"}function LN(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 qK(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 gm(t,e,n){return`${D7e(t)}${qK(e,4)}${qK(n,4)}`}function $K(t){if(!t)return!1;const e=Date.now()+4320*60*60*1e3;return(Yn(t)?.getTime()??0)>e}function F7e(t,e,n,a){let i=ese(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)&&p3(c.type,t.type)&&Ia(c.color)===Ia(t.color)),o=s?void 0:i.find(c=>!n.has(c.globalTrayId)&&p3(c.type,t.type)&&md(c.color,t.color)),l=s||o?void 0:i.find(c=>!n.has(c.globalTrayId)&&p3(c.type,t.type));return s??o??l}function ese(t,e){return t.filter(n=>e==null||n.extruderId===e)}function Ks(t){return t?!!(t.tray_uuid&&t.tray_uuid!=="00000000000000000000000000000000"||t.tag_uid&&t.tag_uid!=="0000000000000000"):!1}function m_(t){const e=[],n=t?.ams_extruder_map,a=!!t?.nozzles?.[1]?.nozzle_diameter||n&&Object.keys(n).length>0||(t?.vt_tray?.length??0)>1;t?.ams?.forEach(i=>{const s=i.tray.length===1;i.tray.forEach(o=>{if(o.tray_type){const l=HK(o.tray_color);e.push({type:o.tray_type,color:l,colorName:fc(l),amsId:i.id,trayId:o.id,isHt:s,isExternal:!1,label:u_(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=HK(i.tray_color),o=i.id??254,l=(t?.vt_tray?.length??0)>1;e.push({type:i.tray_type,color:s,colorName:fc(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 VK(t,e,n){if(!t?.filaments||t.filaments.length===0)return;const a=m_(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,S)=>{const k=x.remain>=0?x.remain:101,C=S.remain>=0?S.remain:101;return k-C}));let p,f,g,w;if(u){const x=m.filter(S=>S.trayInfoIdx===u);x.length===1?p=x[0]:x.length>1&&(n&&x.sort((S,k)=>{const C=S.remain>=0?S.remain:101,P=k.remain>=0?k.remain:101;return C-P}),f=x.find(S=>S.type?.toUpperCase()===d.type?.toUpperCase()&&Ia(S.color)===Ia(d.color)),f||(g=x.find(S=>S.type?.toUpperCase()===d.type?.toUpperCase()&&md(S.color,d.color))),!f&&!g&&(w=x.find(S=>S.type?.toUpperCase()===d.type?.toUpperCase())))}!p&&!f&&!g&&!w&&(f=m.find(x=>x.type?.toUpperCase()===d.type?.toUpperCase()&&Ia(x.color)===Ia(d.color)),f||(g=m.find(x=>x.type?.toUpperCase()===d.type?.toUpperCase()&&md(x.color,d.color))),!f&&!g&&(w=m.find(x=>x.type?.toUpperCase()===d.type?.toUpperCase())));const b=p||f||g||w||void 0;return b&&s.add(b.globalTrayId),{slot_id:d.slot_id,globalTrayId:b?.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 L7e(t){return y.useMemo(()=>m_(t),[t])}function tse(t,e,n,a){const i=L7e(e),s=e?.fila_switch?.installed===!0,o=y.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],_=i.find(M=>M.globalTrayId===F);if(_){const M=_.type?.toUpperCase()===m.type?.toUpperCase(),H=Ia(_.color)===Ia(m.color)||md(_.color,m.color);let I;return M&&H?I="match":M?I="type_only":I="mismatch",{...m,loaded:_,hasFilament:!0,typeMatch:M,colorMatch:H,status:I,isManual:!0}}}const f=m.tray_info_idx||"";let g=i.filter(F=>!u.has(F.globalTrayId));m.nozzle_id!=null&&!s&&(g=g.filter(F=>F.extruderId===m.nozzle_id)),a&&(g=[...g].sort((F,_)=>{const M=F.remain>=0?F.remain:101,H=_.remain>=0?_.remain:101;return M-H}));let w,b,x,S;if(f){const F=g.filter(_=>_.trayInfoIdx===f);F.length===1?w=F[0]:F.length>1&&(a&&F.sort((_,M)=>{const H=_.remain>=0?_.remain:101,I=M.remain>=0?M.remain:101;return H-I}),b=F.find(_=>_.type?.toUpperCase()===m.type?.toUpperCase()&&Ia(_.color)===Ia(m.color)),b||(x=F.find(_=>_.type?.toUpperCase()===m.type?.toUpperCase()&&md(_.color,m.color))),!b&&!x&&(S=F.find(_=>_.type?.toUpperCase()===m.type?.toUpperCase())))}!w&&!b&&!x&&!S&&(b=g.find(F=>F.type?.toUpperCase()===m.type?.toUpperCase()&&Ia(F.color)===Ia(m.color)),b||(x=g.find(F=>F.type?.toUpperCase()===m.type?.toUpperCase()&&md(F.color,m.color))),!b&&!x&&(S=g.find(F=>F.type?.toUpperCase()===m.type?.toUpperCase())));const k=w||b||x||S||void 0;k&&u.add(k.globalTrayId);const C=!!k,P=C,T=!!w||!!b||!!x;let A;return w||b||x?A="match":S?A="type_only":A="mismatch",{...m,loaded:k,hasFilament:C,typeMatch:P,colorMatch:T,status:A,isManual:!1}})},[t,i,n,a,s]),l=y.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 R7e(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],S=e.find(k=>k.globalTrayId===x);if(S){const k=S.type?.toUpperCase()===u.type?.toUpperCase(),C=Ia(S.color)===Ia(u.color)||md(S.color,u.color);k&&C?i++:k?s++:o++;continue}}let p=e.filter(x=>!l.has(x.globalTrayId));if(u.nozzle_id!=null){const x=p.filter(S=>S.extruderId===u.nozzle_id);x.length>0&&(p=x)}a&&(p=[...p].sort((x,S)=>{const k=x.remain>=0?x.remain:101,C=S.remain>=0?S.remain:101;return k-C}));const f=p.find(x=>x.type?.toUpperCase()===u.type?.toUpperCase()&&Ia(x.color)===Ia(u.color)),g=f?void 0:p.find(x=>x.type?.toUpperCase()===u.type?.toUpperCase()&&md(x.color,u.color)),w=f||g?void 0:p.find(x=>x.type?.toUpperCase()===u.type?.toUpperCase()),b=f??g??w;b&&l.add(b.globalTrayId),f||g?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 I7e(t,e,n,a){if(!t?.filaments||t.filaments.length===0)return;const i=m_(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(b=>!s.has(b.globalTrayId));if(d.nozzle_id!=null){const b=m.filter(x=>x.extruderId===d.nozzle_id);b.length>0&&(m=b)}a&&(m=[...m].sort((b,x)=>{const S=b.remain>=0?b.remain:101,k=x.remain>=0?x.remain:101;return S-k}));const p=m.find(b=>b.type?.toUpperCase()===d.type?.toUpperCase()&&Ia(b.color)===Ia(d.color)),f=p?void 0:m.find(b=>b.type?.toUpperCase()===d.type?.toUpperCase()&&md(b.color,d.color)),g=p||f?void 0:m.find(b=>b.type?.toUpperCase()===d.type?.toUpperCase()),w=p??f??g;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 GK={useDefault:!0,manualMappings:{},autoConfigured:!1};function O7e(t,e,n,a,i,s,o){const l=rf({queries:t.map(w=>({queryKey:["printer-status",w],queryFn:()=>ae.getPrinterStatus(w),enabled:t.length>0,staleTime:5e3}))}),c=y.useMemo(()=>t.map((w,b)=>{const x=l[b],S=x?.data,C=e?.find(H=>H.id===w)?.name||`Printer ${w}`,P=m_(S),T=i[w]||GK,A=VK(n,S,o),F=T.useDefault?a:T.manualMappings,_=I7e(n,S,F,o),M=R7e(n?.filaments,P,F,o);return{printerId:w,printerName:C,status:S,isLoading:x?.isLoading??!1,loadedFilaments:P,autoMapping:A,finalMapping:_,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,b)=>{s(x=>({...x,[w]:{...x[w]||GK,...b}}))},m=w=>{const b=c.find(k=>k.printerId===w);if(!b||!b.status||!n?.filaments)return;const x=VK(n,b.status,o);if(!x)return;const S={};x.forEach((k,C)=>{k!==-1&&(S[C+1]=k)}),u(w,{useDefault:!1,manualMappings:S,autoConfigured:!0})},p=()=>{for(const w of t)m(w)},f=w=>c.find(x=>x.printerId===w)?.finalMapping,g=c.every(w=>w.matchStatus!=="missing");return{printerResults:c,isLoading:d,perPrinterConfigs:i,updatePrinterConfig:u,autoConfigureAll:p,autoConfigurePrinter:m,getFinalMapping:f,allPrintersReady:g}}const nse={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$",BZD:"BZ$",MYR:"RM",CZK:"Kč",THB:"฿",ZAR:"R",TRY:"₺",RUB:"₽",HUF:"Ft",ILS:"₪",UAH:"₴"};function Ho(t){return nse[t.toUpperCase()]||t}const z7e=Object.entries(nse).map(([t,e])=>({code:t,label:`${t} (${e})`}));function U7e({printerId:t,filamentReqs:e,manualMappings:n,onManualMappingChange:a,currencySymbol:i,defaultCostPerKg:s,defaultExpanded:o=!1}){const{t:l}=_t(),c=tn(),[d,u]=y.useState(!1),[m,p]=y.useState(o),{data:f}=Xe({queryKey:["printer-status",t],queryFn:()=>ae.getPrinterStatus(t),enabled:!!t}),{data:g}=Xe({queryKey:["spool-assignments",t],queryFn:()=>ae.getAssignments(t),enabled:!!t}),{loadedFilaments:w,filamentComparison:b,hasTypeMismatch:x,hasColorMismatch:S}=tse(e,f,n),k=y.useMemo(()=>{const L=new Map;for(const Z of g||[]){const ne=Z.ams_id===255,Y=Qg(Z.ams_id,Z.tray_id,ne);L.set(Y,Z.spool?.cost_per_kg??null)}return L},[g]),C=y.useMemo(()=>{const L=new Map;for(const Z of g||[]){const ne=Z.ams_id===255,Y=Qg(Z.ams_id,Z.tray_id,ne),le=Z.spool;if(!le){L.set(Y,null);continue}L.set(Y,Math.max(0,Math.round((le.label_weight??0)-(le.weight_used??0))))}return L},[g]),P=y.useMemo(()=>{let L=0;for(const Z of b){const ne=Z.loaded?.globalTrayId;if(ne==null)continue;const le=k.get(ne)??null??s;le>0&&(L+=Z.used_grams/1e3*le)}return L},[b,k,s]),T=y.useMemo(()=>Array.from(k.values()).some(L=>L!=null&&L>0),[k]),A=e?.filaments&&e.filaments.length>0,F=e?.filaments?.some(L=>L.nozzle_id!=null)??!1,_=f?.fila_switch?.installed===!0,M=L=>{const Z=f?.fila_switch;if(!Z?.installed)return null;const ne=Z.in_slots.indexOf(L);return ne<0?null:Z.out_extruders[ne]??null};if(!A||!f)return null;const H=x?"#f97316":S?"#facc15":"#00ae42",I=(L,Z)=>{if(L>0)if(Z===""){const ne={...n};delete ne[L],a(ne)}else a({...n,[L]:parseInt(Z,10)})},z=async()=>{u(!0);try{await ae.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(Mw,{className:"w-4 h-4",fill:H,stroke:"none"}),r.jsx("span",{children:l("printModal.filamentMapping")}),x?r.jsx("span",{className:"text-xs text-orange-400",children:"(Type not found)"}):S?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(Zo,{className:"w-4 h-4 ml-auto"}):r.jsx(Ln,{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:z,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(tr,{className:`w-3 h-3 ${d?"animate-spin":""}`}),r.jsx("span",{children:"Re-read"})]})]}),b.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} - ${fc(L.color)}`,children:r.jsx(Mw,{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:ne=>I(L.slot_id||0,ne.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(ne=>L.nozzle_id==null||_||ne.extruderId===L.nozzle_id).map(ne=>{const Y=C.get(ne.globalTrayId),le=Y!=null?l("printModal.slotRemainingShort",{grams:Y,defaultValue:` - ${Y}g left`}):"",ue=_?M(ne.globalTrayId):null,de=ue==null?"":` [${l(ue===1?"printModal.leftNozzle":"printModal.rightNozzle")}]`;return r.jsxs("option",{value:ne.globalTrayId,className:"bg-bambu-dark text-white",children:[ne.label,": ",ne.traySubBrands||ne.type," (",ne.colorName,")",le,de]},ne.globalTrayId)})]}),L.status==="match"?r.jsx(Ar,{className:"w-3 h-3 text-bambu-green"}):L.status==="type_only"?r.jsx("span",{title:"Same type, different color",children:r.jsx(Nn,{className:"w-3 h-3 text-yellow-400"})}):r.jsx("span",{title:"Filament type not loaded",children:r.jsx(Nn,{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 B7e({filamentReqs:t,availableFilaments:e,overrides:n,onChange:a,forceColorMatch:i,onForceColorMatchChange:s}){const{t:o}=_t(),l=y.useMemo(()=>{const u={};for(const m of e){const p=wP(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[wP(u.type)]||[],g=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} - ${fc(u.color)}`,children:r.jsx(Mw,{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:g.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," (",fc(u.color),")"]}),g.map((w,b)=>r.jsxs("option",{value:`${w.type}|${w.color}`,className:"bg-bambu-dark text-white",children:[w.tray_sub_brands||w.type," (",fc(w.color),")"]},`${w.type}-${w.color}-${w.tray_sub_brands}-${b}`))]}),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(fs,{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(ES,{className:"w-3 h-3"}),o("printModal.forceColorMatch")]})]},u.slot_id)})})]})}function H7e({plates:t,isMultiPlate:e,selectedPlates:n,onToggle:a,onSelectAll:i,onDeselectAll:s,multiSelect:o}){const{t:l}=_t();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(ca,{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(Nn,{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(gs,{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:La(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(ca,{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?` • ${cs(d.print_time_seconds)}`:""]})]}),!o&&u&&r.jsx(Ar,{className:"w-4 h-4 text-bambu-green flex-shrink-0"})]},d.index)})})]})}const q7e=new Set(["IDLE","FINISH","FAILED"]);function $7e({printerResult:t,filamentReqs:e,onUpdateConfig:n}){const a=tn(),[i,s]=y.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 ae.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)),b=a.getQueryData(["settings"]);p=F7e(d,t.loadedFilaments,w,b?.prefer_lowest_filament)}let g="mismatch";if(p){const w=p.type?.toUpperCase()===d.type?.toUpperCase(),b=Ia(p.color)===Ia(d.color)||md(p.color,d.color);w&&b?g="match":w&&(g="type_only")}return{req:d,loaded:p,status:g,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(tr,{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} - ${fc(d.color)}`,children:r.jsx(Mw,{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:g=>o(d.slot_id||0,g.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 --"}),ese(t.loadedFilaments,d.nozzle_id).map(g=>r.jsxs("option",{value:g.globalTrayId,className:"bg-bambu-dark text-white",children:[g.label,": ",g.traySubBrands||g.type," (",g.colorName,")"]},g.globalTrayId))]}),m==="match"?r.jsx(Ar,{className:"w-3 h-3 text-bambu-green"}):m==="type_only"?r.jsx("span",{title:"Same type, different color",children:r.jsx(Nn,{className:"w-3 h-3 text-yellow-400"})}):r.jsx("span",{title:"Filament type not loaded",children:r.jsx(Nn,{className:"w-3 h-3 text-orange-400"})})]},f))]})}function V7e({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:g,targetLocation:w,onTargetLocationChange:b,slicedForModel:x}){const[S,k]=y.useState(!1),C=s?t:t.filter(oe=>oe.is_active),P=rf({queries:C.map(oe=>({queryKey:["printerStatus",oe.id],queryFn:()=>ae.getPrinterStatus(oe.id),staleTime:5e3}))}),T=y.useMemo(()=>{const oe=new Map;return C.forEach((me,pe)=>{const we=P[pe];we?.data&&oe.set(me.id,we.data)}),oe},[C,P]),A=oe=>{const me=T.get(oe);return me?me.connected?!q7e.has(me.state??""):!0:!1},F=oe=>{const me=T.get(oe);if(!me)return null;if(!me.connected)return"Offline";const pe=me.state;return pe?pe==="RUNNING"?me.stg_cur_name||"Printing":pe==="PREPARE"?"Preparing":pe==="PAUSE"?"Paused":pe==="IDLE"?"Idle":pe==="FINISH"?"Finished":pe==="FAILED"?"Failed":pe:null},_=y.useMemo(()=>{if(m!=="printer"||!x||S)return C;const oe=C.filter(me=>me.model===x);return oe.length>0?oe:C},[C,m,x,S]),M=C.length-_.length,H=y.useMemo(()=>{const oe=C.map(me=>me.model).filter(me=>!!me);return[...new Set(oe)].sort()},[C]),I=y.useMemo(()=>{if(!f)return[];const oe=C.filter(me=>me.model===f&&me.location).map(me=>me.location).filter(me=>!!me);return[...new Set(oe)].sort()},[C,f]),z=p&&g&&H.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(ft,{className:"w-6 h-6 text-bambu-green animate-spin"})});if(_.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=oe=>{o&&A(oe)||(i?e.includes(oe)?n(e.filter(me=>me!==oe)):n([...e,oe]):n([oe]))},ne=()=>{const oe=o?_.filter(me=>!A(me.id)):_;n(oe.map(me=>me.id))},Y=()=>{n([])},le=(oe,me,pe)=>{pe.stopPropagation(),!(!d||!u)&&(me?d(oe):u(oe,{useDefault:!0,manualMappings:{},autoConfigured:!1}))},ue=oe=>e.includes(oe),de=e.length,Q=oe=>l?.find(me=>me.printerId===oe);return r.jsxs("div",{className:"space-y-2 mb-6",children:[z&&r.jsxs("div",{className:"flex gap-2 mb-4",children:[r.jsxs("button",{type:"button",onClick:()=>{p("printer"),g(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(hr,{className:"w-4 h-4"}),r.jsx("span",{className:"text-sm",children:"Specific Printer"})]}),r.jsxs("button",{type:"button",onClick:()=>{p("model"),n([]);const oe=x&&H.includes(x)?x:H[0];g(oe)},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(bm,{className:"w-4 h-4"}),r.jsxs("span",{className:"text-sm",children:["Any ",x||"Model"]})]})]}),m==="model"&&z&&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:oe=>{g(oe.target.value||null),b&&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 text-sm",children:[r.jsx("option",{value:"",children:"Select a model..."}),H.map(oe=>r.jsx("option",{value:oe,children:oe},oe))]})]}),f&&I.length>0&&b&&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:oe=>b(oe.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(oe=>r.jsx("option",{value:oe,children:oe},oe))]})]}),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&&_.length>1&&r.jsxs("div",{className:"flex items-center justify-between text-xs text-bambu-gray mb-2",children:[r.jsx("span",{children:de===0?"Select printers":`${de} printer${de!==1?"s":""} selected`}),r.jsxs("div",{className:"flex gap-2",children:[de<_.length&&r.jsx("button",{type:"button",onClick:ne,className:"text-bambu-green hover:text-bambu-green/80 transition-colors",children:"Select all"}),de>0&&r.jsx("button",{type:"button",onClick:Y,className:"text-bambu-gray hover:text-white transition-colors",children:"Clear"})]})]}),m==="printer"&&_.map(oe=>{const me=ue(oe.id),pe=Q(oe.id),we=pe&&!pe.config.useDefault,$=A(oe.id),J=o&&$,j=F(oe.id);return r.jsxs("div",{children:[r.jsxs("button",{type:"button",onClick:()=>Z(oe.id),disabled:J,className:`w-full flex items-center gap-3 p-3 rounded-lg border transition-colors ${J?"border-bambu-dark-tertiary bg-bambu-dark opacity-50 cursor-not-allowed":me?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary bg-bambu-dark hover:border-bambu-gray"} ${oe.is_active?"":"opacity-60"}`,children:[r.jsx("div",{className:`p-2 rounded-lg ${J?"bg-bambu-dark-tertiary":me?"bg-bambu-green/20":"bg-bambu-dark-tertiary"}`,children:r.jsx(hr,{className:`w-5 h-5 ${J?"text-bambu-gray/50":me?"text-bambu-green":"text-bambu-gray"}`})}),r.jsxs("div",{className:"text-left flex-1",children:[r.jsxs("p",{className:`font-medium ${J?"text-bambu-gray":"text-white"}`,children:[oe.name,!oe.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:[oe.model||"Unknown model"," • ",oe.ip_address]})]}),j&&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:j}),i&&r.jsx("div",{className:`w-5 h-5 rounded border-2 flex items-center justify-center transition-colors ${J?"border-bambu-gray/30":me?"bg-bambu-green border-bambu-green":"border-bambu-gray/50"}`,children:me&&r.jsx(Ar,{className:"w-3 h-3 text-white"})})]}),me&&L&&pe&&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:E=>E.stopPropagation(),children:[r.jsx("input",{type:"checkbox",checked:we,onChange:E=>le(oe.id,E.target.checked,E),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 ${pe.matchStatus==="full"?"text-bambu-green":pe.matchStatus==="partial"?"text-yellow-400":"text-orange-400"}`,children:["(",pe.exactMatches,"/",pe.totalSlots," matched)"]}),pe.isLoading&&r.jsx(tr,{className:"w-3 h-3 text-bambu-gray animate-spin"}),we&&r.jsxs("button",{type:"button",onClick:E=>{E.stopPropagation(),d(oe.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(YZ,{className:"w-3 h-3"}),"Auto"]})]}),we&&r.jsx($7e,{printerResult:pe,filamentReqs:c.filaments,onUpdateConfig:E=>u(oe.id,E)})]})]},oe.id)}),m==="printer"&&M>0&&!S&&r.jsxs("button",{type:"button",onClick:()=>k(!0),className:"text-xs text-bambu-gray hover:text-white transition-colors mt-2 flex items-center gap-1",children:[r.jsx(Nn,{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"&&S&&x&&r.jsx("button",{type:"button",onClick:()=>k(!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"&&de===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 G7e=[{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 W7e({options:t,onChange:e,defaultExpanded:n=!1}){const[a,i]=y.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(xy,{className:"w-4 h-4"}),r.jsx("span",{children:"Print Options"}),a?r.jsx(Zo,{className:"w-4 h-4 ml-auto"}):r.jsx(Ln,{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:G7e.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 K7e({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}=_t(),[d,u]=y.useState(""),[m,p]=y.useState(""),[f,g]=y.useState(!0),[w,b]=y.useState(!0),x=y.useRef(null),S=y.useRef(!1);y.useEffect(()=>{if(t.scheduleType!=="scheduled"){S.current=!1;return}if(!S.current){S.current=!0;let _;t.scheduledTime?(_=new Date(t.scheduledTime),isNaN(_.getTime())&&(_=new Date,_.setHours(_.getHours()+1,0,0,0))):(_=new Date,_.setHours(_.getHours()+1,0,0,0),e({...t,scheduledTime:eL(_)})),u(JF(_,n)),p(k6(_,a)),g(!0),b(!0)}},[t.scheduleType,t.scheduledTime,n,a,e,t]);const k=_=>{e({...t,scheduleType:_})},C=(_,M)=>{const H=Zve(_,n),I=Jve(M);g(!!H),b(!!I),H&&I&&(H.setHours(I.hours,I.minutes,0,0),H>new Date&&e({...t,scheduledTime:eL(H)}))},P=_=>{u(_),C(_,m)},T=_=>{p(_),C(d,_)},A=_=>{const M=_.target.value;if(M){const H=new Date(M);isNaN(H.getTime())||(u(JF(H,n)),p(k6(H,a)),g(!0),b(!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:()=>k("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:()=>k("scheduled"),children:[r.jsx(wa,{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:()=>k("manual"),children:[r.jsx(UZ,{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:_=>P(_.target.value),placeholder:Qve(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(wa,{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:_=>T(_.target.value),placeholder:Yve(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:_=>e({...t,requirePreviousSuccess:_.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:_=>e({...t,autoOffAfter:_.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(_u,{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:_=>e({...t,gcodeInjection:_.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(Ky,{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:_=>e({...t,staggerEnabled:_.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(ca,{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:_=>e({...t,staggerGroupSize:Math.max(1,parseInt(_.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:_=>e({...t,staggerIntervalMinutes:Math.max(1,parseInt(_.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 _=Math.ceil(o/t.staggerGroupSize),M=o%t.staggerGroupSize,H=(_-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:_,size:t.staggerGroupSize,interval:t.staggerIntervalMinutes}),M!==0&&t.staggerGroupSize1?` (${c("printModal.staggerTotal","total: {{minutes}} min",{minutes:H})})`:""]})})()]})]}),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 ed={bed_levelling:!0,flow_cali:!1,vibration_cali:!0,layer_inspect:!1,timelapse:!1},h3={scheduleType:"asap",scheduledTime:"",requirePreviousSuccess:!1,autoOffAfter:!1,gcodeInjection:!1,staggerEnabled:!1,staggerGroupSize:2,staggerIntervalMinutes:5};function bc({mode:t,archiveId:e,libraryFileId:n,archiveName:a,queueItem:i,initialSelectedPrinterIds:s,onClose:o,onSuccess:l,projectId:c,cleanupLibraryAfterDispatch:d}){const{t:u}=_t(),m=tn(),{showToast:p}=on(),{hasPermission:f}=dr(),g=!!n&&!e,[w,b]=y.useState(()=>t==="edit-queue-item"&&i?.printer_id?[i.printer_id]:s?.length?s:[]),[x,S]=y.useState(()=>t==="edit-queue-item"&&i?.plate_id!=null?new Set([i.plate_id]):new Set),k=x.size===1?[...x][0]:null,[C,P]=y.useState(1),[T,A]=y.useState(()=>t==="edit-queue-item"&&i?{bed_levelling:i.bed_levelling??ed.bed_levelling,flow_cali:i.flow_cali??ed.flow_cali,vibration_cali:i.vibration_cali??ed.vibration_cali,layer_inspect:i.layer_inspect??ed.layer_inspect,timelapse:i.timelapse??ed.timelapse}:ed),[F,_]=y.useState(()=>{if(t==="edit-queue-item"&&i){let ut="asap";i.manual_start?ut="manual":i.scheduled_time&&!$K(i.scheduled_time)&&(ut="scheduled");let Ct="";if(i.scheduled_time&&!$K(i.scheduled_time)){const Le=Yn(i.scheduled_time)??new Date;Ct=eL(Le)}return{scheduleType:ut,scheduledTime:Ct,requirePreviousSuccess:i.require_previous_success,autoOffAfter:i.auto_off_after,gcodeInjection:i.gcode_injection??!1,staggerEnabled:!1,staggerGroupSize:h3.staggerGroupSize,staggerIntervalMinutes:h3.staggerIntervalMinutes}}return h3}),[M,H]=y.useState(()=>{if(t==="edit-queue-item"&&i?.ams_mapping&&Array.isArray(i.ams_mapping)){const ut={};return i.ams_mapping.forEach((Ct,Le)=>{Ct!==-1&&(ut[Le+1]=Ct)}),ut}return{}}),[I,z]=y.useState({}),[L,Z]=y.useState(()=>t==="edit-queue-item"&&i?.target_model?"model":"printer"),[ne,Y]=y.useState(()=>t==="edit-queue-item"&&i?.target_model?i.target_model:null),[le,ue]=y.useState(()=>t==="edit-queue-item"&&i?.target_location?i.target_location:null),[de,Q]=y.useState(()=>{if(t==="edit-queue-item"&&i?.filament_overrides){const ut={};for(const Ct of i.filament_overrides)ut[Ct.slot_id]={type:Ct.type,color:Ct.color};return ut}return{}}),[oe,me]=y.useState(()=>{if(t==="edit-queue-item"&&i?.filament_overrides){const ut={};for(const Ct of i.filament_overrides)ut[Ct.slot_id]=Ct.force_color_match===!0;return ut}return{}}),[pe]=y.useState(()=>t==="edit-queue-item"&&i?.printer_id?[i.printer_id]:[]),[we]=y.useState(()=>t==="edit-queue-item"&&i?i.plate_id:null),[$,J]=y.useState(!1),[j,E]=y.useState({current:0,total:0}),[B,W]=y.useState(null),[O,ie]=y.useState(new Set),U=w.length,G=w.length>0?w[0]:null,{data:K}=Xe({queryKey:["settings"],queryFn:ae.getSettings}),X=y.useRef(!1);y.useEffect(()=>{!K||X.current||t==="edit-queue-item"||(X.current=!0,A({bed_levelling:K.default_bed_levelling??ed.bed_levelling,flow_cali:K.default_flow_cali??ed.flow_cali,vibration_cali:K.default_vibration_cali??ed.vibration_cali,layer_inspect:K.default_layer_inspect??ed.layer_inspect,timelapse:K.default_timelapse??ed.timelapse}))},[K,t]);const se=y.useRef(!1);y.useEffect(()=>{!K||se.current||t==="edit-queue-item"||(se.current=!0,_(ut=>({...ut,staggerGroupSize:K.stagger_group_size??ut.staggerGroupSize,staggerIntervalMinutes:K.stagger_interval_minutes??ut.staggerIntervalMinutes})))},[K,t]);const te=Ho(K?.currency||"USD"),fe=K?.default_filament_cost??0,{data:ce,isLoading:he}=Xe({queryKey:["printers"],queryFn:ae.getPrinters}),{data:q}=Xe({queryKey:["spool-assignments"],queryFn:()=>ae.getAssignments(),staleTime:30*1e3,enabled:(t==="reprint"||t==="add-to-queue")&&L==="printer"||g&&t==="reprint"}),{data:R}=Xe({queryKey:["archive",e],queryFn:()=>ae.getArchive(e),enabled:!!e&&!g}),{data:re}=Xe({queryKey:["library-file",n],queryFn:()=>ae.getLibraryFile(n),enabled:g&&!!n}),be=R?.sliced_for_model||re?.sliced_for_model||null,{data:ye,isError:_e}=Xe({queryKey:["archive-plates",e],queryFn:()=>ae.getArchivePlates(e),enabled:!!e&&!g,retry:!1}),{data:xe}=Xe({queryKey:["library-file-plates",n],queryFn:()=>ae.getLibraryFilePlates(n),enabled:g&&!!n}),ge=g?xe:ye,{data:Me,isError:Be}=Xe({queryKey:["archive-filaments",e,k],queryFn:()=>ae.getArchiveFilamentRequirements(e,k??void 0),enabled:!!e&&!g&&(k!==null||!ge?.is_multi_plate),retry:!1}),{data:Fe}=Xe({queryKey:["library-file-filaments",n,k],queryFn:()=>ae.getLibraryFileFilamentRequirements(n,k??void 0),enabled:g&&!!n&&(k!==null||!ge?.is_multi_plate)}),Oe=!g&&(_e||Be),Re=g?Fe:Me,We=y.useMemo(()=>{if(!(k===null||!ge?.plates?.length))return ge.plates.find(ut=>ut.index===k)?.name||void 0},[ge,k]),{data:ze}=Xe({queryKey:["available-filaments",ne,le],queryFn:()=>ae.getAvailableFilaments(ne,le??void 0),enabled:L==="model"&&!!ne}),{data:st}=Xe({queryKey:["printer-status",G],queryFn:()=>ae.getPrinterStatus(G),enabled:!!G}),{amsMapping:Ee}=tse(Re,st,M,K?.prefer_lowest_filament),it=O7e(w,ce,Re,M,I,z,K?.prefer_lowest_filament);y.useEffect(()=>{ge?.plates&&ge.plates.length>=1&&x.size===0&&S(new Set([ge.plates[0].index]))},[ge,x.size]),y.useEffect(()=>{if(t==="edit-queue-item")return;const ut=ce?.filter(Ct=>Ct.is_active)||[];ut.length===1&&w.length===0&&b([ut[0].id])},[t,ce,w.length]),y.useEffect(()=>{t==="edit-queue-item"?(JSON.stringify(w.sort())!==JSON.stringify(pe.sort())||k!==we)&&(H({}),z({}),ie(new Set)):(H({}),z({}),ie(new Set))},[t,w,k,pe,we]);const[Ce,Ze]=y.useState(ne),[Ie,ke]=y.useState(k);y.useEffect(()=>{(ne!==Ce||k!==Ie)&&(Ze(ne),ke(k),(t!=="edit-queue-item"||Ce!==null)&&(Q({}),me({})))},[ne,k,Ce,Ie,t]),y.useEffect(()=>{if(!K?.per_printer_mapping_expanded||w.length<=1)return;const ut=w.filter(Ct=>{if(O.has(Ct))return!1;const Le=it.printerResults.find(Ae=>Ae.printerId===Ct);return Le&&Le.status&&!Le.isLoading});ut.length>0&&(ie(Ct=>{const Le=new Set(Ct);return ut.forEach(Ae=>Le.add(Ae)),Le}),ut.forEach(Ct=>{it.autoConfigurePrinter(Ct)}))},[K?.per_printer_mapping_expanded,w,O,it]),y.useEffect(()=>{const ut=Ct=>{Ct.key==="Escape"&&!$&&o()};return window.addEventListener("keydown",ut),()=>window.removeEventListener("keydown",ut)},[o,$]);const Ve=ge?.is_multi_plate??!1,rt=ge?.plates??[],Qe=y.useMemo(()=>{const ut=new Map;return q&&q.forEach(Ct=>{const Le=Ct.ams_id===255,Ae=Qg(Ct.ams_id,Ct.tray_id,Le),Ge=ut.get(Ct.printer_id)??new Map;Ge.set(Ae,Ct),ut.set(Ct.printer_id,Ge)}),ut},[q]),Te=y.useMemo(()=>{if(!B||B.length===0)return"";const ut=B.map(Ct=>u("printModal.insufficientFilamentLine",{printer:Ct.printerName,slot:Ct.slotLabel,required:Math.round(Ct.requiredGrams),remaining:Math.round(Ct.remainingGrams)}));return[u("printModal.insufficientFilamentMessage"),...ut].join(` `)},[B,u]),tt=lt({mutationFn:ut=>ae.addToQueue(ut)}),ot=lt({mutationFn:ut=>ae.updateQueueItem(i.id,ut),onSuccess:()=>{m.invalidateQueries({queryKey:["queue"]}),p("Queue item updated"),l?.(),o()},onError:ut=>{p(ut.message||"Failed to update queue item","error")}}),Tt=F.staggerEnabled&&w.length>1,Ut=async(ut,Ct)=>{if(ut?.preventDefault(),!Ct?.skipFilamentCheck&&!K?.disable_filament_warnings&&(t==="reprint"||t==="add-to-queue")&&L==="printer"){const Ye=[],nt=Re?.filaments??[];if(nt.length>0&&Qe.size>0){const at=(et,vt)=>!Number.isFinite(et)||et<=0||!Number.isFinite(vt)||vt<0?null:Math.max(0,et-vt);for(const et of w){const vt=w.length>1?it.getFinalMapping(et):Ee;if(!vt)continue;const wt=w.length>1?it.printerResults.find(qe=>qe.printerId===et)?.status:st,Ue=m_(wt),He=new Map(Ue.map(qe=>[qe.globalTrayId,qe.label])),Dt=Qe.get(et),Rt=ce?.find(qe=>qe.id===et)?.name??`Printer ${et}`;Dt&&nt.forEach(qe=>{if(!qe.slot_id||qe.slot_id<=0)return;const Ke=vt[qe.slot_id-1];if(!Number.isFinite(Ke)||Ke<0)return;const Qt=Dt.get(Ke)?.spool;if(!Qt)return;const dn=at(Qt.label_weight,Qt.weight_used);dn!==null&&(dn>=qe.used_grams||Ye.push({printerName:Rt,slotLabel:He.get(Ke)??`Slot ${qe.slot_id}`,requiredGrams:qe.used_grams,remainingGrams:dn}))})}}if(Ye.length>0){W(Ye);return}}if(L==="printer"&&w.length===0){p("Please select at least one printer","error");return}if(L==="model"&&!ne){p("Please select a target printer model","error");return}J(!0);const Le=x.size>1?rt.filter(Ye=>x.has(Ye.index)):[null],Ae=L==="model"?Le.length:w.length*Le.length;E({current:0,total:Ae});const Ge={success:0,failed:0,errors:[]},Je=Ye=>{if(w.length>1){const nt=I[Ye];if(nt&&!nt.useDefault)return it.getFinalMapping(Ye)}return Ee},mt=(()=>{const Ye=[];if(Re?.filaments)for(const nt of Re.filaments){const at=de[nt.slot_id],et=oe[nt.slot_id]??!1,vt=at?.type??nt.type,wt=at?.color??nt.color;(at||et)&&Ye.push({slot_id:nt.slot_id,type:vt,color:wt,color_name:fc(wt),force_color_match:et})}else for(const[nt,{type:at,color:et}]of Object.entries(de)){const vt=parseInt(nt,10),wt=oe[vt]??!1;Ye.push({slot_id:vt,type:at,color:et,color_name:fc(et),force_color_match:wt})}return Ye.length>0?Ye:void 0})(),Ne=(Ye,nt)=>({printer_id:L==="printer"?Ye:null,target_model:L==="model"?ne:null,target_location:L==="model"?le:null,filament_overrides:L==="model"?mt:void 0,archive_id:g?void 0:e,library_file_id:g?n:void 0,require_previous_success:F.requirePreviousSuccess,auto_off_after:F.autoOffAfter,gcode_injection:F.gcodeInjection,manual_start:F.scheduleType==="manual",ams_mapping:Ye?Je(Ye):void 0,plate_id:nt!==void 0?nt:k,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"),J(!1);return}let Ye=0;for(const nt of Le){Ye++,E({current:Ye,total:Ae});const at=nt?nt.index:k;try{if(t==="edit-queue-item"&&!nt){const et={printer_id:null,target_model:ne,target_location:le,filament_overrides:mt||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:at,scheduled_time:F.scheduleType==="scheduled"&&F.scheduledTime?new Date(F.scheduledTime).toISOString():null,...T};await ot.mutateAsync(et)}else{const et=Ne(null,at);Zt>1&&(et.quantity=Zt),await tt.mutateAsync(et)}Ge.success++}catch(et){Ge.failed++;const vt=nt?nt.name||`Plate ${nt.index}`:"";Ge.errors.push(vt?`${vt}: ${et.message}`:et.message)}}}else{const Ye=F.staggerEnabled&&(t==="add-to-queue"||t==="reprint")&&w.length>1,nt=Ye?F.scheduleType==="scheduled"&&F.scheduledTime?new Date(F.scheduledTime).getTime():Date.now():0;let at=0;for(const et of Le){const vt=et?et.index:k;for(let wt=0;wt1){const Dt=Ne(Ue,vt);Dt.quantity=Zt-1,await tt.mutateAsync(Dt)}}else if(t==="edit-queue-item"&&at===1){const He=Je(Ue),Dt={printer_id:Ue,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:He,plate_id:vt,scheduled_time:F.scheduleType==="scheduled"&&F.scheduledTime?new Date(F.scheduledTime).toISOString():null,...T};await ot.mutateAsync(Dt)}else{const He=Ne(Ue,vt);if(Zt>1&&(He.quantity=Zt),Ye){const Dt=Math.floor(wt/F.staggerGroupSize);if(Dt>0){const Rt=Dt*F.staggerIntervalMinutes*6e4;He.scheduled_time=new Date(nt+Rt).toISOString()}}await tt.mutateAsync(He)}Ge.success++}catch(He){Ge.failed++;const Dt=ce?.find(Ke=>Ke.id===Ue)?.name||`Printer ${Ue}`,Rt=et?et.name||`Plate ${et.index}`:"",qe=Rt?`${Dt} (${Rt})`:Dt;Ge.errors.push(`${qe}: ${He.message}`)}}}}J(!1),Ge.failed===0?(t==="reprint"&&Tt?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 ${ne}`: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"]}))},bt=$||ot.isPending,Wt=y.useMemo(()=>!(bt||L==="printer"&&w.length===0||L==="model"&&!ne||L==="model"&&t==="reprint"||Ve&&x.size===0),[w.length,L,ne,t,Ve,x.size,bt]),Zt=L==="printer"&&w.length>1?1:C,cn=(()=>{const ut=w.length;if(t==="reprint"){const Ct=Tt&&ut>1;let Le=Ct?u("printModal.staggerToPrinters",{count:ut,defaultValue:"Stagger to {{count}} printers"}):ut>1?u("queue.printToPrinters",{count:ut}):u("queue.print");return Zt>1&&(Le=`${Le} ×${Zt}`),{title:u(g?"queue.print":"queue.reprint"),icon:hr,submitText:Le,submitIcon:Ct?wa:hr,loadingText:j.total>1?u("queue.sendingProgress",{current:j.current,total:j.total}):u("queue.sending")}}if(t==="add-to-queue"){let Ct=u("queue.addToQueue");return x.size>1?Ct=u("queue.queueSelectedPlates",{count:x.size}):ut>1&&(Ct=u("queue.queueToPrinters",{count:ut})),Zt>1&&(Ct=`${Ct} ×${Zt}`),{title:u("queue.schedulePrint"),icon:wa,submitText:Ct,submitIcon:wa,loadingText:j.total>1?u("queue.addingProgress",{current:j.current,total:j.total}):u("queue.adding")}}return{title:u("queue.editQueueItem"),icon:mi,submitText:u("common.save"),submitIcon:mi,loadingText:j.total>1?u("queue.savingProgress",{current:j.current,total:j.total}):u("common.saving")}})(),ct=cn.icon,kt=cn.submitIcon,Nt=G&&x.size<=1&&(g||(Ve?k!==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(At,{className:"w-full max-w-2xl max-h-[90vh] overflow-y-auto",onClick:ut=>ut.stopPropagation(),children:r.jsxs(Et,{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(ct,{className:"w-5 h-5 text-bambu-green"}),r.jsx("h2",{className:"text-lg font-semibold text-white",children:cn.title})]}),r.jsx(je,{variant:"ghost",size:"sm",onClick:o,disabled:$,children:r.jsx(Vt,{className:"w-5 h-5"})})]}),r.jsxs("form",{onSubmit:Ut,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(ut=>ut.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(H7e,{plates:rt,isMultiPlate:Ve,selectedPlates:x,onToggle:ut=>{S(Ct=>{const Le=new Set(Ct);return t==="add-to-queue"?Le.has(ut)?Le.delete(ut):Le.add(ut):(Le.clear(),Le.add(ut)),Le})},onSelectAll:t==="add-to-queue"?()=>S(new Set(rt.map(ut=>ut.index))):void 0,onDeselectAll:t==="add-to-queue"?()=>S(new Set):void 0,multiSelect:t==="add-to-queue"}),!s?.length&&r.jsx(V7e,{printers:ce||[],selectedPrinterIds:w,onMultiSelect:b,isLoading:he,allowMultiple:!0,showInactive:t==="edit-queue-item",disableBusy:t==="reprint",printerMappingResults:it.printerResults,filamentReqs:Re,onAutoConfigurePrinter:it.autoConfigurePrinter,onUpdatePrinterConfig:it.updatePrinterConfig,assignmentMode:t==="reprint"?"printer":L,onAssignmentModeChange:t!=="reprint"?Z:void 0,targetModel:ne,onTargetModelChange:t!=="reprint"?Y:void 0,targetLocation:le,onTargetLocationChange:t!=="reprint"?ue:void 0,slicedForModel:be}),L==="model"&&ne&&Re&&ze&&ze.length>0&&r.jsx(B7e,{filamentReqs:Re,availableFilaments:ze,overrides:de,onChange:Q,forceColorMatch:oe,onForceColorMatchChange:(ut,Ct)=>me(Le=>({...Le,[ut]:Ct}))}),be&&L==="printer"&&w.length===1&&(()=>{const ut=ce?.find(Ct=>Ct.id===w[0]);return ut&&ut.model&&be!==ut.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(Nn,{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 ",ut.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."})]}),Nt&&!Oe&&w.length===1&&r.jsx(U7e,{printerId:G,filamentReqs:Re,manualMappings:M,onManualMappingChange:H,defaultExpanded:!!s?.length||(K?.per_printer_mapping_expanded??!1),currencySymbol:te,defaultCostPerKg:fe}),(t==="reprint"||U>0||L==="model"&&ne)&&r.jsx(W7e,{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:ut=>P(Math.max(1,Math.min(999,parseInt(ut.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:ut=>_({...F,staggerEnabled:ut.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(ca,{className:"w-3.5 h-3.5"}),u("printModal.staggerPrinterStarts","Stagger printer starts")]})]}),F.staggerEnabled&&(()=>{const ut=F.staggerGroupSize,Ct=F.staggerIntervalMinutes,Le=Math.ceil(w.length/ut),Ae=(Le-1)*Ct;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:Le,size:ut,interval:Ct}),Le>1?` (${u("printModal.staggerTotal","total: {{minutes}} min",{minutes:Ae})})`:""]})})()]}),t!=="reprint"&&r.jsx(K7e,{options:F,onChange:_,dateFormat:K?.date_format||"system",timeFormat:K?.time_format||"system",canControlPrinter:f("printers:control"),showStagger:t==="add-to-queue"&&L==="printer"&&w.length>1,printerCount:w.length,hasGcodeSnippets:!!K?.gcode_snippets}),t==="reprint"&&!!K?.gcode_snippets&&Zt>1&&r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("input",{type:"checkbox",id:"gcodeInjectionReprint",checked:F.gcodeInjection,onChange:ut=>_({...F,gcodeInjection:ut.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(Ky,{className:"w-3.5 h-3.5"}),u("printModal.gcodeInjection","Inject auto-print G-code")]})]}),ot.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:ot.error?.message||"Failed to complete operation"}),r.jsxs("div",{className:`flex gap-3 ${t==="reprint"?"":"pt-2"}`,children:[r.jsx(je,{type:"button",variant:"secondary",onClick:o,className:"flex-1",disabled:$,children:"Cancel"}),r.jsx(je,{type:"submit",disabled:!Wt,className:"flex-1",children:bt?r.jsxs(r.Fragment,{children:[r.jsx(ft,{className:"w-4 h-4 animate-spin"}),cn.loadingText]}):r.jsxs(r.Fragment,{children:[r.jsx(kt,{className:"w-4 h-4"}),cn.submitText]})})]})]})]})}),B&&B.length>0&&r.jsx(wn,{title:u("printModal.insufficientFilamentTitle"),message:Te,confirmText:u("printModal.printAnyway"),cancelText:u("common.cancel"),variant:"warning",onConfirm:()=>{W(null),Ut(void 0,{skipFilamentCheck:!0})},onCancel:()=>W(null)})]})}function WK({value:t}){const{t:e}=_t(),[n,a]=y.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(Ar,{className:"w-3.5 h-3.5 text-bambu-green"}):r.jsx(Ti,{className:"w-3.5 h-3.5"})})}function Q7e({printer:t,status:e,totalPrintHours:n,onClose:a}){const{t:i}=_t();y.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(WK,{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(WK,{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(xO,{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=Ree(e.wifi_signal);s.push({label:i("printers.wifiSignalLabel"),value:r.jsxs("span",{className:"flex items-center gap-2",children:[r.jsx(VZ,{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:Dg(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(At,{className:"w-full max-w-md",onClick:o=>o.stopPropagation(),children:r.jsxs(Et,{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(Vt,{className:"w-5 h-5 text-bambu-gray"})})]}),r.jsx("div",{className:"flex justify-center mb-4",children:r.jsx("img",{src:Lee(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 Y7e(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 f3({trayColor:t,trayType:e,isEmpty:n,emptyKind:a,slotNumber:i}){const s=a==="reset"?"#3d3d3d":"#666";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?s:"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&&Y7e(t)?"#000":"#fff"},children:i})})}function m5({summary:t,children:e,defaultOpen:n=!1,className:a="",summaryClassName:i="",open:s,onToggle:o}){const[l,c]=y.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(Ln,{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})]})}const KK=240,QK=320;function g3(t){return(t??.02).toFixed(3)}function YK({side:t}){const{mode:e}=ob(),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 rse(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 ase(t,e){return t?t.startsWith("HH")?e("printers.nozzleHighFlow"):t.startsWith("HS")?e("printers.nozzleStandardFlow"):"":""}function ise({slot:t,index:e,activeStatus:n,filamentName:a,children:i}){const{t:s}=_t(),[o,l]=y.useState(!1),[c,d]=y.useState("top"),u=y.useRef(null),m=y.useRef(null),p=y.useRef(null),f=!t.nozzle_diameter&&!t.nozzle_type,g=t.stat===1;y.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)},b=()=>{p.current&&clearTimeout(p.current),p.current=setTimeout(()=>l(!1),100)};y.useEffect(()=>()=>{p.current&&clearTimeout(p.current)},[]);const x=jO(t.filament_color),S=rse(t.nozzle_type,s),k=ase(t.nozzle_type,s);return r.jsxs("div",{ref:u,className:"relative",onMouseEnter:w,onMouseLeave:b,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 6586197c0..c06ad3513 100644 --- a/static/index.html +++ b/static/index.html @@ -26,7 +26,7 @@ - +