diff --git a/CHANGELOG.md b/CHANGELOG.md index bc9380ccd..98884745e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,7 @@ All notable changes to Bambuddy will be documented in this file. - **Slicer Bundle (.bbscfg) import (#1712, reported by @IndividualGhost1905)** — Bundle import never delivered what users expected. BambuStudio's "Export Preset Bundle" only includes user-customised presets; system processes / filaments are deliberately excluded by BS. So a fresh-install user who only used stock processes (the common case) got back a bundle containing their printer + maybe four custom filaments + zero processes. Importing that bundle into Bambuddy and then opening the SliceModal flipped into bundle mode — which constrained the dropdowns to bundle contents only — and surfaced "no presets" for process, blocking slicing on STL (3MF still worked because the embedded process JSON bypasses the dropdown). The first round of #1712 (`d459b6ea`, 2026-05-XX) addressed cross-tier visibility / dedup / banner behaviour but didn't touch the bundle-mode dropdown trap. Investigating the second round made it clear the bundle import wasn't unlocking anything the existing tiers don't already cover — custom presets reach Bambuddy through Bambu Cloud sync, Orca Cloud sync, or Single Preset Import; standard presets come from the sidecar's `/profiles/bundled` route automatically — so bundle mode was a fourth code path delivering no unique value while gating users on a slot they couldn't populate. **What was removed.** Backend: `POST/GET/DELETE /slicer/bundles*` routes, `SliceRequest.bundle` field + `SliceBundleSpec` schema, the bundle-dispatch fork in `library.py::_run_slicer_with_fallback` (cross-class slice-all loop, normal slice branch, `_resolve_target_printer_model` short-circuit), the bundle-context query params on `GET /library/files/{id}/filament-requirements` and `GET /archives/{id}/filament-requirements`, the bundle-fingerprint key in `slice_preview.py`'s LRU cache (back to `(kind, source_id, plate_id, content_hash)`), `SlicerApiService.import_bundle/list_bundles/get_bundle/delete_bundle/slice_with_bundle`, the `BundleSummary` / `BundleNotFoundError` types. Frontend: `BundlePicker` + `BundleStringDropdown` components, `isBundleMode` state and every branch on it in `SliceModal.tsx`, `selectedBundleId` / `bundleProcessName` / `bundleFilamentNames` state, the bundle-mode auto-pick effect, the bundle dispatch shape in `buildSliceBody`, the `bundlesQuery` itself, `SlicerBundle` / `SliceBundleSpec` types, `listSlicerBundles` / `importSlicerBundle` / `deleteSlicerBundle` API methods. The bundle-derived path in `buildCompatibilityIndex` is also gone — the function now only takes the printer-model registry and returns `{bambuModelByShortCode}`. `presetCompatibility` keeps its two remaining paths: the slicer's own `compatible_printers` list on local-imported presets (authoritative when set) and the `@BBL ` name-based fallback against the printer-model registry. Tests: `TestBundleRoutes` / `TestBundleClientMethods` / `TestSliceWithBundle` / `TestBundleAwarePreview` / `TestBundleDispatchShape` classes deleted across `test_slicer_presets.py` / `test_slicer_api.py` / `test_slice_preview.py` / `test_slice_request_schema.py` / `test_library_slice_api.py`; the SliceModal's "Bundle tier" describe block and the bundle-only assertions in `slicerPrinterMatch.test.ts` deleted; `SlicerBundlesPanel.test.tsx` removed; `TestNozzleClassGuard` simplified (no more bundle vs preset request distinction). **What replaces the Settings panel.** `SlicerBundlesPanel` is kept under the same name and slot in `SettingsPage` but now renders a static notice (title: "Slicer Bundles (removed)") explaining the removal and pointing users at Single Preset Import / Bambu Cloud / Orca Cloud, with the slicer sidecar covering stock presets automatically. The notice is permanent and can be removed in a future cleanup. **i18n.** `settings.slicerBundles.*` block replaced with `settings.slicerBundlesRemoved.{title,description,alternatives}` translated across all 11 locales (de / en / es / fr / it / ja / ko / pt-BR / tr / zh-CN / zh-TW) per `feedback_translate_dont_fallback`. `slice.bundle` / `slice.bundleNone` / `slice.bundleAllRequired` keys removed across all locales. Parity check 5106 leaves × 11 locales green. **Migration.** Hard cutover, no automatic preset migration. Users who previously imported bundles will see them disappear from Settings → Slicer Bundles after this drops; their printer preset still lives on the sidecar bundle store but is no longer surfaced. Standard presets from the sidecar's BBL tree cover stock slicing; users who need their customs re-upload them via Single Preset Import or sync via Bambu Cloud / Orca Cloud. **Why this resolves #1712.** shaddowlink's failing path was: import bundle for H2D → bundle has 0 processes (BS-side limitation) → SliceModal flips into bundle mode → process dropdown empty → can't slice STL. Post-removal: same import isn't possible, but the cross-tier preset picker shows H2D processes from the sidecar's standard tier (which always had them — bundle mode was the thing hiding them), filtered by `@BBL H2D` compatibility. STL slicing works without any user action. **Tests:** full backend suite 5907/5907 green; ruff clean; frontend ESLint clean; `npm run build` clean; vitest 158 files / 2118 tests green; i18n parity 5106 leaves × 11 locales green. ### Added +- **Re-print / Schedule modal: cross-extruder AMS slot picks on dual-nozzle (#1722, reported by @privatsturm)** — On a dual-nozzle setup (e.g. H2D with AMS A+C wired to the left extruder and AMS B wired to the right), the per-filament slot dropdown in the Re-print and Schedule modals used to hide every slot whose extruder didn't match the filament's slicer-assigned nozzle. A filament the slicer had assigned to the left extruder would only let the user pick from A or C; a right-assigned filament could only pick from B. Users who'd intentionally loaded the required filament into the "other" AMS — for example, AMS B (right side) carrying a colour the slicer had planned to print on the left — couldn't select it, even though the printer can physically run that AMS through its wired extruder. Three slice-output diffs (BambuStudio Desktop, OrcaSlicer Desktop, Bambuddy sidecar) all produced identical filament_map values for the same source 3MF, so the slicer wasn't the source of the asymmetry — Bambuddy's UI filter was. **Behaviour:** every loaded slot is now offered for every filament row in the Re-print and Schedule modals' specific-printer flow, regardless of which extruder it's wired to. The L/R badge on the filament row stays as a visual hint to what the slicer planned; the dropdown now trusts the user to pick based on their physical setup. Single-nozzle printers and FTS-equipped setups are unchanged — both short-circuited the filter already and continue to. Printer firmware accepts or rejects the resulting `ams_mapping` at start-print, so a physically-impossible pick fails loudly rather than silently. **Implementation:** `FilamentMapping.tsx:248-254` carried a guard `f.extruderId === item.nozzle_id` on the slot dropdown's `loadedFilaments` filter; the guard is now removed. The single-nozzle and FTS short-circuits stay. **Tests:** `'still applies the per-nozzle filter when FTS is null'` flipped to `'offers cross-extruder slots in the dropdown without FTS (#1722)'` — same scenario (no FTS, AMS 0 on right, filament asking for left), but now asserts both slots ARE listed. The FTS-installed case (#1162) and the rest of the FilamentMapping suite stay green. Backend untouched; no schema, no i18n. 5/5 FilamentMapping vitests green; 1043/1043 full component sweep green; frontend build clean. - **VP wire-payload dump escape hatch for shape-of-payload triage (#1622 investigation)** — When a virtual printer in non-proxy mode is misbehaving for the slicer-facing surface (AMS slot fields rendering empty, filament dropdown unselectable, K-profile not visible), the existing logs prove the bridge is bound and pushing at 1Hz but don't show what's actually in the wire payload. Without that, "cache is missing fields" is indistinguishable from "the slicer-facing copy is stripping them." Set `BAMBUDDY_VP_DUMP_WIRE=1` and Bambuddy writes the bridge's cached push_status (`/vp_wire/_in.json`) and the periodic 1Hz copy that gets sent to the slicer (`/vp_wire/_out.json`) to disk, overwritten on each tick. Diffing the two answers the bisect question; diffing a misbehaving VP's `_out.json` against a known-good VP's `_out.json` (e.g. P1S vs H2D in the #1622 case) answers the model-shape question. Off by default, no overhead when disabled (single env-var read per tick); env var re-read on every call so toggling without restart works; failures swallowed at debug so a broken dump can never break the 1Hz loop. Implementation lives in `backend/app/services/virtual_printer/_debug.py` with call sites in `mqtt_server.py::_send_status_report` (cached branch only — synthetic fallback is uninteresting for this triage) and `mqtt_bridge.py::_on_printer_raw` (immediately after the merge that produces `_latest_print_state`). 21 unit tests in `test_vp_wire_dump.py` pin: disabled-by-default, atomic tmp+rename writes (no half-written .json visible to a reader), sanitized vp_name (path-separator stripped, empty name falls back to `vp`, .. inside a single filename component is harmless because slashes are collapsed before path construction), per-call env check, dict + bytes + str payload acceptance, swallow-on-OSError. Not gated on debug-logging because the bridge's verbose path is already noisy; this dump is small (one file per direction per VP) and only present when the operator opts in. Diagnostic-only — does not change the bridge data path. - **VP slicer↔printer command-flow trace (#1622 round 2)** — The snapshot dump above answers "is the cached push shape correct?", but the round-1 captures from #1622 ruled that out: P1S AMS payload reaches the slicer byte-identical to what the printer sent, sticky-key preservation works, the visible slot data is intact. The remaining symptom (picking a generic filament in archive mode "unloads" the slot) lives on the command path, not in the periodic push — and the snapshot dump doesn't capture command traffic. Same env flag (`BAMBUDDY_VP_DUMP_WIRE=1`) now also appends every slicer-originated publish on `device//request` AND every printer-originated response the bridge fans out to the slicer (extrusion_cali_get, ams_filament_setting acks, xcam, system, etc.) to `/vp_wire/_cmd.jsonl`, one JSON line per event with UTC iso timestamp, direction (`slicer_to_bridge` / `printer_to_slicer`), MQTT topic, a `.` grep handle, and the parsed payload. Excludes the cached-as-base 1Hz push (already covered by the snapshot dump) and `pushall`/`get_version` (handled locally, never forwarded). Printer-side captures happen AFTER serial rewrite so the dump matches what the slicer actually saw on the wire. New `append_event` helper in `_debug.py` mirrors the same swallow-on-OSError + sanitized-vp_name + per-call env-check posture as `dump_wire`; bytes payloads are utf-8 decoded then json-parsed with the same `\x00`-tolerance fix from #927 so OrcaSlicer's C-string-null publishes parse cleanly; un-parseable bytes fall back to `{"raw": "..."}` so every line stays valid JSON. Eight additional unit tests in `test_vp_wire_dump.py` pin: disabled-by-default, bytes parsing, trailing-null tolerance, unparseable-fallback, vp_name sanitization, iso timestamp shape, append-multiple-lines, swallow-on-OSError. Diagnostic-only — does not change the publish or fan-out data path. diff --git a/frontend/src/__tests__/components/FilamentMapping.test.tsx b/frontend/src/__tests__/components/FilamentMapping.test.tsx index dd4d2cfb0..713be6025 100644 --- a/frontend/src/__tests__/components/FilamentMapping.test.tsx +++ b/frontend/src/__tests__/components/FilamentMapping.test.tsx @@ -193,7 +193,15 @@ describe('FilamentMapping — FTS routing', () => { expect(screen.queryByLabelText(/Force color match/i)).not.toBeInTheDocument(); }); - it('still applies the per-nozzle filter when FTS is null', async () => { + it('offers cross-extruder slots in the dropdown without FTS (#1722)', async () => { + // Before #1722 the dropdown filtered to only slots whose extruder matched + // the filament's slicer-assigned nozzle. On a dual-nozzle printer with one + // AMS per side, that prevented the user from picking a slot on the OTHER + // extruder even when they'd intentionally loaded the required filament + // there. The fix: trust the user, show every loaded slot regardless of + // which extruder it's wired to. The L/R badge on the filament row still + // tells the user what the slicer planned; the printer firmware accepts + // or rejects the cross-extruder ams_mapping at start-print. server.use( http.get( '/api/v1/printers/:id/status', @@ -219,13 +227,13 @@ describe('FilamentMapping — FTS routing', () => { />, ); - // Required nozzle is 1 (LEFT) but AMS 0 is on extruder 0 (RIGHT) — neither - // slot should appear in the dropdown. + // Required nozzle is 1 (LEFT) and AMS 0 is wired to extruder 0 (RIGHT). + // Both slots must STILL appear so the user can pick them — explicitly the + // cross-extruder scenario the #1722 fix unblocks. await waitFor(() => { - // Wait for component to render — the slot label should NOT be present - expect(screen.queryByText(/Bambu PLA/)).not.toBeInTheDocument(); - expect(screen.queryByText(/Bambu PETG/)).not.toBeInTheDocument(); + expect(screen.getByText(/Bambu PLA/)).toBeInTheDocument(); }); + expect(screen.getByText(/Bambu PETG/)).toBeInTheDocument(); }); it('renders sub-brand + material-disambiguated colour on the required side (#1718)', async () => { diff --git a/frontend/src/components/PrintModal/FilamentMapping.tsx b/frontend/src/components/PrintModal/FilamentMapping.tsx index fc4251cf3..2230849cf 100644 --- a/frontend/src/components/PrintModal/FilamentMapping.tsx +++ b/frontend/src/components/PrintModal/FilamentMapping.tsx @@ -245,14 +245,20 @@ export function FilamentMapping({ - {loadedFilaments - .filter( - (f) => - item.nozzle_id == null || - ftsInstalled || - f.extruderId === item.nozzle_id, - ) - .map((f) => { + {/* + #1722: every loaded slot is offered for every filament row, + regardless of which extruder the slot is wired to. Before this + change a slot was only listed when its extruder matched the + filament's slicer-assigned nozzle (item.nozzle_id), which + locked users out of cross-extruder picks even when they'd + intentionally loaded the required filament into the "other" + AMS. The L/R badge on the filament row still tells the user + what the slicer planned; the dropdown now trusts the user to + pick based on their physical setup. Printer firmware accepts + or rejects the ams_mapping at start-print — failure is loud, + not silent. + */} + {loadedFilaments.map((f) => { const remainingWeight = trayRemainingWeightMap.get(f.globalTrayId); const remainingLabel = remainingWeight != null ? t('printModal.slotRemainingShort', { diff --git a/static/assets/index-C-AWhT3K.js b/static/assets/index-I24jNRag.js similarity index 99% rename from static/assets/index-C-AWhT3K.js rename to static/assets/index-I24jNRag.js index 46d7ba52a..c1df291fa 100644 --- a/static/assets/index-C-AWhT3K.js +++ b/static/assets/index-I24jNRag.js @@ -8514,7 +8514,7 @@ ${l("inventory.assignProfileMismatchMessage",{spoolProfile:T.spoolProfile||l("co ${l("inventory.assignProfileMismatchMessage",{spoolProfile:T.spoolProfile||l("common.unknown"),trayProfile:T.trayProfile||l("common.unknown"),location:s.location})}`),A=`${A} -${l("inventory.assignReconfigureNote")}`,r.jsx(ka,{title:l("inventory.assignMismatchTitle"),message:A,confirmText:l("inventory.assignMismatchConfirm"),variant:"warning",overlayZIndex:"z-[110]",isLoading:Y.isPending,onConfirm:Q,onCancel:()=>{Y.isPending||(N(!1),k(null),j(null))}})})()]})}const p9e={bambuModelByShortCode:{}},tY={"A1 MINI":["A1M"]};function Pz(t,e){const a=t.toUpperCase(),n=e.toUpperCase();if(a===n)return!0;const i=tY[n];if(i&&i.includes(a))return!0;const s=tY[a];return!!(s&&s.includes(n))}function h9e(t){const e={};for(const[a,n]of Object.entries(t))n in e||(e[n]=a.replace(/^Bambu Lab\s+/,""));return e}function f9e(t={}){return{bambuModelByShortCode:h9e(t)}}function aY(t){return t.replace(/\s+/g,"").toLowerCase()}const g9e="0.4";function yse(t){const e=t.match(/^(.*?)\s+([\d.]+)\s*nozzle\s*$/i);return e?{stripped:e[1].trim(),nozzle:e[2]}:{stripped:t.trim(),nozzle:null}}function b9e(t){const e="@BBL ",a=t.indexOf(e);if(a<0)return null;const n=t.slice(a+e.length).trim(),{stripped:i,nozzle:s}=yse(n);return i?{token:i,nozzle:s}:null}function x9e(t){const e=t.match(/^Bambu Lab\s+(.+)$/i);if(!e)return null;const{stripped:a,nozzle:n}=yse(e[1]);return a?{model:a,nozzle:n}:null}function y9e(t,e,a){const n=b9e(t);if(!n)return"unknown";const i=a[n.token]??n.token,s=x9e(e);return s?aY(s.model)!==aY(i)&&!Pz(n.token,s.model)||s.nozzle!==null&&(n.nozzle??g9e)!==s.nozzle?"mismatch":"match":"unknown"}function Uy(t,e,a,n){if(!a)return"unknown";const i=t.compatible_printers;return i&&i.length>0?i.includes(a)?"match":"mismatch":y9e(t.name,a,n.bambuModelByShortCode)}const vse=["PLA","PETG","ABS","TPU","ASA","PC","PA","PVA","HIPS","PA-CF","PETG-CF","PLA-CF"],v9e=["Bambu","PolyLite","PolyTerra","eSUN","Overture","Fiberon","SUNLU","Inland","Hatchbox","Generic"],gw=["Basic","Matte","Silk","Silk+","Tough","Tough+","HF","High Flow","Engineering","CF","GF","Galaxy","Glow","Marble","Metal","Rainbow","Sparkle","Wood","Translucent","Transparent","Clear","Lite","Pro","Plus","Max","Super","Ultra","Flex","Soft","Hard","Strong","Impact","Heat Resistant","UV Resistant","ESD","Conductive","Magnetic","Gradient","Dual Color","Tri Color","Multicolor"],wse=[{name:"Black",hex:"000000"},{name:"White",hex:"FFFFFF"},{name:"Gray",hex:"808080"},{name:"Red",hex:"FF0000"},{name:"Orange",hex:"FFA500"},{name:"Yellow",hex:"FFFF00"},{name:"Green",hex:"00AE42"},{name:"Blue",hex:"0066FF"},{name:"Purple",hex:"8B00FF"},{name:"Pink",hex:"FF69B4"},{name:"Brown",hex:"8B4513"},{name:"Silver",hex:"C0C0C0"},{name:"Clear",hex:"00000000"}],w9e=[{name:"Dark Red",hex:"8B0000"},{name:"Crimson",hex:"DC143C"},{name:"Coral",hex:"FF7F50"},{name:"Salmon",hex:"FA8072"},{name:"Dark Orange",hex:"FF8C00"},{name:"Peach",hex:"FFDAB9"},{name:"Gold",hex:"FFD700"},{name:"Khaki",hex:"F0E68C"},{name:"Lemon",hex:"FFF44F"},{name:"Lime",hex:"32CD32"},{name:"Forest Green",hex:"228B22"},{name:"Olive",hex:"808000"},{name:"Mint",hex:"98FF98"},{name:"Teal",hex:"008080"},{name:"Navy",hex:"000080"},{name:"Sky Blue",hex:"87CEEB"},{name:"Royal Blue",hex:"4169E1"},{name:"Cyan",hex:"00FFFF"},{name:"Turquoise",hex:"40E0D0"},{name:"Violet",hex:"EE82EE"},{name:"Magenta",hex:"FF00FF"},{name:"Indigo",hex:"4B0082"},{name:"Lavender",hex:"E6E6FA"},{name:"Plum",hex:"DDA0DD"},{name:"Hot Pink",hex:"FF69B4"},{name:"Rose",hex:"FF007F"},{name:"Blush",hex:"FFB6C1"},{name:"Chocolate",hex:"D2691E"},{name:"Tan",hex:"D2B48C"},{name:"Beige",hex:"F5F5DC"},{name:"Maroon",hex:"800000"},{name:"Dark Gray",hex:"404040"},{name:"Light Gray",hex:"D3D3D3"},{name:"Charcoal",hex:"36454F"},{name:"Ivory",hex:"FFFFF0"},{name:"Bambu Green",hex:"00AE42"},{name:"Jade White",hex:"E8E8E8"},{name:"Titan Gray",hex:"5A5A5A"}],rY=[...wse,...w9e],Sse="bambuddy-recent-colors",S9e=8,k9e=[{code:"GFL00",name:"Bambu PLA Basic",displayName:"Bambu PLA Basic",isCustom:!1,allCodes:["GFL00"]},{code:"GFL01",name:"Bambu PLA Matte",displayName:"Bambu PLA Matte",isCustom:!1,allCodes:["GFL01"]},{code:"GFL05",name:"Generic PLA",displayName:"Generic PLA",isCustom:!1,allCodes:["GFL05"]},{code:"GFG00",name:"Bambu PETG Basic",displayName:"Bambu PETG Basic",isCustom:!1,allCodes:["GFG00"]},{code:"GFG05",name:"Generic PETG",displayName:"Generic PETG",isCustom:!1,allCodes:["GFG05"]},{code:"GFB00",name:"Bambu ABS Basic",displayName:"Bambu ABS Basic",isCustom:!1,allCodes:["GFB00"]},{code:"GFB05",name:"Generic ABS",displayName:"Generic ABS",isCustom:!1,allCodes:["GFB05"]},{code:"GFA00",name:"Bambu ASA Basic",displayName:"Bambu ASA Basic",isCustom:!1,allCodes:["GFA00"]},{code:"GFU00",name:"Bambu TPU 95A",displayName:"Bambu TPU 95A",isCustom:!1,allCodes:["GFU00"]},{code:"GFU05",name:"Generic TPU",displayName:"Generic TPU",isCustom:!1,allCodes:["GFU05"]},{code:"GFC00",name:"Bambu PC Basic",displayName:"Bambu PC Basic",isCustom:!1,allCodes:["GFC00"]},{code:"GFN00",name:"Bambu PA Basic",displayName:"Bambu PA Basic",isCustom:!1,allCodes:["GFN00"]},{code:"GFN05",name:"Generic PA",displayName:"Generic PA",isCustom:!1,allCodes:["GFN05"]},{code:"GFS00",name:"Bambu PLA-CF",displayName:"Bambu PLA-CF",isCustom:!1,allCodes:["GFS00"]},{code:"GFT00",name:"Bambu PETG-CF",displayName:"Bambu PETG-CF",isCustom:!1,allCodes:["GFT00"]},{code:"GFNC0",name:"Bambu PA-CF",displayName:"Bambu PA-CF",isCustom:!1,allCodes:["GFNC0"]},{code:"GFV00",name:"Bambu PVA",displayName:"Bambu PVA",isCustom:!1,allCodes:["GFV00"]}];function lf(t){let e=t.replace(/@.*$/,"").trim();e=e.replace(/\(Custom\)/i,"").trim(),e=e.replace(/^[#*]+\s*/,"").trim();const a=["PLA-CF","PETG-CF","ABS-GF","ASA-CF","PA-CF","PAHT-CF","PA6-CF","PA6-GF","PPA-CF","PPA-GF","PET-CF","PPS-CF","PC-CF","PC-ABS","ABS-GF","PCTG","PETG","PLA","ABS","ASA","PC","PA","TPU","PVA","HIPS","BVOH","PPS","PEEK","PEI"];let n="",i=-1;for(const c of a){const d=e.toUpperCase().indexOf(c.toUpperCase());if(d!==-1){n=c,i=d;break}}let s="";i>0&&(s=e.substring(0,i).trim(),s=s.replace(/[-_\s]+$/,""));let o="";i!==-1&&n&&(o=e.substring(i+n.length).trim(),o=o.replace(/^[-_\s]+/,""));let l="";for(const c of gw)if(o.toLowerCase().includes(c.toLowerCase())){l=c;break}if(!l&&s)for(const c of gw){const d=new RegExp(`\\s+${c}$`,"i");if(d.test(s)){l=c,s=s.replace(d,"").trim();break}}return{brand:s,material:n,variant:l}}function kse(t,e){const a=new Set(v9e);for(const n of t){const{brand:i}=lf(n.name);i&&i.length>1&&a.add(i)}if(e)for(const n of e)if(n.filament_vendor&&n.filament_vendor.length>1)a.add(n.filament_vendor);else{const{brand:i}=lf(n.name);i&&i.length>1&&a.add(i)}return Array.from(a).sort((n,i)=>n.localeCompare(i))}function _9e(t){const e=t.filter(n=>n.preset_type==="filament");return e.length===0?[]:e.map(n=>{const i=String(n.id),s=n.filament_type||i,o=Array.from(new Set([i,s]));return{code:i,name:n.name,displayName:n.name,isCustom:!1,allCodes:o}}).sort((n,i)=>n.displayName.localeCompare(i.displayName))}function _se(t,e,a,n){const i=[],s=[],o=new Set;for(const u of t)if(u.is_custom){const m=u.name.toUpperCase();(e.size===0||Array.from(e).some(f=>m.includes(f))||!m.includes("@"))&&(i.push({code:u.setting_id,name:u.name,displayName:`${u.name} (Custom)`,isCustom:!0,allCodes:[u.setting_id]}),o.add(u.setting_id))}else s.push({code:u.setting_id,name:u.name,displayName:u.name,isCustom:!1,allCodes:[u.setting_id]}),o.add(u.setting_id);const l=a&&a.length>0?_9e(a):[],c=[];if(n&&n.length>0)for(const u of n){const m=u.filament_id.startsWith("GF")?"GFS"+u.filament_id.slice(2):u.filament_id;o.has(u.filament_id)||o.has(m)||c.push({code:u.filament_id,name:u.name,displayName:u.name,isCustom:!1,allCodes:[u.filament_id,m]})}const d=[...i,...s,...l,...c];return d.length===0?k9e:d.sort((u,m)=>u.displayName.localeCompare(m.displayName))}function Cse(t,e){if(!t)return;let a=e.find(n=>n.code===t);if(a||(a=e.find(n=>n.allCodes.includes(t))),!a){const n=t.toLowerCase();a=e.find(i=>i.code.toLowerCase()===n||i.allCodes.some(s=>s.toLowerCase()===n))}return a}function Pse(){try{const t=localStorage.getItem(Sse);if(t)return JSON.parse(t)}catch{}return[]}function Nse(t,e){const a=e.filter(i=>i.hex.toUpperCase()!==t.hex.toUpperCase()),n=[t,...a].slice(0,S9e);try{localStorage.setItem(Sse,JSON.stringify(n))}catch{}return n}function bw(t){if(!t)return"";let e=t.split("_")[0];return/^GFS/i.test(e)&&(e=e.slice(0,2)+e.slice(3)),e.toUpperCase()}function Tse(t){return!!t&&/^GF[A-Z]99$/i.test(t)}function PF(t,e){if(!e.material)return!1;const a=bw(e.slicer_filament),n=bw(t.filament_id);if(a&&n&&a===n&&!Tse(n))return!0;const s=(t.name||"").replace(/^High Flow[_\s]+/i,"").replace(/^Standard[_\s]+/i,"").replace(/^HF[_\s]+/i,"").replace(/^S[_\s]+/i,"").trim(),o=lf(s);return!(!(o.material.toUpperCase()===e.material.toUpperCase())||e.brand&&!(o.brand.toLowerCase().includes(e.brand.toLowerCase())||e.brand.toLowerCase().includes(o.brand.toLowerCase()))||e.subtype&&!(o.variant.toLowerCase().includes(e.subtype.toLowerCase())||e.subtype.toLowerCase().includes(o.variant.toLowerCase())||s.toLowerCase().includes(e.subtype.toLowerCase())))}function nY(t,e){if(t===255)return"External";let a,n=!1;t>=128&&t<=135?(a=t-128,n=!0):t>=0&&t<=3?(a=t,n=e===1):a=0,a=Math.max(0,Math.min(a,7));const i=String.fromCharCode(65+a);return n?`HT-${i}`:`AMS-${i}`}function NF(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 cg=["PLA","PETG","PCTG","ABS","ASA","TPU","PC","PA","NYLON","PVA","HIPS","PP","PET"];function iY(t){const e=t.replace(/@.+$/,"").trim(),a=e.toUpperCase(),n=a.match(/\bSUPPORT\s+FOR\s+/);if(n){const s=a.slice(n.index+n[0].length);for(const o of cg)if(new RegExp(`\\b${o}\\b`).test(s)){const c=e.slice(0,n.index).trim();return{material:o,brand:c,variant:"Support"}}}for(const s of cg){const o=new RegExp(`\\b${s}\\b`,"i");if(o.test(a)){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 C9e(t){return!t.startsWith("GF")&&!t.startsWith("P1")}const P9e={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"},sY=[{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"}],oY=[{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 lY(t){const e=t.toLowerCase().trim();return P9e[e]||null}function cY(t){const e=t.indexOf("@");if(e<0)return null;const n=t.slice(e+1).trim().match(/^BBL\s+(.+?)(?:\s+[\d.]+\s*nozzle)?$/i);return n?n[1].trim():null}function Ase({isOpen:t,onClose:e,printerId:a,slotInfo:n,nozzleDiameter:i="0.4",printerModel:s,onSuccess:o,fullScreen:l}){const{t:c}=wt(),[d,u]=y.useState(""),[m,p]=y.useState(null),[f,g]=y.useState(""),[v,b]=y.useState(""),[x,S]=y.useState(""),[k,P]=y.useState(!1),[N,T]=y.useState(!1),j=y.useRef(""),{data:D,isLoading:C,isError:E}=$e({queryKey:["cloudSettings"],queryFn:()=>ne.getCloudSettings(),enabled:t,retry:!1}),{data:R}=$e({queryKey:["orcaCloudProfilesForAmsSlot"],queryFn:()=>ne.orcaCloudListProfiles(),enabled:t,retry:!1}),{data:I,isLoading:O}=$e({queryKey:["localPresets"],queryFn:()=>ne.getLocalPresets(),enabled:t}),{data:z,isLoading:X}=$e({queryKey:["builtinFilaments"],queryFn:()=>ne.getBuiltinFilaments(),enabled:t,staleTime:1/0}),{data:ae,isLoading:Y}=$e({queryKey:["kprofiles",a,i],queryFn:()=>ne.getKProfiles(a,i),enabled:t&&!!a}),{data:ce}=$e({queryKey:["colorCatalog"],queryFn:()=>ne.getColorCatalog(),enabled:t,staleTime:1/0}),de=rt({mutationFn:async()=>{if(!d)throw new Error("No filament preset selected");const B=d.startsWith("local_"),W=d.startsWith("builtin_"),H=d.startsWith("orca_")?d.replace("orca_",""):d,le=!B&&!W?R?.filament.find(ze=>ze.setting_id===H):void 0,U=!!le,G=le??null,Z=B?parseInt(d.replace("local_",""),10):null,J=W?d.replace("builtin_",""):null,re=B?I?.filament.find(ze=>ze.id===Z):null,se=W?z?.find(ze=>ze.filament_id===J):null,fe=!B&&!W&&!U?D?.filament.find(ze=>ze.setting_id===d):null;if(!B&&!W&&!U&&!fe)throw new Error("Selected preset not found");if(B&&!re)throw new Error("Selected local preset not found");if(W&&!se)throw new Error("Selected builtin preset not found");if(U&&!G)throw new Error("Selected Orca Cloud preset not found");const me=B?re.name:W?se.name:U?G.name:fe.name,pe=iY(me),V=m?.slot_id??-1,L=f||n.trayColor?.slice(0,6)||"FFFFFF",te=me.replace(/@.+$/,"").trim();let be,xe;const ve=pe.material.toUpperCase(),De={PLA:"GFL99","PLA-CF":"GFL98","PLA SILK":"GFL96","PLA HIGH SPEED":"GFL95",PETG:"GFG99","PETG HF":"GFG96","PETG-CF":"GFG98",PCTG:"GFG97",ABS:"GFB99",ASA:"GFB98",PC:"GFC99",PA:"GFN99","PA-CF":"GFN98",NYLON:"GFN99",TPU:"GFU99",PVA:"GFS99",HIPS:"GFS98",PE:"GFP99",PP:"GFP97"};if(B){const ze=(cg.includes(ve)?ve:re?.filament_type||pe.material||"").toUpperCase();be=De[ze]||De[ze.replace(/[-\s]?CF$/,"")]||De[ze.replace(/\+$/,"")]||De[ze.split(/[-\s]/)[0]]||"",xe=""}else if(U){const ze=(cg.includes(ve)?ve:pe.material||"").toUpperCase();be=De[ze]||De[ze.replace(/[-\s]?CF$/,"")]||De[ze.replace(/\+$/,"")]||De[ze.split(/[-\s]/)[0]]||"",xe=""}else if(W)be=J,xe="";else if(be=NF(d),xe=d,!d.startsWith("GFS"))try{const ze=await ne.getCloudSettingDetail(d);ze.filament_id&&(be=ze.filament_id)}catch(ze){console.warn("Failed to fetch preset detail for filament_id:",ze)}let je=B&&re?.nozzle_temp_min?re.nozzle_temp_min:190,Te=B&&re?.nozzle_temp_max?re.nozzle_temp_max:230;if(!B||W||U||!re?.nozzle_temp_min&&!re?.nozzle_temp_max){const ze=(B?cg.includes(ve)?ve:re?.filament_type||pe.material||"":pe.material).toUpperCase();ze.includes("PLA")?(je=190,Te=230):ze.includes("PETG")?(je=220,Te=260):ze.includes("ABS")||ze.includes("ASA")?(je=240,Te=280):ze.includes("TPU")?(je=200,Te=240):ze==="PCTG"?(je=220,Te=260):ze.includes("PC")?(je=260,Te=300):(ze.includes("PA")||ze.includes("NYLON"))&&(je=250,Te=290)}const qe=m?.k_value?parseFloat(m.k_value):0,Pe=B?cg.includes(ve)?ve:re?.filament_type||pe.material||"PLA":U&&cg.includes(ve)?ve:pe.material||"PLA",Ie=await ne.configureAmsSlot(a,n.amsId,n.trayId,{tray_info_idx:be,tray_type:Pe,tray_sub_brands:te,tray_color:L+"FF",nozzle_temp_min:je,nozzle_temp_max:Te,cali_idx:V,nozzle_diameter:i,setting_id:xe,kprofile_filament_id:m?.filament_id,kprofile_setting_id:m?.setting_id||void 0,k_value:qe}),Re=B?`local_${Z}`:W?`builtin_${J}`:d,Ue=B?"local":W?"builtin":U?"orca_cloud":"cloud";try{await ne.saveSlotPreset(a,n.amsId,n.trayId,Re,te,Ue)}catch(ze){console.warn("Failed to save slot preset mapping:",ze)}return Ie},onSuccess:()=>{P(!0),o?.(),setTimeout(()=>{P(!1),e()},1500)}}),oe=rt({mutationFn:async()=>ne.resetAmsSlot(a,n.amsId,n.trayId),onSuccess:()=>{P(!0),o?.(),setTimeout(()=>{P(!1),e()},1500)}}),K=y.useMemo(()=>{const B=x.toLowerCase(),W=[],H=new Set,le=n.savedPresetId,U=n.trayInfoIdx;if(R?.filament)for(const G of R.filament){const Z=`orca_${G.setting_id}`;if(H.add(G.setting_id),H.add(Z),!(B&&!G.name.toLowerCase().includes(B))){if(s){const J=cY(G.name);if(J&&!Pz(J,s))continue}W.push({id:Z,name:G.name,source:"orca_cloud",isUser:!0})}}if(D?.filament)for(const G of D.filament){if(H.has(G.setting_id))continue;H.add(G.setting_id);const J=le===G.setting_id||U&&(G.setting_id===U||NF(G.setting_id)===U);if(!(B&&!G.name.toLowerCase().includes(B))){if(!J&&s){const re=cY(G.name);if(re&&!Pz(re,s))continue}W.push({id:G.setting_id,name:G.name,source:"cloud",isUser:C9e(G.setting_id)})}}if(I?.filament)for(const G of I.filament){const Z=`local_${G.id}`;B&&!G.name.toLowerCase().includes(B)||W.push({id:Z,name:G.name,source:"local",isUser:!1})}if(z)for(const G of z){if(H.has(G.filament_id))continue;const Z=G.filament_id.startsWith("GF")?"GFS"+G.filament_id.slice(2):G.filament_id;H.has(Z)||(!B||G.name.toLowerCase().includes(B))&&W.push({id:`builtin_${G.filament_id}`,name:G.name,source:"builtin",isUser:!1})}return W.sort((G,Z)=>{const J={local:0,orca_cloud:1,cloud:2,builtin:3};return G.source!==Z.source?J[G.source]-J[Z.source]:G.isUser&&!Z.isUser?-1:!G.isUser&&Z.isUser?1:G.name.localeCompare(Z.name)})},[R?.filament,D?.filament,I?.filament,z,x,s,n.savedPresetId,n.trayInfoIdx]),ie=y.useMemo(()=>{if(!d)return null;let B=null,W="";if(d.startsWith("local_")){const U=parseInt(d.replace("local_",""),10);B=I?.filament.find(Z=>Z.id===U)?.name||null}else if(d.startsWith("builtin_")){const U=d.replace("builtin_","");B=z?.find(Z=>Z.filament_id===U)?.name||null,W=bw(U)}else{const U=d.startsWith("orca_")?d.replace("orca_",""):d,G=R?.filament.find(Z=>Z.setting_id===U);if(G)B=G.name;else if(D?.filament){const Z=D.filament.find(J=>J.setting_id===d);B=Z?.name||null,Z&&(W=bw(Z.setting_id))}}if(!B)return null;let H=B.replace(/@.+$/,"").trim();H.startsWith("# ")&&(H=H.slice(2).trim());const le=iY(H);return{fullName:H,material:le.material,brand:le.brand,filamentId:W}},[d,D?.filament,I?.filament,z,R?.filament]),ue=ie?.fullName||"",he=y.useMemo(()=>{if(!ce||!ie)return[];const{fullName:B,brand:W}=ie,H=B.replace(/^(Bambu\s*(Lab)?|eSUN|Polymaker|Overture|Sunlu|Hatchbox)\s*/i,"").trim();return ce.filter(le=>{const U=(le.material||"").toUpperCase(),G=le.manufacturer.toUpperCase();if(!(U===H.toUpperCase()||U.includes(H.toUpperCase())||H.toUpperCase().includes(U)))return!1;if(W){const J=W.toUpperCase();if(!G.includes(J)&&!J.includes(G))return!1}return!0})},[ce,ie]),ge=y.useMemo(()=>{if(!ae?.profiles)return[];if(!ie){const pe=n.caliIdx;if(pe!=null&&pe>0){const V=ae.profiles.find(L=>L.slot_id===pe&&(n.extruderId===void 0||L.extruder_id===n.extruderId));if(V)return[V]}return[]}const{fullName:B,material:W,brand:H,filamentId:le}=ie,U=B.toUpperCase(),G=W.toUpperCase(),Z=H.toUpperCase(),J=le;if(!G||G.length<2)return[];const re=ae.profiles.filter(pe=>{if(J){const be=bw(pe.filament_id);if(be&&be===J&&!Tse(be))return!0}const V=pe.name.toUpperCase();if(Z)return!(!V.includes(Z)||!V.includes(G));if(V.includes(U)||V.includes(G))return!0;const te={NYLON:["PA","PA-CF","PA6"],PA:["NYLON"]}[G]||[];for(const be of te)if(V.includes(be))return!0;return!1}),se=new Map;for(const pe of re){const V=`${pe.name}|${pe.k_value}`,L=se.get(V);L?n.extruderId!==void 0&&pe.extruder_id===n.extruderId&&L.extruder_id!==n.extruderId&&se.set(V,pe):se.set(V,pe)}const fe=Array.from(se.values()),me=n.caliIdx;if(me!=null&&me>0&&!fe.some(pe=>pe.slot_id===me)){const pe=ae.profiles.find(V=>V.slot_id===me&&(n.extruderId===void 0||V.extruder_id===n.extruderId));pe&&fe.unshift(pe)}return fe},[ae?.profiles,ie,n.extruderId,n.caliIdx]);y.useEffect(()=>{if(t){if(n.savedPresetId)u(n.savedPresetId);else if(n.trayInfoIdx&&D?.filament){let B=D.filament.find(W=>W.setting_id===n.trayInfoIdx);B||(B=D.filament.find(W=>NF(W.setting_id)===n.trayInfoIdx)),B&&u(B.setting_id)}else if(n.trayInfoIdx&&z?.length){const B=n.trayInfoIdx,W=z.find(H=>H.filament_id===B);W&&u(`builtin_${W.filament_id}`)}if(n.trayColor){const B=n.trayColor.slice(0,6);B&&g(B)}}else u(""),p(null),g(""),b(""),S(""),P(!1),j.current=""},[t,n.savedPresetId,n.trayInfoIdx,n.trayColor,D?.filament,z]),y.useEffect(()=>{if(ge.length>0){if(n.caliIdx!=null&&n.caliIdx>0){const B=ge.find(W=>W.slot_id===n.caliIdx);if(B){p(B);return}}p(ge[0])}else p(null)},[d,ge,n.caliIdx]);const q=y.useCallback(B=>{B.key==="Escape"&&e()},[e]);y.useEffect(()=>{if(t)return document.addEventListener("keydown",q),()=>document.removeEventListener("keydown",q)},[t,q]);const Q=C&&!E||O||X||Y;if(y.useEffect(()=>{if(!Q&&d&&d!==j.current){const B=requestAnimationFrame(()=>{const H=document.querySelector('[class*="fixed inset-0 z-50"]')?.querySelector(`[data-preset-id="${CSS.escape(d)}"]`);H&&(j.current=d,H.scrollIntoView({block:"nearest"}))});return()=>cancelAnimationFrame(B)}},[d,Q]),!t)return null;const A=d&&!de.isPending,F=f||n.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(xd,{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:"|"}),n.trayColor&&r.jsx("span",{className:"w-4 h-4 rounded-full border border-black/20",style:{backgroundColor:`#${n.trayColor.slice(0,6)}`}}),r.jsx("span",{className:"text-white/70",children:c("configureAmsSlot.slotLabel",{ams:nY(n.amsId,n.trayCount),slot:n.trayId+1})}),n.traySubBrands&&r.jsxs("span",{children:["(",n.traySubBrands,")"]})]})]}),r.jsx("button",{onClick:e,className:"p-1 text-bambu-gray hover:text-white rounded transition-colors",children:r.jsx(Ht,{className:"w-5 h-5"})})]}),r.jsxs("div",{className:`p-4 overflow-y-auto ${l?"flex-1 min-h-0":"space-y-4 max-h-[60vh]"}`,children:[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(to,{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:[n.trayColor&&r.jsx("span",{className:"w-4 h-4 rounded-full border border-black/20",style:{backgroundColor:`#${n.trayColor.slice(0,6)}`}}),r.jsx("span",{className:"text-white font-medium",children:c("configureAmsSlot.slotLabel",{ams:nY(n.amsId,n.trayCount),slot:n.trayId+1})}),n.traySubBrands&&r.jsxs("span",{className:"text-bambu-gray",children:["(",n.traySubBrands,")"]})]})]}),Q?r.jsx("div",{className:"flex justify-center py-8",children:r.jsx(lt,{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:B=>S(B.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:K.length===0?r.jsx("p",{className:"text-center py-4 text-bambu-gray",children:D?.filament?.length===0&&!I?.filament?.length?c("configureAmsSlot.noPresetsAvailable"):c("configureAmsSlot.noMatchingPresets")}):K.map(B=>r.jsx("button",{"data-preset-id":B.id,onClick:()=>u(B.id),className:`group w-full p-2 rounded-lg border text-left transition-colors ${d===B.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:B.name,children:B.name}),r.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[B.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")}),B.source==="orca_cloud"&&r.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded bg-purple-500/20 text-purple-400",children:c("configureAmsSlot.orcaCloud")}),B.source==="cloud"&&r.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded bg-bambu-blue/20 text-bambu-blue",children:c("configureAmsSlot.bambuCloud")}),B.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")})]})]})},B.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"),ue&&r.jsx("span",{className:"ml-2 text-xs text-bambu-blue",children:c("configureAmsSlot.filteringFor",{material:ue})})]}),ge.length>0?r.jsxs("div",{className:"relative",children:[r.jsxs("select",{value:m?.name||"",onChange:B=>{const W=ge.find(H=>H.name===B.target.value);p(W||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")}),ge.map(B=>r.jsxs("option",{value:B.name,children:[B.name," (K=",B.k_value,")"]},`${B.name}-${B.extruder_id}`))]}),r.jsx(za,{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")}),he.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:ie?.fullName})}),r.jsx("div",{className:"flex flex-wrap gap-1.5",children:he.map(B=>r.jsxs("button",{onClick:()=>{const W=B.hex_color.replace("#","").toUpperCase();g(W),b(B.color_name)},className:`h-7 px-2 rounded-md border-2 transition-all flex items-center gap-1.5 ${f===B.hex_color.replace("#","").toUpperCase()?"border-bambu-green scale-105":"border-white/20 hover:border-white/40"}`,title:B.color_name,children:[r.jsx("span",{className:"w-4 h-4 rounded-full border border-black/20 flex-shrink-0",style:{backgroundColor:B.hex_color}}),r.jsx("span",{className:"text-xs text-white/80 whitespace-nowrap",children:B.color_name})]},B.id))})]}),r.jsxs("div",{className:"flex flex-wrap gap-1.5 mb-2",children:[sY.map(B=>r.jsx("button",{onClick:()=>{g(B.hex),b(B.name)},className:`w-7 h-7 rounded-md border-2 transition-all ${f===B.hex?"border-bambu-green scale-110":"border-white/20 hover:border-white/40"}`,style:{backgroundColor:`#${B.hex}`},title:B.name},B.hex)),r.jsx("button",{onClick:()=>T(!N),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(N?"configureAmsSlot.showLessColors":"configureAmsSlot.showMoreColors"),children:N?"−":"+"})]}),N&&r.jsx("div",{className:"flex flex-wrap gap-1.5 mb-2",children:oY.map(B=>r.jsx("button",{onClick:()=>{g(B.hex),b(B.name)},className:`w-7 h-7 rounded-md border-2 transition-all ${f===B.hex?"border-bambu-green scale-110":"border-white/20 hover:border-white/40"}`,style:{backgroundColor:`#${B.hex}`},title:B.name},B.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:`#${F}`}}),r.jsx("input",{type:"text",placeholder:c("configureAmsSlot.colorPlaceholder"),value:v,onChange:B=>{const W=B.target.value;b(W);const H=lY(W);if(H)g(H);else{const le=W.replace(/[^0-9A-Fa-f]/g,"").toUpperCase();le.length===6?g(le):le.length===3&&g(le.split("").map(U=>U+U).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:B=>S(B.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:K.length===0?r.jsx("p",{className:"text-center py-4 text-bambu-gray",children:D?.filament?.length===0&&!I?.filament?.length?c("configureAmsSlot.noPresetsAvailable"):c("configureAmsSlot.noMatchingPresets")}):K.map(B=>r.jsx("button",{"data-preset-id":B.id,onClick:()=>u(B.id),className:`group w-full p-2 rounded-lg border text-left transition-colors ${d===B.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:B.name,children:B.name}),r.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[B.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")}),B.source==="orca_cloud"&&r.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded bg-purple-500/20 text-purple-400",children:c("configureAmsSlot.orcaCloud")}),B.source==="cloud"&&r.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded bg-bambu-blue/20 text-bambu-blue",children:c("configureAmsSlot.bambuCloud")}),B.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")})]})]})},B.id))})]})]}),r.jsxs("div",{children:[r.jsxs("label",{className:"block text-sm text-bambu-gray mb-2",children:[c("configureAmsSlot.kProfileLabel"),ue&&r.jsx("span",{className:"ml-2 text-xs text-bambu-blue",children:c("configureAmsSlot.filteringFor",{material:ue})})]}),ge.length>0?r.jsxs("div",{className:"relative",children:[r.jsxs("select",{value:m?.name||"",onChange:B=>{const W=ge.find(H=>H.name===B.target.value);p(W||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")}),ge.map(B=>r.jsxs("option",{value:B.name,children:[B.name," (K=",B.k_value,")"]},`${B.name}-${B.extruder_id}`))]}),r.jsx(za,{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")}),he.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:ie?.fullName})}),r.jsx("div",{className:"flex flex-wrap gap-1.5",children:he.map(B=>r.jsxs("button",{onClick:()=>{const W=B.hex_color.replace("#","").toUpperCase();g(W),b(B.color_name)},className:`h-7 px-2 rounded-md border-2 transition-all flex items-center gap-1.5 ${f===B.hex_color.replace("#","").toUpperCase()?"border-bambu-green scale-105":"border-white/20 hover:border-white/40"}`,title:B.color_name,children:[r.jsx("span",{className:"w-4 h-4 rounded-full border border-black/20 flex-shrink-0",style:{backgroundColor:B.hex_color}}),r.jsx("span",{className:"text-xs text-white/80 whitespace-nowrap",children:B.color_name})]},B.id))})]}),r.jsxs("div",{className:"flex flex-wrap gap-1.5 mb-2",children:[sY.map(B=>r.jsx("button",{onClick:()=>{g(B.hex),b(B.name)},className:`w-7 h-7 rounded-md border-2 transition-all ${f===B.hex?"border-bambu-green scale-110":"border-white/20 hover:border-white/40"}`,style:{backgroundColor:`#${B.hex}`},title:B.name},B.hex)),r.jsx("button",{onClick:()=>T(!N),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(N?"configureAmsSlot.showLessColors":"configureAmsSlot.showMoreColors"),children:N?"−":"+"})]}),N&&r.jsx("div",{className:"flex flex-wrap gap-1.5 mb-2",children:oY.map(B=>r.jsx("button",{onClick:()=>{g(B.hex),b(B.name)},className:`w-7 h-7 rounded-md border-2 transition-all ${f===B.hex?"border-bambu-green scale-110":"border-white/20 hover:border-white/40"}`,style:{backgroundColor:`#${B.hex}`},title:B.name},B.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:`#${F}`}}),r.jsx("input",{type:"text",placeholder:c("configureAmsSlot.colorPlaceholder"),value:v,onChange:B=>{const W=B.target.value;b(W);const H=lY(W);if(H)g(H);else{const le=W.replace(/[^0-9A-Fa-f]/g,"").toUpperCase();le.length===6?g(le):le.length===3&&g(le.split("").map(U=>U+U).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(Le,{variant:"secondary",onClick:()=>oe.mutate(),disabled:oe.isPending||de.isPending,className:"text-red-400 hover:text-red-300 hover:bg-red-500/10",children:oe.isPending?r.jsxs(r.Fragment,{children:[r.jsx(lt,{className:"w-4 h-4 animate-spin"}),c("configureAmsSlot.resetting")]}):r.jsxs(r.Fragment,{children:[r.jsx(bs,{className:"w-4 h-4"}),c("configureAmsSlot.resetSlot")]})}),r.jsxs("div",{className:"flex gap-2",children:[r.jsx(Le,{variant:"secondary",onClick:e,children:c("configureAmsSlot.cancel")}),r.jsx(Le,{onClick:()=>de.mutate(),disabled:!A,children:de.isPending?r.jsxs(r.Fragment,{children:[r.jsx(lt,{className:"w-4 h-4 animate-spin"}),c("configureAmsSlot.configuring")]}):r.jsxs(r.Fragment,{children:[r.jsx(xd,{className:"w-4 h-4"}),c("configureAmsSlot.configureSlot")]})})]})]}),(de.isError||oe.isError)&&r.jsx("div",{className:"mx-4 mb-4 p-2 bg-red-500/20 border border-red-500/50 rounded text-sm text-red-400",children:de.error?.message||oe.error?.message})]})]})}function dY({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 jse({folderId:t,onClose:e,onUploadComplete:a,onFileUploaded:n,autoUpload:i,validateFile:s,accept:o}){const{t:l}=wt(),[c,d]=y.useState([]),[u,m]=y.useState(!1),[p,f]=y.useState(!1),[g,v]=y.useState(!0),[b,x]=y.useState(!1),[S,k]=y.useState(!0),[P,N]=y.useState(null),T=y.useRef(null),j=oe=>{oe.preventDefault(),m(!0)},D=oe=>{oe.preventDefault(),m(!1)},C=oe=>{oe.preventDefault(),m(!1),O(Array.from(oe.dataTransfer.files))},E=oe=>{oe.target.files&&O(Array.from(oe.target.files))},R=(oe,K)=>{d(ie=>ie.map(ue=>ue.file===oe?{...ue,...K}:ue))},I=async oe=>{f(!0);for(const K of oe)if(K.status==="pending"){R(K.file,{status:"uploading"});try{if(K.isZip){const ie=await ne.extractZipFile(K.file,t,g,b,S);R(K.file,{status:ie.errors.length>0&&ie.extracted===0?"error":"success",extractedCount:ie.extracted,error:ie.errors.length>0?l("fileManager.zipFilesFailed","{{count}} files failed",{count:ie.errors.length}):void 0})}else{const ie=await ne.uploadLibraryFile(K.file,t,S);R(K.file,{status:"success"});const ue=n?.(ie);if(ue){N(ue),d([]),f(!1);return}}}catch(ie){R(K.file,{status:"error",error:ie instanceof Error?ie.message:l("fileManager.uploadFailed","Upload failed")})}}f(!1),a(),d(K=>(K.some(ue=>ue.status==="error")||e(),K))},O=oe=>{if(N(null),s)for(const ie of oe){const ue=s(ie);if(ue){N(ue);return}}const K=oe.map(ie=>({file:ie,status:"pending",isZip:ie.name.toLowerCase().endsWith(".zip"),is3mf:ie.name.toLowerCase().endsWith(".3mf")}));d(ie=>[...ie,...K]),i&&oe.length>0&&I(K)},z=oe=>{d(K=>K.filter((ie,ue)=>ue!==oe))},X=c.some(oe=>oe.isZip&&oe.status==="pending"),ae=c.some(oe=>oe.file.name.toLowerCase().endsWith(".stl")&&oe.status==="pending"),Y=c.some(oe=>oe.is3mf&&oe.status==="pending"),ce=c.filter(oe=>oe.status==="pending").length,de=c.length>0&&ce===0&&!p;return r.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:r.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-lg border border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"p-4 border-b border-bambu-dark-tertiary flex items-center justify-between",children:[r.jsx("h2",{className:"text-lg font-semibold text-white",children:l("fileManager.uploadFiles")}),r.jsx("button",{onClick:e,className:"p-1 hover:bg-bambu-dark rounded",children:r.jsx(Ht,{className:"w-5 h-5 text-bambu-gray"})})]}),r.jsxs("div",{className:"p-4 space-y-4",children:[r.jsxs("div",{onDragOver:j,onDragLeave:D,onDrop:C,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(Sn,{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:E}),X&&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(ro,{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:oe=>v(oe.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:oe=>x(oe.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(xr,{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")})]})]})}),(ae||X)&&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(gu,{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(X&&!ae?"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:oe=>k(oe.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((oe,K)=>r.jsxs("div",{className:"flex items-center gap-3 p-2 bg-bambu-dark rounded-lg",children:[oe.isZip?r.jsx(ro,{className:"w-4 h-4 text-blue-400 flex-shrink-0"}):r.jsx(FT,{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:oe.file.name}),r.jsxs("p",{className:"text-xs text-bambu-gray",children:[(oe.file.size/1024/1024).toFixed(2)," MB",oe.isZip&&oe.status==="pending"&&r.jsxs("span",{className:"text-blue-400 ml-2",children:["• ",l("fileManager.willBeExtracted")]}),oe.extractedCount!==void 0&&r.jsxs("span",{className:"text-green-400 ml-2",children:["• ",l("fileManager.filesExtracted",{count:oe.extractedCount})]})]}),oe.status==="error"&&oe.error&&r.jsx("p",{className:"text-xs text-red-400 mt-1 break-words",children:oe.error})]}),oe.status==="pending"&&r.jsx("button",{onClick:()=>z(K),className:"p-1 hover:bg-bambu-dark-tertiary rounded",children:r.jsx(Ht,{className:"w-4 h-4 text-bambu-gray"})}),oe.status==="uploading"&&r.jsx(lt,{className:"w-4 h-4 text-bambu-green animate-spin"}),oe.status==="success"&&r.jsx(fr,{className:"w-4 h-4 text-green-500"}),oe.status==="error"&&r.jsx("span",{title:oe.error,children:r.jsx(Fr,{className:"w-4 h-4 text-red-500"})})]},K))}),P&&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(Fr,{className:"w-5 h-5 text-red-400 mt-0.5 flex-shrink-0"}),r.jsx("p",{className:"text-sm text-red-300",children:P})]})})]}),r.jsxs("div",{className:"p-4 border-t border-bambu-dark-tertiary flex justify-end gap-2",children:[r.jsx(Le,{variant:"secondary",onClick:e,children:l("common.cancel")}),!de&&r.jsx(Le,{onClick:()=>I(c),disabled:ce===0||p,children:p?r.jsxs(r.Fragment,{children:[r.jsx(lt,{className:"w-4 h-4 mr-2 animate-spin"}),l("fileManager.uploading")]}):r.jsxs(r.Fragment,{children:[r.jsx(Sn,{className:"w-4 h-4 mr-2"}),l("common.upload")," ",ce>0?`(${ce})`:""]})})]})]})})}function uY(t){if(!t)return"#808080";const e=t.replace("#","");return e.length>=8&&e.substring(6,8).toLowerCase()!=="ff"?`#${e.substring(0,8)}`:`#${e.substring(0,6)}`}function On(t){return t?t.replace("#","").toLowerCase().substring(0,6):""}const N9e=[["PA-CF","PA12-CF","PAHT-CF"]],Mse={};for(const t of N9e){const e=t[0];for(const a of t)Mse[a.toUpperCase()]=e.toUpperCase()}function M1(t){if(!t)return"";const e=t.toUpperCase();return Mse[e]??e}function TF(t,e){return M1(t)===M1(e)}function fd(t,e,a=40){const n=On(t),i=On(e);if(!n||!i||n.length<6||i.length<6)return!1;const s=parseInt(n.substring(0,2),16),o=parseInt(n.substring(2,4),16),l=parseInt(n.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)<=a&&Math.abs(o-d)<=a&&Math.abs(l-u)<=a}function yk(t,e,a,n){if(n)return"Ext";const i=String.fromCharCode(65+(t>=128?t-128:t));return a?`HT-${i}`:`${i}${e+1}`}function ib(t,e,a){return a?254+e:t>=128?t:t*4+e}function by(t){return t>50?"#00ae42":t>=15?"#f59e0b":"#ef4444"}function GP(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 mY(t,e){return(Number.isFinite(t)?Math.max(0,Math.trunc(t)):0).toString(16).toUpperCase().padStart(e,"0").slice(-e)}function T9e(t){const e=(t||"").trim().toUpperCase();let a=2166136261;for(let n=0;n>>0).toString(16).toUpperCase().padStart(8,"0")}function wm(t,e,a){return`${T9e(t)}${mY(e,4)}${mY(a,4)}`}function pY(t){if(!t)return!1;const e=Date.now()+4320*60*60*1e3;return(Ga(t)?.getTime()??0)>e}function A9e(t,e,a,n){let i=Ese(e,t.nozzle_id);n&&(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=>!a.has(c.globalTrayId)&&TF(c.type,t.type)&&On(c.color)===On(t.color)),o=s?void 0:i.find(c=>!a.has(c.globalTrayId)&&TF(c.type,t.type)&&fd(c.color,t.color)),l=s||o?void 0:i.find(c=>!a.has(c.globalTrayId)&&TF(c.type,t.type));return s??o??l}function Ese(t,e){return t.filter(a=>e==null||a.extruderId===e)}function Qs(t){return t?!!(t.tray_uuid&&t.tray_uuid!=="00000000000000000000000000000000"||t.tag_uid&&t.tag_uid!=="0000000000000000"):!1}function vk(t){const e=[],a=t?.ams_extruder_map,n=!!t?.nozzles?.[1]?.nozzle_diameter||a&&Object.keys(a).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=uY(o.tray_color);e.push({type:o.tray_type,color:l,colorName:_c(l),amsId:i.id,trayId:o.id,isHt:s,isExternal:!1,label:yk(i.id,o.id,s,!1),globalTrayId:ib(i.id,o.id,!1),trayInfoIdx:o.tray_info_idx||"",traySubBrands:o.tray_sub_brands||"",extruderId:a?.[String(i.id)],remain:o.remain??-1})}})});for(const i of t?.vt_tray??[])if(i.tray_type){const s=uY(i.tray_color),o=i.id??254,l=(t?.vt_tray?.length??0)>1;e.push({type:i.tray_type,color:s,colorName:_c(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:n?255-o:void 0,remain:i.remain??-1})}return e}function hY(t,e,a){if(!t?.filaments||t.filaments.length===0)return;const n=vk(e);if(n.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=n.filter(x=>!s.has(x.globalTrayId));d.nozzle_id!=null&&!i&&(m=m.filter(x=>x.extruderId===d.nozzle_id)),a&&(m=[...m].sort((x,S)=>{const k=x.remain>=0?x.remain:101,P=S.remain>=0?S.remain:101;return k-P}));let p,f,g,v;if(u){const x=m.filter(S=>S.trayInfoIdx===u);x.length===1?p=x[0]:x.length>1&&(a&&x.sort((S,k)=>{const P=S.remain>=0?S.remain:101,N=k.remain>=0?k.remain:101;return P-N}),f=x.find(S=>S.type?.toUpperCase()===d.type?.toUpperCase()&&On(S.color)===On(d.color)),f||(g=x.find(S=>S.type?.toUpperCase()===d.type?.toUpperCase()&&fd(S.color,d.color))),!f&&!g&&(v=x.find(S=>S.type?.toUpperCase()===d.type?.toUpperCase())))}!p&&!f&&!g&&!v&&(f=m.find(x=>x.type?.toUpperCase()===d.type?.toUpperCase()&&On(x.color)===On(d.color)),f||(g=m.find(x=>x.type?.toUpperCase()===d.type?.toUpperCase()&&fd(x.color,d.color))),!f&&!g&&(v=m.find(x=>x.type?.toUpperCase()===d.type?.toUpperCase())));const b=p||f||g||v||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 j9e(t){return y.useMemo(()=>vk(t),[t])}function Dse(t,e,a,n){const i=j9e(e),s=e?.fila_switch?.installed===!0,o=y.useMemo(()=>{if(!t?.filaments||t.filaments.length===0)return[];const u=new Set(Object.values(a));return t.filaments.map(m=>{const p=m.slot_id||0;if(p>0&&a[p]!==void 0){const D=a[p],C=i.find(E=>E.globalTrayId===D);if(C){const E=C.type?.toUpperCase()===m.type?.toUpperCase(),R=On(C.color)===On(m.color)||fd(C.color,m.color);let I;return E&&R?I="match":E?I="type_only":I="mismatch",{...m,loaded:C,hasFilament:!0,typeMatch:E,colorMatch:R,status:I,isManual:!0}}}const f=m.tray_info_idx||"";let g=i.filter(D=>!u.has(D.globalTrayId));m.nozzle_id!=null&&!s&&(g=g.filter(D=>D.extruderId===m.nozzle_id)),n&&(g=[...g].sort((D,C)=>{const E=D.remain>=0?D.remain:101,R=C.remain>=0?C.remain:101;return E-R}));let v,b,x,S;if(f){const D=g.filter(C=>C.trayInfoIdx===f);D.length===1?v=D[0]:D.length>1&&(n&&D.sort((C,E)=>{const R=C.remain>=0?C.remain:101,I=E.remain>=0?E.remain:101;return R-I}),b=D.find(C=>C.type?.toUpperCase()===m.type?.toUpperCase()&&On(C.color)===On(m.color)),b||(x=D.find(C=>C.type?.toUpperCase()===m.type?.toUpperCase()&&fd(C.color,m.color))),!b&&!x&&(S=D.find(C=>C.type?.toUpperCase()===m.type?.toUpperCase())))}!v&&!b&&!x&&!S&&(b=g.find(D=>D.type?.toUpperCase()===m.type?.toUpperCase()&&On(D.color)===On(m.color)),b||(x=g.find(D=>D.type?.toUpperCase()===m.type?.toUpperCase()&&fd(D.color,m.color))),!b&&!x&&(S=g.find(D=>D.type?.toUpperCase()===m.type?.toUpperCase())));const k=v||b||x||S||void 0;k&&u.add(k.globalTrayId);const P=!!k,N=P,T=!!v||!!b||!!x;let j;return v||b||x?j="match":S?j="type_only":j="mismatch",{...m,loaded:k,hasFilament:P,typeMatch:N,colorMatch:T,status:j,isManual:!1}})},[t,i,a,n,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 M9e(t,e,a,n){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(a));for(const u of t){const m=u.slot_id||0;if(m>0&&a[m]!==void 0){const x=a[m],S=e.find(k=>k.globalTrayId===x);if(S){const k=S.type?.toUpperCase()===u.type?.toUpperCase(),P=On(S.color)===On(u.color)||fd(S.color,u.color);k&&P?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)}n&&(p=[...p].sort((x,S)=>{const k=x.remain>=0?x.remain:101,P=S.remain>=0?S.remain:101;return k-P}));const f=p.find(x=>x.type?.toUpperCase()===u.type?.toUpperCase()&&On(x.color)===On(u.color)),g=f?void 0:p.find(x=>x.type?.toUpperCase()===u.type?.toUpperCase()&&fd(x.color,u.color)),v=f||g?void 0:p.find(x=>x.type?.toUpperCase()===u.type?.toUpperCase()),b=f??g??v;b&&l.add(b.globalTrayId),f||g?i++:v?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 E9e(t,e,a,n){if(!t?.filaments||t.filaments.length===0)return;const i=vk(e);if(i.length===0)return;const s=new Set(Object.values(a)),o=[];for(const d of t.filaments){const u=d.slot_id||0;if(u>0&&a[u]!==void 0){o.push({slot_id:u,globalTrayId:a[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)}n&&(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()&&On(b.color)===On(d.color)),f=p?void 0:m.find(b=>b.type?.toUpperCase()===d.type?.toUpperCase()&&fd(b.color,d.color)),g=p||f?void 0:m.find(b=>b.type?.toUpperCase()===d.type?.toUpperCase()),v=p??f??g;v&&s.add(v.globalTrayId),o.push({slot_id:u,globalTrayId:v?.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 fY={useDefault:!0,manualMappings:{},autoConfigured:!1};function D9e(t,e,a,n,i,s,o){const l=dp({queries:t.map(v=>({queryKey:["printer-status",v],queryFn:()=>ne.getPrinterStatus(v),enabled:t.length>0,staleTime:5e3}))}),c=y.useMemo(()=>t.map((v,b)=>{const x=l[b],S=x?.data,P=e?.find(R=>R.id===v)?.name||`Printer ${v}`,N=vk(S),T=i[v]||fY,j=hY(a,S,o),D=T.useDefault?n:T.manualMappings,C=E9e(a,S,D,o),E=M9e(a?.filaments,N,D,o);return{printerId:v,printerName:P,status:S,isLoading:x?.isLoading??!1,loadedFilaments:N,autoMapping:j,finalMapping:C,matchStatus:E.status,exactMatches:E.exactMatches,typeOnlyMatches:E.typeOnlyMatches,missingTypes:E.missingTypes,totalSlots:E.totalSlots,config:T}}),[t,l,e,a,i,n,o]),d=l.some(v=>v.isLoading),u=(v,b)=>{s(x=>({...x,[v]:{...x[v]||fY,...b}}))},m=v=>{const b=c.find(k=>k.printerId===v);if(!b||!b.status||!a?.filaments)return;const x=hY(a,b.status,o);if(!x)return;const S={};x.forEach((k,P)=>{k!==-1&&(S[P+1]=k)}),u(v,{useDefault:!1,manualMappings:S,autoConfigured:!0})},p=()=>{for(const v of t)m(v)},f=v=>c.find(x=>x.printerId===v)?.finalMapping,g=c.every(v=>v.matchStatus!=="missing");return{printerResults:c,isLoading:d,perPrinterConfigs:i,updatePrinterConfig:u,autoConfigureAll:p,autoConfigurePrinter:m,getFinalMapping:f,allPrintersReady:g}}const Fse={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 Vo(t){return Fse[t.toUpperCase()]||t}const F9e=Object.entries(Fse).map(([t,e])=>({code:t,label:`${t} (${e})`})),Vd="/img/bed",L9e={"cool plate":{icon:`${Vd}/bed_cool.png`,label:"Cool Plate"},"pc plate":{icon:`${Vd}/bed_cool.png`,label:"Cool Plate"},"cool plate (supertack)":{icon:`${Vd}/bed_cool_supertack.png`,label:"Cool Plate SuperTack"},"supertack plate":{icon:`${Vd}/bed_cool_supertack.png`,label:"Cool Plate SuperTack"},"bambu cool plate supertack":{icon:`${Vd}/bed_cool_supertack.png`,label:"Cool Plate SuperTack"},"engineering plate":{icon:`${Vd}/bed_engineering.png`,label:"Engineering Plate"},"high temp plate":{icon:`${Vd}/bed_high_templ.png`,label:"High Temp Plate"},"textured pei plate":{icon:`${Vd}/bed_pei.png`,label:"Textured PEI Plate"},"pei plate":{icon:`${Vd}/bed_pei.png`,label:"PEI Plate"},"smooth pei plate":{icon:`${Vd}/bed_pei_cool.png`,label:"Smooth PEI Plate"}};function wk(t){return t?L9e[t.trim().toLowerCase()]??null:null}function R9e(t){const e=t.trim().split(/\s+/);return e.length<=1?t.trim():e.slice(1).join(" ")}function Lse(t){const{data:e}=$e({queryKey:["builtin-filaments"],queryFn:()=>ne.getBuiltinFilaments(),staleTime:3e5}),{data:a}=$e({queryKey:["filament-id-map"],queryFn:()=>ne.getFilamentIdMap(),staleTime:300*1e3}),n=y.useMemo(()=>{const o={};for(const l of e||[])l.filament_id&&(o[l.filament_id]=l.name);for(const[l,c]of Object.entries(a||{}))l&&c&&(o[l]=c);return o},[e,a]),i=y.useMemo(()=>(t||[]).map(o=>{const l=o.tray_info_idx&&n[o.tray_info_idx]||o.type;return{resolvedName:l,materialHint:R9e(l),color:o.color}}),[t,n]),s=dp({queries:i.map(({color:o,materialHint:l})=>({queryKey:["color-by-material",o,l],queryFn:()=>ne.getColorByMaterial(o,l),enabled:!!o,staleTime:300*1e3}))});return i.map(({resolvedName:o,color:l},c)=>{const d=s[c]?.data?.color_name??null;return{resolvedName:o,colorLabel:d||_c(l)}})}function z9e({printerId:t,filamentReqs:e,manualMappings:a,onManualMappingChange:n,currencySymbol:i,defaultCostPerKg:s,defaultExpanded:o=!1,forceColorMatch:l,onForceColorMatchChange:c}){const{t:d}=wt(),u=ia(),[m,p]=y.useState(!1),[f,g]=y.useState(o),{data:v}=$e({queryKey:["printer-status",t],queryFn:()=>ne.getPrinterStatus(t),enabled:!!t}),{data:b}=$e({queryKey:["spool-assignments",t],queryFn:()=>ne.getAssignments(t),enabled:!!t}),{loadedFilaments:x,filamentComparison:S,hasTypeMismatch:k,hasColorMismatch:P}=Dse(e,v,a),N=Lse(e?.filaments),T=y.useMemo(()=>{const Y=new Map;for(const ce of b||[]){const de=ce.ams_id===255,oe=ib(ce.ams_id,ce.tray_id,de);Y.set(oe,ce.spool?.cost_per_kg??null)}return Y},[b]),j=y.useMemo(()=>{const Y=new Map;for(const ce of b||[]){const de=ce.ams_id===255,oe=ib(ce.ams_id,ce.tray_id,de),K=ce.spool;if(!K){Y.set(oe,null);continue}Y.set(oe,Math.max(0,Math.round((K.label_weight??0)-(K.weight_used??0))))}return Y},[b]),D=y.useMemo(()=>{let Y=0;for(const ce of S){const de=ce.loaded?.globalTrayId;if(de==null)continue;const K=T.get(de)??null??s;K>0&&(Y+=ce.used_grams/1e3*K)}return Y},[S,T,s]),C=y.useMemo(()=>Array.from(T.values()).some(Y=>Y!=null&&Y>0),[T]),E=e?.filaments&&e.filaments.length>0,R=e?.filaments?.some(Y=>Y.nozzle_id!=null)??!1,I=v?.fila_switch?.installed===!0,O=Y=>{const ce=v?.fila_switch;if(!ce?.installed)return null;const de=ce.in_slots.indexOf(Y);return de<0?null:ce.out_extruders[de]??null};if(!E||!v)return null;const z=k?"#f97316":P?"#facc15":"#00ae42",X=(Y,ce)=>{if(Y>0)if(ce===""){const de={...a};delete de[Y],n(de)}else n({...a,[Y]:parseInt(ce,10)})},ae=async()=>{p(!0);try{await ne.refreshPrinterStatus(t),await new Promise(Y=>setTimeout(Y,500)),await u.refetchQueries({queryKey:["printer-status",t]})}finally{p(!1)}};return r.jsxs("div",{className:"mb-4",children:[r.jsxs("button",{type:"button",onClick:()=>g(!f),className:"flex items-center gap-2 text-sm text-bambu-gray hover:text-white transition-colors w-full",children:[r.jsx(Uw,{className:"w-4 h-4",fill:z,stroke:"none"}),r.jsx("span",{children:d("printModal.filamentMapping")}),k?r.jsx("span",{className:"text-xs text-orange-400",children:"(Type not found)"}):P?r.jsx("span",{className:"text-xs text-yellow-400",children:"(Color mismatch)"}):r.jsx("span",{className:"text-xs text-bambu-green",children:"(Ready)"}),f?r.jsx(el,{className:"w-4 h-4 ml-auto"}):r.jsx(za,{className:"w-4 h-4 ml-auto"})]}),f&&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:ae,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:m,children:[r.jsx(tr,{className:`w-3 h-3 ${m?"animate-spin":""}`}),r.jsx("span",{children:"Re-read"})]})]}),S.map((Y,ce)=>{const de=Y.slot_id??0,oe=de>0&&c!=null,{resolvedName:K,colorLabel:ie}=N[ce]??{resolvedName:Y.type,colorLabel:_c(Y.color)};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 16px"},children:[r.jsx("span",{title:`Required: ${K} - ${ie}`,children:r.jsx(Uw,{className:"w-3 h-3",fill:Y.color,stroke:Y.color})}),r.jsxs("span",{className:"text-white truncate flex items-center gap-1",children:[R&&Y.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:Y.nozzle_id===1?d("printModal.leftNozzleTooltip"):d("printModal.rightNozzleTooltip"),children:Y.nozzle_id===1?d("printModal.leftNozzle"):d("printModal.rightNozzle")}),K," ",r.jsxs("span",{className:"text-bambu-gray",children:["(",Y.used_grams,"g)"]})]}),r.jsx("span",{className:"text-bambu-gray",children:"→"}),r.jsxs("select",{value:Y.loaded?.globalTrayId??"",onChange:ue=>X(de,ue.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 ${Y.status==="match"?"border-bambu-green/50 text-bambu-green":Y.status==="type_only"?"border-yellow-400/50 text-yellow-400":"border-orange-400/50 text-orange-400"} ${Y.isManual?"ring-1 ring-blue-400/50":""}`,title:Y.isManual?"Manually selected":"Auto-matched",children:[r.jsx("option",{value:"",className:"bg-bambu-dark text-bambu-gray",children:"-- Select slot --"}),x.filter(ue=>Y.nozzle_id==null||I||ue.extruderId===Y.nozzle_id).map(ue=>{const he=j.get(ue.globalTrayId),ge=he!=null?d("printModal.slotRemainingShort",{grams:he,defaultValue:` - ${he}g left`}):"",q=I?O(ue.globalTrayId):null,Q=q==null?"":` [${d(q===1?"printModal.leftNozzle":"printModal.rightNozzle")}]`;return r.jsxs("option",{value:ue.globalTrayId,className:"bg-bambu-dark text-white",children:[ue.label,": ",ue.traySubBrands||ue.type," (",ue.colorName,")",ge,Q]},ue.globalTrayId)})]}),Y.status==="match"?r.jsx(_r,{className:"w-3 h-3 text-bambu-green"}):Y.status==="type_only"?r.jsx("span",{title:"Same type, different color",children:r.jsx(xa,{className:"w-3 h-3 text-yellow-400"})}):r.jsx("span",{title:"Filament type not loaded",children:r.jsx(xa,{className:"w-3 h-3 text-orange-400"})})]}),oe&&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:l?.[de]??!1,onChange:ue=>c(de,ue.target.checked),className:"accent-bambu-green w-3 h-3"}),r.jsx(nv,{className:"w-3 h-3"}),d("printModal.forceColorMatch")]})]},ce)}),r.jsxs("div",{className:"text-xs text-bambu-gray",children:[d("printModal.totalCost")," ",r.jsx("span",{className:"text-white",children:D>0||C?`${i}${D.toFixed(2)}`:"N/A"})]}),k&&r.jsx("p",{className:"text-xs text-orange-400 mt-2",children:"Required filament type not found in printer."})]})]})}function I9e({filamentReqs:t,availableFilaments:e,overrides:a,onChange:n,forceColorMatch:i,onForceColorMatchChange:s}){const{t:o}=wt(),l=Lse(t?.filaments),c=y.useMemo(()=>{const m={};for(const p of e){const f=M1(p.type);m[f]||(m[f]=[]),m[f].push(p)}return m},[e]),d=t?.filaments;if(!d||d.length===0||e.length===0)return null;const u=(m,p)=>{if(p===""){const f={...a};delete f[m],n(f)}else{const[f,g]=p.split("|");n({...a,[m]:{type:f,color:g}})}};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:d.map((m,p)=>{const f=a[m.slot_id],g=!!f,v=c[M1(m.type)]||[],b=m.nozzle_id!=null?v.filter(k=>k.extruder_id==null||k.extruder_id===m.nozzle_id):v,{resolvedName:x,colorLabel:S}=l[p]??{resolvedName:m.type,colorLabel:_c(m.color)};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")}: ${x} - ${S}`,children:r.jsx(Uw,{className:"w-3 h-3",fill:m.color,stroke:m.color})}),r.jsxs("span",{className:"text-white truncate",children:[x," ",r.jsxs("span",{className:"text-bambu-gray",children:["(",m.used_grams,"g)"]})]}),r.jsx("span",{className:"text-bambu-gray",children:"→"}),r.jsxs("select",{value:g?`${f.type}|${f.color}`:"",onChange:k=>u(m.slot_id,k.target.value),disabled:b.length===0,className:`flex-1 px-2 py-1 rounded border text-xs bg-bambu-dark-secondary focus:outline-none focus:ring-1 focus:ring-bambu-green ${g?"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"),": ",x," (",S,")"]}),b.map((k,P)=>r.jsxs("option",{value:`${k.type}|${k.color}`,className:"bg-bambu-dark text-white",children:[k.tray_sub_brands||k.type," (",_c(k.color),")"]},`${k.type}-${k.color}-${k.tray_sub_brands}-${P}`))]}),g?r.jsx("button",{type:"button",onClick:()=>u(m.slot_id,""),className:"text-bambu-gray hover:text-white transition-colors",title:o("printModal.resetToOriginal"),children:r.jsx(bs,{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?.[m.slot_id]??!1,onChange:k=>s?.(m.slot_id,k.target.checked),className:"accent-bambu-green w-3 h-3"}),r.jsx(nv,{className:"w-3 h-3"}),o("printModal.forceColorMatch")]})]},m.slot_id)})})]})}function O9e({plates:t,isMultiPlate:e,selectedPlates:a,onToggle:n,onSelectAll:i,onDeselectAll:s,multiSelect:o}){const{t:l}=wt();if(!e||t.length<=1)return null;const c=a.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(tn,{className:"w-4 h-4 text-bambu-gray"}),r.jsxs("span",{className:"text-sm text-bambu-gray",children:["Select Plate",o?"s":""," to Print"]}),a.size===0&&r.jsxs("span",{className:"text-xs text-orange-400 flex items-center gap-1",children:[r.jsx(xa,{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=a.has(d.index);return r.jsxs("button",{type:"button",onClick:()=>n(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(xs,{className:"w-4 h-4 text-bambu-green flex-shrink-0"}):r.jsx(so,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"})),d.has_thumbnail&&d.thumbnail_url!=null?r.jsx("img",{src:zn(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(tn,{className:"w-5 h-5 text-bambu-gray"})}),r.jsxs("div",{className:"min-w-0 flex-1",children:[r.jsx("p",{className:"text-sm text-white font-medium truncate",children: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?` • ${ds(d.print_time_seconds)}`:""]}),(()=>{const m=wk(d.bed_type);return m?r.jsxs("p",{className:"text-xs text-bambu-gray flex items-center gap-1 mt-0.5 truncate",title:m.label,children:[r.jsx("img",{src:m.icon,alt:"",className:"w-3.5 h-3.5 object-contain flex-shrink-0"}),r.jsx("span",{className:"truncate",children:m.label})]}):null})()]}),!o&&u&&r.jsx(_r,{className:"w-4 h-4 text-bambu-green flex-shrink-0"})]},d.index)})})]})}const B9e=new Set(["IDLE","FINISH","FAILED"]);function U9e({printerResult:t,filamentReqs:e,onUpdateConfig:a}){const n=ia(),[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),a({useDefault:!1,manualMappings:m,autoConfigured:!1})},l=async()=>{s(!0);try{await ne.refreshPrinterStatus(t.printerId),await new Promise(d=>setTimeout(d,500)),await n.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(v=>v.globalTrayId===m),f=!0;else{const v=new Set(Object.values(t.config.manualMappings)),b=n.getQueryData(["settings"]);p=A9e(d,t.loadedFilaments,v,b?.prefer_lowest_filament)}let g="mismatch";if(p){const v=p.type?.toUpperCase()===d.type?.toUpperCase(),b=On(p.color)===On(d.color)||fd(p.color,d.color);v&&b?g="match":v&&(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} - ${_c(d.color)}`,children:r.jsx(Uw,{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(_r,{className:"w-3 h-3 text-bambu-green"}):m==="type_only"?r.jsx("span",{title:"Same type, different color",children:r.jsx(xa,{className:"w-3 h-3 text-yellow-400"})}):r.jsx("span",{title:"Filament type not loaded",children:r.jsx(xa,{className:"w-3 h-3 text-orange-400"})})]},f))]})}function H9e({printers:t,selectedPrinterIds:e,onMultiSelect:a,isLoading:n=!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:v,onTargetLocationChange:b,slicedForModel:x}){const[S,k]=y.useState(!1),P=s?t:t.filter(ie=>ie.is_active),N=dp({queries:P.map(ie=>({queryKey:["printerStatus",ie.id],queryFn:()=>ne.getPrinterStatus(ie.id),staleTime:5e3}))}),T=y.useMemo(()=>{const ie=new Map;return P.forEach((ue,he)=>{const ge=N[he];ge?.data&&ie.set(ue.id,ge.data)}),ie},[P,N]),j=ie=>{const ue=T.get(ie);return ue?ue.connected?!B9e.has(ue.state??""):!0:!1},D=ie=>{const ue=T.get(ie);if(!ue)return null;if(!ue.connected)return"Offline";const he=ue.state;return he?he==="RUNNING"?ue.stg_cur_name||"Printing":he==="PREPARE"?"Preparing":he==="PAUSE"?"Paused":he==="IDLE"?"Idle":he==="FINISH"?"Finished":he==="FAILED"?"Failed":he:null},C=y.useMemo(()=>{if(m!=="printer"||!x||S)return P;const ie=P.filter(ue=>ue.model===x);return ie.length>0?ie:P},[P,m,x,S]),E=P.length-C.length,R=y.useMemo(()=>{const ie=P.map(ue=>ue.model).filter(ue=>!!ue);return[...new Set(ie)].sort()},[P]),I=y.useMemo(()=>{if(!f)return[];const ie=P.filter(ue=>ue.model===f&&ue.location).map(ue=>ue.location).filter(ue=>!!ue);return[...new Set(ie)].sort()},[P,f]),O=p&&g&&R.length>0,z=i&&e.length>1&&l&&c?.filaments&&c.filaments.length>0&&d&&u;if(n)return r.jsx("div",{className:"flex justify-center py-8",children:r.jsx(lt,{className:"w-6 h-6 text-bambu-green animate-spin"})});if(C.length===0)return r.jsxs("div",{className:"flex items-center gap-2 text-red-400 text-sm mb-4",children:[r.jsx(wn,{className:"w-4 h-4"}),"No ",s?"":"active ","printers available"]});const X=ie=>{o&&j(ie)||(i?e.includes(ie)?a(e.filter(ue=>ue!==ie)):a([...e,ie]):a([ie]))},ae=()=>{const ie=o?C.filter(ue=>!j(ue.id)):C;a(ie.map(ue=>ue.id))},Y=()=>{a([])},ce=(ie,ue,he)=>{he.stopPropagation(),!(!d||!u)&&(ue?d(ie):u(ie,{useDefault:!0,manualMappings:{},autoConfigured:!1}))},de=ie=>e.includes(ie),oe=e.length,K=ie=>l?.find(ue=>ue.printerId===ie);return r.jsxs("div",{className:"space-y-2 mb-6",children:[O&&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(xr,{className:"w-4 h-4"}),r.jsx("span",{className:"text-sm",children:"Specific Printer"})]}),r.jsxs("button",{type:"button",onClick:()=>{p("model"),a([]);const ie=x&&R.includes(x)?x:R[0];g(ie)},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(Sm,{className:"w-4 h-4"}),r.jsxs("span",{className:"text-sm",children:["Any ",x||"Model"]})]})]}),m==="model"&&O&&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:ie=>{g(ie.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..."}),R.map(ie=>r.jsx("option",{value:ie,children:ie},ie))]})]}),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:v||"",onChange:ie=>b(ie.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(ie=>r.jsx("option",{value:ie,children:ie},ie))]})]}),f&&r.jsxs("p",{className:"text-xs text-bambu-gray",children:["Scheduler will assign to first available idle ",f," printer",v?` in ${v}`:""]})]}),m==="printer"&&i&&C.length>1&&r.jsxs("div",{className:"flex items-center justify-between text-xs text-bambu-gray mb-2",children:[r.jsx("span",{children:oe===0?"Select printers":`${oe} printer${oe!==1?"s":""} selected`}),r.jsxs("div",{className:"flex gap-2",children:[oe0&&r.jsx("button",{type:"button",onClick:Y,className:"text-bambu-gray hover:text-white transition-colors",children:"Clear"})]})]}),m==="printer"&&C.map(ie=>{const ue=de(ie.id),he=K(ie.id),ge=he&&!he.config.useDefault,q=j(ie.id),Q=o&&q,A=D(ie.id);return r.jsxs("div",{children:[r.jsxs("button",{type:"button",onClick:()=>X(ie.id),disabled:Q,className:`w-full flex items-center gap-3 p-3 rounded-lg border transition-colors ${Q?"border-bambu-dark-tertiary bg-bambu-dark opacity-50 cursor-not-allowed":ue?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary bg-bambu-dark hover:border-bambu-gray"} ${ie.is_active?"":"opacity-60"}`,children:[r.jsx("div",{className:`p-2 rounded-lg ${Q?"bg-bambu-dark-tertiary":ue?"bg-bambu-green/20":"bg-bambu-dark-tertiary"}`,children:r.jsx(xr,{className:`w-5 h-5 ${Q?"text-bambu-gray/50":ue?"text-bambu-green":"text-bambu-gray"}`})}),r.jsxs("div",{className:"text-left flex-1",children:[r.jsxs("p",{className:`font-medium ${Q?"text-bambu-gray":"text-white"}`,children:[ie.name,!ie.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:[ie.model||"Unknown model"," • ",ie.ip_address]})]}),A&&r.jsx("span",{className:`text-xs px-2 py-0.5 rounded-full ${q?"bg-yellow-500/20 text-yellow-400":"bg-bambu-green/20 text-bambu-green"}`,children:A}),i&&r.jsx("div",{className:`w-5 h-5 rounded border-2 flex items-center justify-center transition-colors ${Q?"border-bambu-gray/30":ue?"bg-bambu-green border-bambu-green":"border-bambu-gray/50"}`,children:ue&&r.jsx(_r,{className:"w-3 h-3 text-white"})})]}),ue&&z&&he&&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:F=>F.stopPropagation(),children:[r.jsx("input",{type:"checkbox",checked:ge,onChange:F=>ce(ie.id,F.target.checked,F),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 ${he.matchStatus==="full"?"text-bambu-green":he.matchStatus==="partial"?"text-yellow-400":"text-orange-400"}`,children:["(",he.exactMatches,"/",he.totalSlots," matched)"]}),he.isLoading&&r.jsx(tr,{className:"w-3 h-3 text-bambu-gray animate-spin"}),ge&&r.jsxs("button",{type:"button",onClick:F=>{F.stopPropagation(),d(ie.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(qI,{className:"w-3 h-3"}),"Auto"]})]}),ge&&r.jsx(U9e,{printerResult:he,filamentReqs:c.filaments,onUpdateConfig:F=>u(ie.id,F)})]})]},ie.id)}),m==="printer"&&E>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(xa,{className:"w-3 h-3 text-yellow-400"}),E," other printer",E>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"&&oe===0&&r.jsxs("p",{className:"text-xs text-orange-400 mt-1 flex items-center gap-1",children:[r.jsx(wn,{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(wn,{className:"w-3 h-3"}),"Select a target printer model"]})]})}function q9e({options:t,onChange:e,defaultExpanded:a=!1,showDualNozzleOptions:n=!1}){const{t:i}=wt(),[s,o]=y.useState(a),c=[{key:"bed_levelling",label:i("settings.defaultBedLevelling"),desc:i("settings.defaultBedLevellingDesc")},{key:"flow_cali",label:i("settings.defaultFlowCali"),desc:i("settings.defaultFlowCaliDesc")},{key:"vibration_cali",label:i("settings.defaultVibrationCali"),desc:i("settings.defaultVibrationCaliDesc")},{key:"layer_inspect",label:i("settings.defaultLayerInspect"),desc:i("settings.defaultLayerInspectDesc")},{key:"timelapse",label:i("settings.defaultTimelapse"),desc:i("settings.defaultTimelapseDesc")},{key:"nozzle_offset_cali",label:i("settings.defaultNozzleOffsetCali"),desc:i("settings.defaultNozzleOffsetCaliDesc"),dualNozzleOnly:!0}].filter(u=>!u.dualNozzleOnly||n),d=u=>{e({...t,[u]:!t[u]})};return r.jsxs("div",{className:"mb-4",children:[r.jsxs("button",{type:"button",onClick:()=>o(!s),className:"flex items-center gap-2 text-sm text-bambu-gray hover:text-white transition-colors w-full",children:[r.jsx(Sy,{className:"w-4 h-4"}),r.jsx("span",{children:i("queue.bulkEdit.printOptions")}),s?r.jsx(el,{className:"w-4 h-4 ml-auto"}):r.jsx(za,{className:"w-4 h-4 ml-auto"})]}),s&&r.jsx("div",{className:"mt-2 bg-bambu-dark rounded-lg p-3 space-y-2",children:c.map(({key:u,label:m,desc:p})=>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:m}),r.jsx("p",{className:"text-xs text-bambu-gray",children:p})]}),r.jsx("div",{className:`relative w-10 h-5 rounded-full transition-colors ${t[u]?"bg-bambu-green":"bg-bambu-dark-tertiary"}`,onClick:()=>d(u),children:r.jsx("div",{className:`absolute top-0.5 w-4 h-4 rounded-full bg-white transition-transform ${t[u]?"translate-x-5":"translate-x-0.5"}`})})]},u))})]})}function V9e({options:t,onChange:e,dateFormat:a="system",timeFormat:n="system",canControlPrinter:i=!0,showStagger:s=!1,printerCount:o=0,hasGcodeSnippets:l=!1}){const{t:c}=wt(),[d,u]=y.useState(""),[m,p]=y.useState(""),[f,g]=y.useState(!0),[v,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 C;t.scheduledTime?(C=new Date(t.scheduledTime),isNaN(C.getTime())&&(C=new Date,C.setHours(C.getHours()+1,0,0,0))):(C=new Date,C.setHours(C.getHours()+1,0,0,0),e({...t,scheduledTime:b3(C)})),u(g3(C,a)),p(H8(C,n)),g(!0),b(!0)}},[t.scheduleType,t.scheduledTime,a,n,e,t]);const k=C=>{e({...t,scheduleType:C})},P=(C,E)=>{const R=D0e(C,a),I=F0e(E);g(!!R),b(!!I),R&&I&&(R.setHours(I.hours,I.minutes,0,0),R>new Date&&e({...t,scheduledTime:b3(R)}))},N=C=>{u(C),P(C,m)},T=C=>{p(C),P(d,C)},j=C=>{const E=C.target.value;if(E){const R=new Date(E);isNaN(R.getTime())||(u(g3(R,a)),p(H8(R,n)),g(!0),b(!0),e({...t,scheduledTime:E}))}},D=()=>{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(ar,{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(Cn,{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(lJ,{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:C=>N(C.target.value),placeholder:j0e(a)}),r.jsx("button",{type:"button",onClick:D,className:"absolute right-2 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white",title:"Open calendar",children:r.jsx(Cn,{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:j,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 ${v?"border-bambu-dark-tertiary focus:border-bambu-green":"border-red-500"}`,value:m,onChange:C=>T(C.target.value),placeholder:M0e(n)})})]}),(!f||!v)&&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:C=>e({...t,requirePreviousSuccess:C.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:C=>e({...t,autoOffAfter:C.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(Nu,{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:C=>e({...t,gcodeInjection:C.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(tv,{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:C=>e({...t,staggerEnabled:C.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(tn,{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:C=>e({...t,staggerGroupSize:Math.max(1,parseInt(C.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:C=>e({...t,staggerIntervalMinutes:Math.max(1,parseInt(C.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 C=Math.ceil(o/t.staggerGroupSize),E=o%t.staggerGroupSize,R=(C-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:C,size:t.staggerGroupSize,interval:t.staggerIntervalMinutes}),E!==0&&t.staggerGroupSize1?` (${c("printModal.staggerTotal","total: {{minutes}} min",{minutes:R})})`:""]})})()]})]}),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 Sl={bed_levelling:!0,flow_cali:!1,vibration_cali:!0,layer_inspect:!1,timelapse:!1,nozzle_offset_cali:!0},AF={scheduleType:"asap",scheduledTime:"",requirePreviousSuccess:!1,autoOffAfter:!1,gcodeInjection:!1,staggerEnabled:!1,staggerGroupSize:2,staggerIntervalMinutes:5};function Pc({mode:t,archiveId:e,libraryFileId:a,archiveName:n,queueItem:i,initialSelectedPrinterIds:s,onClose:o,onSuccess:l,projectId:c,cleanupLibraryAfterDispatch:d}){const{t:u}=wt(),m=ia(),{showToast:p}=da(),{hasPermission:f}=lr(),g=!!a&&!e,[v,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,[P,N]=y.useState(1),[T,j]=y.useState(()=>t==="edit-queue-item"&&i?{bed_levelling:i.bed_levelling??Sl.bed_levelling,flow_cali:i.flow_cali??Sl.flow_cali,vibration_cali:i.vibration_cali??Sl.vibration_cali,layer_inspect:i.layer_inspect??Sl.layer_inspect,timelapse:i.timelapse??Sl.timelapse,nozzle_offset_cali:i.nozzle_offset_cali??Sl.nozzle_offset_cali}:Sl),[D,C]=y.useState(()=>{if(t==="edit-queue-item"&&i){let Ce="asap";i.manual_start?Ce="manual":i.scheduled_time&&!pY(i.scheduled_time)&&(Ce="scheduled");let Ke="";if(i.scheduled_time&&!pY(i.scheduled_time)){const nt=Ga(i.scheduled_time)??new Date;Ke=b3(nt)}return{scheduleType:Ce,scheduledTime:Ke,requirePreviousSuccess:i.require_previous_success,autoOffAfter:i.auto_off_after,gcodeInjection:i.gcode_injection??!1,staggerEnabled:!1,staggerGroupSize:AF.staggerGroupSize,staggerIntervalMinutes:AF.staggerIntervalMinutes}}return AF}),[E,R]=y.useState(()=>{if(t==="edit-queue-item"&&i?.ams_mapping&&Array.isArray(i.ams_mapping)){const Ce={};return i.ams_mapping.forEach((Ke,nt)=>{Ke!==-1&&(Ce[nt+1]=Ke)}),Ce}return{}}),[I,O]=y.useState({}),[z,X]=y.useState(()=>t==="edit-queue-item"&&i?.target_model?"model":"printer"),[ae,Y]=y.useState(()=>t==="edit-queue-item"&&i?.target_model?i.target_model:null),[ce,de]=y.useState(()=>t==="edit-queue-item"&&i?.target_location?i.target_location:null),[oe,K]=y.useState(()=>{if(t==="edit-queue-item"&&i?.filament_overrides){const Ce={};for(const Ke of i.filament_overrides)Ce[Ke.slot_id]={type:Ke.type,color:Ke.color};return Ce}return{}}),[ie,ue]=y.useState(()=>{if(t==="edit-queue-item"&&i?.filament_overrides){const Ce={};for(const Ke of i.filament_overrides)Ce[Ke.slot_id]=Ke.force_color_match===!0;return Ce}return{}}),[he]=y.useState(()=>t==="edit-queue-item"&&i?.printer_id?[i.printer_id]:[]),[ge]=y.useState(()=>t==="edit-queue-item"&&i?i.plate_id:null),[q,Q]=y.useState(!1),[A,F]=y.useState({current:0,total:0}),[B,W]=y.useState(null),[H,le]=y.useState(new Set),U=v.length,G=v.length>0?v[0]:null,{data:Z}=$e({queryKey:["settings"],queryFn:ne.getSettings}),J=y.useRef(!1);y.useEffect(()=>{!Z||J.current||t==="edit-queue-item"||(J.current=!0,j({bed_levelling:Z.default_bed_levelling??Sl.bed_levelling,flow_cali:Z.default_flow_cali??Sl.flow_cali,vibration_cali:Z.default_vibration_cali??Sl.vibration_cali,layer_inspect:Z.default_layer_inspect??Sl.layer_inspect,timelapse:Z.default_timelapse??Sl.timelapse,nozzle_offset_cali:Z.default_nozzle_offset_cali??Sl.nozzle_offset_cali}))},[Z,t]);const re=y.useRef(!1);y.useEffect(()=>{!Z||re.current||t==="edit-queue-item"||(re.current=!0,C(Ce=>({...Ce,staggerGroupSize:Z.stagger_group_size??Ce.staggerGroupSize,staggerIntervalMinutes:Z.stagger_interval_minutes??Ce.staggerIntervalMinutes})))},[Z,t]);const se=Vo(Z?.currency||"USD"),fe=Z?.default_filament_cost??0,{data:me,isLoading:pe}=$e({queryKey:["printers"],queryFn:ne.getPrinters}),{data:V}=$e({queryKey:["spool-assignments"],queryFn:()=>ne.getAssignments(),staleTime:30*1e3,enabled:(t==="reprint"||t==="add-to-queue")&&z==="printer"||g&&t==="reprint"}),{data:L}=$e({queryKey:["archive",e],queryFn:()=>ne.getArchive(e),enabled:!!e&&!g}),{data:te}=$e({queryKey:["library-file",a],queryFn:()=>ne.getLibraryFile(a),enabled:g&&!!a}),be=L?.sliced_for_model||te?.sliced_for_model||null,{data:xe,isError:ve}=$e({queryKey:["archive-plates",e],queryFn:()=>ne.getArchivePlates(e),enabled:!!e&&!g,retry:!1}),{data:De}=$e({queryKey:["library-file-plates",a],queryFn:()=>ne.getLibraryFilePlates(a),enabled:g&&!!a}),je=g?De:xe,{data:Te,isError:qe}=$e({queryKey:["archive-filaments",e,k],queryFn:()=>ne.getArchiveFilamentRequirements(e,k??void 0),enabled:!!e&&!g&&(k!==null||!je?.is_multi_plate),retry:!1}),{data:Pe}=$e({queryKey:["library-file-filaments",a,k],queryFn:()=>ne.getLibraryFileFilamentRequirements(a,k??void 0),enabled:g&&!!a&&(k!==null||!je?.is_multi_plate)}),Ie=!g&&(ve||qe),Re=g?Pe:Te,Ue=y.useMemo(()=>{if(!(k===null||!je?.plates?.length))return je.plates.find(Ce=>Ce.index===k)?.name||void 0},[je,k]),{data:ze}=$e({queryKey:["available-filaments",ae,ce],queryFn:()=>ne.getAvailableFilaments(ae,ce??void 0),enabled:z==="model"&&!!ae}),{data:it}=$e({queryKey:["printer-status",G],queryFn:()=>ne.getPrinterStatus(G),enabled:!!G}),{amsMapping:Oe}=Dse(Re,it,E,Z?.prefer_lowest_filament),tt=D9e(v,me,Re,E,I,O,Z?.prefer_lowest_filament);y.useEffect(()=>{je?.plates&&je.plates.length>=1&&x.size===0&&S(new Set([je.plates[0].index]))},[je,x.size]),y.useEffect(()=>{if(t==="edit-queue-item")return;const Ce=me?.filter(Ke=>Ke.is_active)||[];Ce.length===1&&v.length===0&&b([Ce[0].id])},[t,me,v.length]),y.useEffect(()=>{t==="edit-queue-item"?(JSON.stringify(v.sort())!==JSON.stringify(he.sort())||k!==ge)&&(R({}),O({}),le(new Set)):(R({}),O({}),le(new Set))},[t,v,k,he,ge]);const[Fe,Ye]=y.useState(ae),[Ve,Me]=y.useState(k);y.useEffect(()=>{(ae!==Fe||k!==Ve)&&(Ye(ae),Me(k),(t!=="edit-queue-item"||Fe!==null)&&(K({}),ue({})))},[ae,k,Fe,Ve,t]),y.useEffect(()=>{if(!Z?.per_printer_mapping_expanded||v.length<=1)return;const Ce=v.filter(Ke=>{if(H.has(Ke))return!1;const nt=tt.printerResults.find(Ae=>Ae.printerId===Ke);return nt&&nt.status&&!nt.isLoading});Ce.length>0&&(le(Ke=>{const nt=new Set(Ke);return Ce.forEach(Ae=>nt.add(Ae)),nt}),Ce.forEach(Ke=>{tt.autoConfigurePrinter(Ke)}))},[Z?.per_printer_mapping_expanded,v,H,tt]),y.useEffect(()=>{const Ce=Ke=>{Ke.key==="Escape"&&!q&&o()};return window.addEventListener("keydown",Ce),()=>window.removeEventListener("keydown",Ce)},[o,q]);const Be=je?.is_multi_plate??!1,Qe=je?.plates??[],Ge=y.useMemo(()=>{const Ce=new Map;return V&&V.forEach(Ke=>{const nt=Ke.ams_id===255,Ae=ib(Ke.ams_id,Ke.tray_id,nt),we=Ce.get(Ke.printer_id)??new Map;we.set(Ae,Ke),Ce.set(Ke.printer_id,we)}),Ce},[V]),Ee=y.useMemo(()=>{if(!B||B.length===0)return"";const Ce=B.map(Ke=>u("printModal.insufficientFilamentLine",{printer:Ke.printerName,slot:Ke.slotLabel,required:Math.round(Ke.requiredGrams),remaining:Math.round(Ke.remainingGrams)}));return[u("printModal.insufficientFilamentMessage"),...Ce].join(` +${l("inventory.assignReconfigureNote")}`,r.jsx(ka,{title:l("inventory.assignMismatchTitle"),message:A,confirmText:l("inventory.assignMismatchConfirm"),variant:"warning",overlayZIndex:"z-[110]",isLoading:Y.isPending,onConfirm:Q,onCancel:()=>{Y.isPending||(N(!1),k(null),j(null))}})})()]})}const p9e={bambuModelByShortCode:{}},tY={"A1 MINI":["A1M"]};function Pz(t,e){const a=t.toUpperCase(),n=e.toUpperCase();if(a===n)return!0;const i=tY[n];if(i&&i.includes(a))return!0;const s=tY[a];return!!(s&&s.includes(n))}function h9e(t){const e={};for(const[a,n]of Object.entries(t))n in e||(e[n]=a.replace(/^Bambu Lab\s+/,""));return e}function f9e(t={}){return{bambuModelByShortCode:h9e(t)}}function aY(t){return t.replace(/\s+/g,"").toLowerCase()}const g9e="0.4";function yse(t){const e=t.match(/^(.*?)\s+([\d.]+)\s*nozzle\s*$/i);return e?{stripped:e[1].trim(),nozzle:e[2]}:{stripped:t.trim(),nozzle:null}}function b9e(t){const e="@BBL ",a=t.indexOf(e);if(a<0)return null;const n=t.slice(a+e.length).trim(),{stripped:i,nozzle:s}=yse(n);return i?{token:i,nozzle:s}:null}function x9e(t){const e=t.match(/^Bambu Lab\s+(.+)$/i);if(!e)return null;const{stripped:a,nozzle:n}=yse(e[1]);return a?{model:a,nozzle:n}:null}function y9e(t,e,a){const n=b9e(t);if(!n)return"unknown";const i=a[n.token]??n.token,s=x9e(e);return s?aY(s.model)!==aY(i)&&!Pz(n.token,s.model)||s.nozzle!==null&&(n.nozzle??g9e)!==s.nozzle?"mismatch":"match":"unknown"}function Uy(t,e,a,n){if(!a)return"unknown";const i=t.compatible_printers;return i&&i.length>0?i.includes(a)?"match":"mismatch":y9e(t.name,a,n.bambuModelByShortCode)}const vse=["PLA","PETG","ABS","TPU","ASA","PC","PA","PVA","HIPS","PA-CF","PETG-CF","PLA-CF"],v9e=["Bambu","PolyLite","PolyTerra","eSUN","Overture","Fiberon","SUNLU","Inland","Hatchbox","Generic"],gw=["Basic","Matte","Silk","Silk+","Tough","Tough+","HF","High Flow","Engineering","CF","GF","Galaxy","Glow","Marble","Metal","Rainbow","Sparkle","Wood","Translucent","Transparent","Clear","Lite","Pro","Plus","Max","Super","Ultra","Flex","Soft","Hard","Strong","Impact","Heat Resistant","UV Resistant","ESD","Conductive","Magnetic","Gradient","Dual Color","Tri Color","Multicolor"],wse=[{name:"Black",hex:"000000"},{name:"White",hex:"FFFFFF"},{name:"Gray",hex:"808080"},{name:"Red",hex:"FF0000"},{name:"Orange",hex:"FFA500"},{name:"Yellow",hex:"FFFF00"},{name:"Green",hex:"00AE42"},{name:"Blue",hex:"0066FF"},{name:"Purple",hex:"8B00FF"},{name:"Pink",hex:"FF69B4"},{name:"Brown",hex:"8B4513"},{name:"Silver",hex:"C0C0C0"},{name:"Clear",hex:"00000000"}],w9e=[{name:"Dark Red",hex:"8B0000"},{name:"Crimson",hex:"DC143C"},{name:"Coral",hex:"FF7F50"},{name:"Salmon",hex:"FA8072"},{name:"Dark Orange",hex:"FF8C00"},{name:"Peach",hex:"FFDAB9"},{name:"Gold",hex:"FFD700"},{name:"Khaki",hex:"F0E68C"},{name:"Lemon",hex:"FFF44F"},{name:"Lime",hex:"32CD32"},{name:"Forest Green",hex:"228B22"},{name:"Olive",hex:"808000"},{name:"Mint",hex:"98FF98"},{name:"Teal",hex:"008080"},{name:"Navy",hex:"000080"},{name:"Sky Blue",hex:"87CEEB"},{name:"Royal Blue",hex:"4169E1"},{name:"Cyan",hex:"00FFFF"},{name:"Turquoise",hex:"40E0D0"},{name:"Violet",hex:"EE82EE"},{name:"Magenta",hex:"FF00FF"},{name:"Indigo",hex:"4B0082"},{name:"Lavender",hex:"E6E6FA"},{name:"Plum",hex:"DDA0DD"},{name:"Hot Pink",hex:"FF69B4"},{name:"Rose",hex:"FF007F"},{name:"Blush",hex:"FFB6C1"},{name:"Chocolate",hex:"D2691E"},{name:"Tan",hex:"D2B48C"},{name:"Beige",hex:"F5F5DC"},{name:"Maroon",hex:"800000"},{name:"Dark Gray",hex:"404040"},{name:"Light Gray",hex:"D3D3D3"},{name:"Charcoal",hex:"36454F"},{name:"Ivory",hex:"FFFFF0"},{name:"Bambu Green",hex:"00AE42"},{name:"Jade White",hex:"E8E8E8"},{name:"Titan Gray",hex:"5A5A5A"}],rY=[...wse,...w9e],Sse="bambuddy-recent-colors",S9e=8,k9e=[{code:"GFL00",name:"Bambu PLA Basic",displayName:"Bambu PLA Basic",isCustom:!1,allCodes:["GFL00"]},{code:"GFL01",name:"Bambu PLA Matte",displayName:"Bambu PLA Matte",isCustom:!1,allCodes:["GFL01"]},{code:"GFL05",name:"Generic PLA",displayName:"Generic PLA",isCustom:!1,allCodes:["GFL05"]},{code:"GFG00",name:"Bambu PETG Basic",displayName:"Bambu PETG Basic",isCustom:!1,allCodes:["GFG00"]},{code:"GFG05",name:"Generic PETG",displayName:"Generic PETG",isCustom:!1,allCodes:["GFG05"]},{code:"GFB00",name:"Bambu ABS Basic",displayName:"Bambu ABS Basic",isCustom:!1,allCodes:["GFB00"]},{code:"GFB05",name:"Generic ABS",displayName:"Generic ABS",isCustom:!1,allCodes:["GFB05"]},{code:"GFA00",name:"Bambu ASA Basic",displayName:"Bambu ASA Basic",isCustom:!1,allCodes:["GFA00"]},{code:"GFU00",name:"Bambu TPU 95A",displayName:"Bambu TPU 95A",isCustom:!1,allCodes:["GFU00"]},{code:"GFU05",name:"Generic TPU",displayName:"Generic TPU",isCustom:!1,allCodes:["GFU05"]},{code:"GFC00",name:"Bambu PC Basic",displayName:"Bambu PC Basic",isCustom:!1,allCodes:["GFC00"]},{code:"GFN00",name:"Bambu PA Basic",displayName:"Bambu PA Basic",isCustom:!1,allCodes:["GFN00"]},{code:"GFN05",name:"Generic PA",displayName:"Generic PA",isCustom:!1,allCodes:["GFN05"]},{code:"GFS00",name:"Bambu PLA-CF",displayName:"Bambu PLA-CF",isCustom:!1,allCodes:["GFS00"]},{code:"GFT00",name:"Bambu PETG-CF",displayName:"Bambu PETG-CF",isCustom:!1,allCodes:["GFT00"]},{code:"GFNC0",name:"Bambu PA-CF",displayName:"Bambu PA-CF",isCustom:!1,allCodes:["GFNC0"]},{code:"GFV00",name:"Bambu PVA",displayName:"Bambu PVA",isCustom:!1,allCodes:["GFV00"]}];function lf(t){let e=t.replace(/@.*$/,"").trim();e=e.replace(/\(Custom\)/i,"").trim(),e=e.replace(/^[#*]+\s*/,"").trim();const a=["PLA-CF","PETG-CF","ABS-GF","ASA-CF","PA-CF","PAHT-CF","PA6-CF","PA6-GF","PPA-CF","PPA-GF","PET-CF","PPS-CF","PC-CF","PC-ABS","ABS-GF","PCTG","PETG","PLA","ABS","ASA","PC","PA","TPU","PVA","HIPS","BVOH","PPS","PEEK","PEI"];let n="",i=-1;for(const c of a){const d=e.toUpperCase().indexOf(c.toUpperCase());if(d!==-1){n=c,i=d;break}}let s="";i>0&&(s=e.substring(0,i).trim(),s=s.replace(/[-_\s]+$/,""));let o="";i!==-1&&n&&(o=e.substring(i+n.length).trim(),o=o.replace(/^[-_\s]+/,""));let l="";for(const c of gw)if(o.toLowerCase().includes(c.toLowerCase())){l=c;break}if(!l&&s)for(const c of gw){const d=new RegExp(`\\s+${c}$`,"i");if(d.test(s)){l=c,s=s.replace(d,"").trim();break}}return{brand:s,material:n,variant:l}}function kse(t,e){const a=new Set(v9e);for(const n of t){const{brand:i}=lf(n.name);i&&i.length>1&&a.add(i)}if(e)for(const n of e)if(n.filament_vendor&&n.filament_vendor.length>1)a.add(n.filament_vendor);else{const{brand:i}=lf(n.name);i&&i.length>1&&a.add(i)}return Array.from(a).sort((n,i)=>n.localeCompare(i))}function _9e(t){const e=t.filter(n=>n.preset_type==="filament");return e.length===0?[]:e.map(n=>{const i=String(n.id),s=n.filament_type||i,o=Array.from(new Set([i,s]));return{code:i,name:n.name,displayName:n.name,isCustom:!1,allCodes:o}}).sort((n,i)=>n.displayName.localeCompare(i.displayName))}function _se(t,e,a,n){const i=[],s=[],o=new Set;for(const u of t)if(u.is_custom){const m=u.name.toUpperCase();(e.size===0||Array.from(e).some(f=>m.includes(f))||!m.includes("@"))&&(i.push({code:u.setting_id,name:u.name,displayName:`${u.name} (Custom)`,isCustom:!0,allCodes:[u.setting_id]}),o.add(u.setting_id))}else s.push({code:u.setting_id,name:u.name,displayName:u.name,isCustom:!1,allCodes:[u.setting_id]}),o.add(u.setting_id);const l=a&&a.length>0?_9e(a):[],c=[];if(n&&n.length>0)for(const u of n){const m=u.filament_id.startsWith("GF")?"GFS"+u.filament_id.slice(2):u.filament_id;o.has(u.filament_id)||o.has(m)||c.push({code:u.filament_id,name:u.name,displayName:u.name,isCustom:!1,allCodes:[u.filament_id,m]})}const d=[...i,...s,...l,...c];return d.length===0?k9e:d.sort((u,m)=>u.displayName.localeCompare(m.displayName))}function Cse(t,e){if(!t)return;let a=e.find(n=>n.code===t);if(a||(a=e.find(n=>n.allCodes.includes(t))),!a){const n=t.toLowerCase();a=e.find(i=>i.code.toLowerCase()===n||i.allCodes.some(s=>s.toLowerCase()===n))}return a}function Pse(){try{const t=localStorage.getItem(Sse);if(t)return JSON.parse(t)}catch{}return[]}function Nse(t,e){const a=e.filter(i=>i.hex.toUpperCase()!==t.hex.toUpperCase()),n=[t,...a].slice(0,S9e);try{localStorage.setItem(Sse,JSON.stringify(n))}catch{}return n}function bw(t){if(!t)return"";let e=t.split("_")[0];return/^GFS/i.test(e)&&(e=e.slice(0,2)+e.slice(3)),e.toUpperCase()}function Tse(t){return!!t&&/^GF[A-Z]99$/i.test(t)}function PF(t,e){if(!e.material)return!1;const a=bw(e.slicer_filament),n=bw(t.filament_id);if(a&&n&&a===n&&!Tse(n))return!0;const s=(t.name||"").replace(/^High Flow[_\s]+/i,"").replace(/^Standard[_\s]+/i,"").replace(/^HF[_\s]+/i,"").replace(/^S[_\s]+/i,"").trim(),o=lf(s);return!(!(o.material.toUpperCase()===e.material.toUpperCase())||e.brand&&!(o.brand.toLowerCase().includes(e.brand.toLowerCase())||e.brand.toLowerCase().includes(o.brand.toLowerCase()))||e.subtype&&!(o.variant.toLowerCase().includes(e.subtype.toLowerCase())||e.subtype.toLowerCase().includes(o.variant.toLowerCase())||s.toLowerCase().includes(e.subtype.toLowerCase())))}function nY(t,e){if(t===255)return"External";let a,n=!1;t>=128&&t<=135?(a=t-128,n=!0):t>=0&&t<=3?(a=t,n=e===1):a=0,a=Math.max(0,Math.min(a,7));const i=String.fromCharCode(65+a);return n?`HT-${i}`:`AMS-${i}`}function NF(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 cg=["PLA","PETG","PCTG","ABS","ASA","TPU","PC","PA","NYLON","PVA","HIPS","PP","PET"];function iY(t){const e=t.replace(/@.+$/,"").trim(),a=e.toUpperCase(),n=a.match(/\bSUPPORT\s+FOR\s+/);if(n){const s=a.slice(n.index+n[0].length);for(const o of cg)if(new RegExp(`\\b${o}\\b`).test(s)){const c=e.slice(0,n.index).trim();return{material:o,brand:c,variant:"Support"}}}for(const s of cg){const o=new RegExp(`\\b${s}\\b`,"i");if(o.test(a)){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 C9e(t){return!t.startsWith("GF")&&!t.startsWith("P1")}const P9e={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"},sY=[{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"}],oY=[{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 lY(t){const e=t.toLowerCase().trim();return P9e[e]||null}function cY(t){const e=t.indexOf("@");if(e<0)return null;const n=t.slice(e+1).trim().match(/^BBL\s+(.+?)(?:\s+[\d.]+\s*nozzle)?$/i);return n?n[1].trim():null}function Ase({isOpen:t,onClose:e,printerId:a,slotInfo:n,nozzleDiameter:i="0.4",printerModel:s,onSuccess:o,fullScreen:l}){const{t:c}=wt(),[d,u]=y.useState(""),[m,p]=y.useState(null),[f,g]=y.useState(""),[v,b]=y.useState(""),[x,S]=y.useState(""),[k,P]=y.useState(!1),[N,T]=y.useState(!1),j=y.useRef(""),{data:D,isLoading:C,isError:E}=$e({queryKey:["cloudSettings"],queryFn:()=>ne.getCloudSettings(),enabled:t,retry:!1}),{data:R}=$e({queryKey:["orcaCloudProfilesForAmsSlot"],queryFn:()=>ne.orcaCloudListProfiles(),enabled:t,retry:!1}),{data:I,isLoading:O}=$e({queryKey:["localPresets"],queryFn:()=>ne.getLocalPresets(),enabled:t}),{data:z,isLoading:X}=$e({queryKey:["builtinFilaments"],queryFn:()=>ne.getBuiltinFilaments(),enabled:t,staleTime:1/0}),{data:ae,isLoading:Y}=$e({queryKey:["kprofiles",a,i],queryFn:()=>ne.getKProfiles(a,i),enabled:t&&!!a}),{data:ce}=$e({queryKey:["colorCatalog"],queryFn:()=>ne.getColorCatalog(),enabled:t,staleTime:1/0}),de=rt({mutationFn:async()=>{if(!d)throw new Error("No filament preset selected");const B=d.startsWith("local_"),W=d.startsWith("builtin_"),H=d.startsWith("orca_")?d.replace("orca_",""):d,le=!B&&!W?R?.filament.find(ze=>ze.setting_id===H):void 0,U=!!le,G=le??null,Z=B?parseInt(d.replace("local_",""),10):null,J=W?d.replace("builtin_",""):null,re=B?I?.filament.find(ze=>ze.id===Z):null,se=W?z?.find(ze=>ze.filament_id===J):null,fe=!B&&!W&&!U?D?.filament.find(ze=>ze.setting_id===d):null;if(!B&&!W&&!U&&!fe)throw new Error("Selected preset not found");if(B&&!re)throw new Error("Selected local preset not found");if(W&&!se)throw new Error("Selected builtin preset not found");if(U&&!G)throw new Error("Selected Orca Cloud preset not found");const me=B?re.name:W?se.name:U?G.name:fe.name,pe=iY(me),V=m?.slot_id??-1,L=f||n.trayColor?.slice(0,6)||"FFFFFF",te=me.replace(/@.+$/,"").trim();let be,xe;const ve=pe.material.toUpperCase(),De={PLA:"GFL99","PLA-CF":"GFL98","PLA SILK":"GFL96","PLA HIGH SPEED":"GFL95",PETG:"GFG99","PETG HF":"GFG96","PETG-CF":"GFG98",PCTG:"GFG97",ABS:"GFB99",ASA:"GFB98",PC:"GFC99",PA:"GFN99","PA-CF":"GFN98",NYLON:"GFN99",TPU:"GFU99",PVA:"GFS99",HIPS:"GFS98",PE:"GFP99",PP:"GFP97"};if(B){const ze=(cg.includes(ve)?ve:re?.filament_type||pe.material||"").toUpperCase();be=De[ze]||De[ze.replace(/[-\s]?CF$/,"")]||De[ze.replace(/\+$/,"")]||De[ze.split(/[-\s]/)[0]]||"",xe=""}else if(U){const ze=(cg.includes(ve)?ve:pe.material||"").toUpperCase();be=De[ze]||De[ze.replace(/[-\s]?CF$/,"")]||De[ze.replace(/\+$/,"")]||De[ze.split(/[-\s]/)[0]]||"",xe=""}else if(W)be=J,xe="";else if(be=NF(d),xe=d,!d.startsWith("GFS"))try{const ze=await ne.getCloudSettingDetail(d);ze.filament_id&&(be=ze.filament_id)}catch(ze){console.warn("Failed to fetch preset detail for filament_id:",ze)}let je=B&&re?.nozzle_temp_min?re.nozzle_temp_min:190,Te=B&&re?.nozzle_temp_max?re.nozzle_temp_max:230;if(!B||W||U||!re?.nozzle_temp_min&&!re?.nozzle_temp_max){const ze=(B?cg.includes(ve)?ve:re?.filament_type||pe.material||"":pe.material).toUpperCase();ze.includes("PLA")?(je=190,Te=230):ze.includes("PETG")?(je=220,Te=260):ze.includes("ABS")||ze.includes("ASA")?(je=240,Te=280):ze.includes("TPU")?(je=200,Te=240):ze==="PCTG"?(je=220,Te=260):ze.includes("PC")?(je=260,Te=300):(ze.includes("PA")||ze.includes("NYLON"))&&(je=250,Te=290)}const qe=m?.k_value?parseFloat(m.k_value):0,Pe=B?cg.includes(ve)?ve:re?.filament_type||pe.material||"PLA":U&&cg.includes(ve)?ve:pe.material||"PLA",Ie=await ne.configureAmsSlot(a,n.amsId,n.trayId,{tray_info_idx:be,tray_type:Pe,tray_sub_brands:te,tray_color:L+"FF",nozzle_temp_min:je,nozzle_temp_max:Te,cali_idx:V,nozzle_diameter:i,setting_id:xe,kprofile_filament_id:m?.filament_id,kprofile_setting_id:m?.setting_id||void 0,k_value:qe}),Re=B?`local_${Z}`:W?`builtin_${J}`:d,Ue=B?"local":W?"builtin":U?"orca_cloud":"cloud";try{await ne.saveSlotPreset(a,n.amsId,n.trayId,Re,te,Ue)}catch(ze){console.warn("Failed to save slot preset mapping:",ze)}return Ie},onSuccess:()=>{P(!0),o?.(),setTimeout(()=>{P(!1),e()},1500)}}),oe=rt({mutationFn:async()=>ne.resetAmsSlot(a,n.amsId,n.trayId),onSuccess:()=>{P(!0),o?.(),setTimeout(()=>{P(!1),e()},1500)}}),K=y.useMemo(()=>{const B=x.toLowerCase(),W=[],H=new Set,le=n.savedPresetId,U=n.trayInfoIdx;if(R?.filament)for(const G of R.filament){const Z=`orca_${G.setting_id}`;if(H.add(G.setting_id),H.add(Z),!(B&&!G.name.toLowerCase().includes(B))){if(s){const J=cY(G.name);if(J&&!Pz(J,s))continue}W.push({id:Z,name:G.name,source:"orca_cloud",isUser:!0})}}if(D?.filament)for(const G of D.filament){if(H.has(G.setting_id))continue;H.add(G.setting_id);const J=le===G.setting_id||U&&(G.setting_id===U||NF(G.setting_id)===U);if(!(B&&!G.name.toLowerCase().includes(B))){if(!J&&s){const re=cY(G.name);if(re&&!Pz(re,s))continue}W.push({id:G.setting_id,name:G.name,source:"cloud",isUser:C9e(G.setting_id)})}}if(I?.filament)for(const G of I.filament){const Z=`local_${G.id}`;B&&!G.name.toLowerCase().includes(B)||W.push({id:Z,name:G.name,source:"local",isUser:!1})}if(z)for(const G of z){if(H.has(G.filament_id))continue;const Z=G.filament_id.startsWith("GF")?"GFS"+G.filament_id.slice(2):G.filament_id;H.has(Z)||(!B||G.name.toLowerCase().includes(B))&&W.push({id:`builtin_${G.filament_id}`,name:G.name,source:"builtin",isUser:!1})}return W.sort((G,Z)=>{const J={local:0,orca_cloud:1,cloud:2,builtin:3};return G.source!==Z.source?J[G.source]-J[Z.source]:G.isUser&&!Z.isUser?-1:!G.isUser&&Z.isUser?1:G.name.localeCompare(Z.name)})},[R?.filament,D?.filament,I?.filament,z,x,s,n.savedPresetId,n.trayInfoIdx]),ie=y.useMemo(()=>{if(!d)return null;let B=null,W="";if(d.startsWith("local_")){const U=parseInt(d.replace("local_",""),10);B=I?.filament.find(Z=>Z.id===U)?.name||null}else if(d.startsWith("builtin_")){const U=d.replace("builtin_","");B=z?.find(Z=>Z.filament_id===U)?.name||null,W=bw(U)}else{const U=d.startsWith("orca_")?d.replace("orca_",""):d,G=R?.filament.find(Z=>Z.setting_id===U);if(G)B=G.name;else if(D?.filament){const Z=D.filament.find(J=>J.setting_id===d);B=Z?.name||null,Z&&(W=bw(Z.setting_id))}}if(!B)return null;let H=B.replace(/@.+$/,"").trim();H.startsWith("# ")&&(H=H.slice(2).trim());const le=iY(H);return{fullName:H,material:le.material,brand:le.brand,filamentId:W}},[d,D?.filament,I?.filament,z,R?.filament]),ue=ie?.fullName||"",he=y.useMemo(()=>{if(!ce||!ie)return[];const{fullName:B,brand:W}=ie,H=B.replace(/^(Bambu\s*(Lab)?|eSUN|Polymaker|Overture|Sunlu|Hatchbox)\s*/i,"").trim();return ce.filter(le=>{const U=(le.material||"").toUpperCase(),G=le.manufacturer.toUpperCase();if(!(U===H.toUpperCase()||U.includes(H.toUpperCase())||H.toUpperCase().includes(U)))return!1;if(W){const J=W.toUpperCase();if(!G.includes(J)&&!J.includes(G))return!1}return!0})},[ce,ie]),ge=y.useMemo(()=>{if(!ae?.profiles)return[];if(!ie){const pe=n.caliIdx;if(pe!=null&&pe>0){const V=ae.profiles.find(L=>L.slot_id===pe&&(n.extruderId===void 0||L.extruder_id===n.extruderId));if(V)return[V]}return[]}const{fullName:B,material:W,brand:H,filamentId:le}=ie,U=B.toUpperCase(),G=W.toUpperCase(),Z=H.toUpperCase(),J=le;if(!G||G.length<2)return[];const re=ae.profiles.filter(pe=>{if(J){const be=bw(pe.filament_id);if(be&&be===J&&!Tse(be))return!0}const V=pe.name.toUpperCase();if(Z)return!(!V.includes(Z)||!V.includes(G));if(V.includes(U)||V.includes(G))return!0;const te={NYLON:["PA","PA-CF","PA6"],PA:["NYLON"]}[G]||[];for(const be of te)if(V.includes(be))return!0;return!1}),se=new Map;for(const pe of re){const V=`${pe.name}|${pe.k_value}`,L=se.get(V);L?n.extruderId!==void 0&&pe.extruder_id===n.extruderId&&L.extruder_id!==n.extruderId&&se.set(V,pe):se.set(V,pe)}const fe=Array.from(se.values()),me=n.caliIdx;if(me!=null&&me>0&&!fe.some(pe=>pe.slot_id===me)){const pe=ae.profiles.find(V=>V.slot_id===me&&(n.extruderId===void 0||V.extruder_id===n.extruderId));pe&&fe.unshift(pe)}return fe},[ae?.profiles,ie,n.extruderId,n.caliIdx]);y.useEffect(()=>{if(t){if(n.savedPresetId)u(n.savedPresetId);else if(n.trayInfoIdx&&D?.filament){let B=D.filament.find(W=>W.setting_id===n.trayInfoIdx);B||(B=D.filament.find(W=>NF(W.setting_id)===n.trayInfoIdx)),B&&u(B.setting_id)}else if(n.trayInfoIdx&&z?.length){const B=n.trayInfoIdx,W=z.find(H=>H.filament_id===B);W&&u(`builtin_${W.filament_id}`)}if(n.trayColor){const B=n.trayColor.slice(0,6);B&&g(B)}}else u(""),p(null),g(""),b(""),S(""),P(!1),j.current=""},[t,n.savedPresetId,n.trayInfoIdx,n.trayColor,D?.filament,z]),y.useEffect(()=>{if(ge.length>0){if(n.caliIdx!=null&&n.caliIdx>0){const B=ge.find(W=>W.slot_id===n.caliIdx);if(B){p(B);return}}p(ge[0])}else p(null)},[d,ge,n.caliIdx]);const q=y.useCallback(B=>{B.key==="Escape"&&e()},[e]);y.useEffect(()=>{if(t)return document.addEventListener("keydown",q),()=>document.removeEventListener("keydown",q)},[t,q]);const Q=C&&!E||O||X||Y;if(y.useEffect(()=>{if(!Q&&d&&d!==j.current){const B=requestAnimationFrame(()=>{const H=document.querySelector('[class*="fixed inset-0 z-50"]')?.querySelector(`[data-preset-id="${CSS.escape(d)}"]`);H&&(j.current=d,H.scrollIntoView({block:"nearest"}))});return()=>cancelAnimationFrame(B)}},[d,Q]),!t)return null;const A=d&&!de.isPending,F=f||n.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(xd,{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:"|"}),n.trayColor&&r.jsx("span",{className:"w-4 h-4 rounded-full border border-black/20",style:{backgroundColor:`#${n.trayColor.slice(0,6)}`}}),r.jsx("span",{className:"text-white/70",children:c("configureAmsSlot.slotLabel",{ams:nY(n.amsId,n.trayCount),slot:n.trayId+1})}),n.traySubBrands&&r.jsxs("span",{children:["(",n.traySubBrands,")"]})]})]}),r.jsx("button",{onClick:e,className:"p-1 text-bambu-gray hover:text-white rounded transition-colors",children:r.jsx(Ht,{className:"w-5 h-5"})})]}),r.jsxs("div",{className:`p-4 overflow-y-auto ${l?"flex-1 min-h-0":"space-y-4 max-h-[60vh]"}`,children:[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(to,{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:[n.trayColor&&r.jsx("span",{className:"w-4 h-4 rounded-full border border-black/20",style:{backgroundColor:`#${n.trayColor.slice(0,6)}`}}),r.jsx("span",{className:"text-white font-medium",children:c("configureAmsSlot.slotLabel",{ams:nY(n.amsId,n.trayCount),slot:n.trayId+1})}),n.traySubBrands&&r.jsxs("span",{className:"text-bambu-gray",children:["(",n.traySubBrands,")"]})]})]}),Q?r.jsx("div",{className:"flex justify-center py-8",children:r.jsx(lt,{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:B=>S(B.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:K.length===0?r.jsx("p",{className:"text-center py-4 text-bambu-gray",children:D?.filament?.length===0&&!I?.filament?.length?c("configureAmsSlot.noPresetsAvailable"):c("configureAmsSlot.noMatchingPresets")}):K.map(B=>r.jsx("button",{"data-preset-id":B.id,onClick:()=>u(B.id),className:`group w-full p-2 rounded-lg border text-left transition-colors ${d===B.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:B.name,children:B.name}),r.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[B.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")}),B.source==="orca_cloud"&&r.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded bg-purple-500/20 text-purple-400",children:c("configureAmsSlot.orcaCloud")}),B.source==="cloud"&&r.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded bg-bambu-blue/20 text-bambu-blue",children:c("configureAmsSlot.bambuCloud")}),B.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")})]})]})},B.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"),ue&&r.jsx("span",{className:"ml-2 text-xs text-bambu-blue",children:c("configureAmsSlot.filteringFor",{material:ue})})]}),ge.length>0?r.jsxs("div",{className:"relative",children:[r.jsxs("select",{value:m?.name||"",onChange:B=>{const W=ge.find(H=>H.name===B.target.value);p(W||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")}),ge.map(B=>r.jsxs("option",{value:B.name,children:[B.name," (K=",B.k_value,")"]},`${B.name}-${B.extruder_id}`))]}),r.jsx(za,{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")}),he.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:ie?.fullName})}),r.jsx("div",{className:"flex flex-wrap gap-1.5",children:he.map(B=>r.jsxs("button",{onClick:()=>{const W=B.hex_color.replace("#","").toUpperCase();g(W),b(B.color_name)},className:`h-7 px-2 rounded-md border-2 transition-all flex items-center gap-1.5 ${f===B.hex_color.replace("#","").toUpperCase()?"border-bambu-green scale-105":"border-white/20 hover:border-white/40"}`,title:B.color_name,children:[r.jsx("span",{className:"w-4 h-4 rounded-full border border-black/20 flex-shrink-0",style:{backgroundColor:B.hex_color}}),r.jsx("span",{className:"text-xs text-white/80 whitespace-nowrap",children:B.color_name})]},B.id))})]}),r.jsxs("div",{className:"flex flex-wrap gap-1.5 mb-2",children:[sY.map(B=>r.jsx("button",{onClick:()=>{g(B.hex),b(B.name)},className:`w-7 h-7 rounded-md border-2 transition-all ${f===B.hex?"border-bambu-green scale-110":"border-white/20 hover:border-white/40"}`,style:{backgroundColor:`#${B.hex}`},title:B.name},B.hex)),r.jsx("button",{onClick:()=>T(!N),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(N?"configureAmsSlot.showLessColors":"configureAmsSlot.showMoreColors"),children:N?"−":"+"})]}),N&&r.jsx("div",{className:"flex flex-wrap gap-1.5 mb-2",children:oY.map(B=>r.jsx("button",{onClick:()=>{g(B.hex),b(B.name)},className:`w-7 h-7 rounded-md border-2 transition-all ${f===B.hex?"border-bambu-green scale-110":"border-white/20 hover:border-white/40"}`,style:{backgroundColor:`#${B.hex}`},title:B.name},B.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:`#${F}`}}),r.jsx("input",{type:"text",placeholder:c("configureAmsSlot.colorPlaceholder"),value:v,onChange:B=>{const W=B.target.value;b(W);const H=lY(W);if(H)g(H);else{const le=W.replace(/[^0-9A-Fa-f]/g,"").toUpperCase();le.length===6?g(le):le.length===3&&g(le.split("").map(U=>U+U).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:B=>S(B.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:K.length===0?r.jsx("p",{className:"text-center py-4 text-bambu-gray",children:D?.filament?.length===0&&!I?.filament?.length?c("configureAmsSlot.noPresetsAvailable"):c("configureAmsSlot.noMatchingPresets")}):K.map(B=>r.jsx("button",{"data-preset-id":B.id,onClick:()=>u(B.id),className:`group w-full p-2 rounded-lg border text-left transition-colors ${d===B.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:B.name,children:B.name}),r.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[B.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")}),B.source==="orca_cloud"&&r.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded bg-purple-500/20 text-purple-400",children:c("configureAmsSlot.orcaCloud")}),B.source==="cloud"&&r.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded bg-bambu-blue/20 text-bambu-blue",children:c("configureAmsSlot.bambuCloud")}),B.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")})]})]})},B.id))})]})]}),r.jsxs("div",{children:[r.jsxs("label",{className:"block text-sm text-bambu-gray mb-2",children:[c("configureAmsSlot.kProfileLabel"),ue&&r.jsx("span",{className:"ml-2 text-xs text-bambu-blue",children:c("configureAmsSlot.filteringFor",{material:ue})})]}),ge.length>0?r.jsxs("div",{className:"relative",children:[r.jsxs("select",{value:m?.name||"",onChange:B=>{const W=ge.find(H=>H.name===B.target.value);p(W||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")}),ge.map(B=>r.jsxs("option",{value:B.name,children:[B.name," (K=",B.k_value,")"]},`${B.name}-${B.extruder_id}`))]}),r.jsx(za,{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")}),he.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:ie?.fullName})}),r.jsx("div",{className:"flex flex-wrap gap-1.5",children:he.map(B=>r.jsxs("button",{onClick:()=>{const W=B.hex_color.replace("#","").toUpperCase();g(W),b(B.color_name)},className:`h-7 px-2 rounded-md border-2 transition-all flex items-center gap-1.5 ${f===B.hex_color.replace("#","").toUpperCase()?"border-bambu-green scale-105":"border-white/20 hover:border-white/40"}`,title:B.color_name,children:[r.jsx("span",{className:"w-4 h-4 rounded-full border border-black/20 flex-shrink-0",style:{backgroundColor:B.hex_color}}),r.jsx("span",{className:"text-xs text-white/80 whitespace-nowrap",children:B.color_name})]},B.id))})]}),r.jsxs("div",{className:"flex flex-wrap gap-1.5 mb-2",children:[sY.map(B=>r.jsx("button",{onClick:()=>{g(B.hex),b(B.name)},className:`w-7 h-7 rounded-md border-2 transition-all ${f===B.hex?"border-bambu-green scale-110":"border-white/20 hover:border-white/40"}`,style:{backgroundColor:`#${B.hex}`},title:B.name},B.hex)),r.jsx("button",{onClick:()=>T(!N),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(N?"configureAmsSlot.showLessColors":"configureAmsSlot.showMoreColors"),children:N?"−":"+"})]}),N&&r.jsx("div",{className:"flex flex-wrap gap-1.5 mb-2",children:oY.map(B=>r.jsx("button",{onClick:()=>{g(B.hex),b(B.name)},className:`w-7 h-7 rounded-md border-2 transition-all ${f===B.hex?"border-bambu-green scale-110":"border-white/20 hover:border-white/40"}`,style:{backgroundColor:`#${B.hex}`},title:B.name},B.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:`#${F}`}}),r.jsx("input",{type:"text",placeholder:c("configureAmsSlot.colorPlaceholder"),value:v,onChange:B=>{const W=B.target.value;b(W);const H=lY(W);if(H)g(H);else{const le=W.replace(/[^0-9A-Fa-f]/g,"").toUpperCase();le.length===6?g(le):le.length===3&&g(le.split("").map(U=>U+U).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(Le,{variant:"secondary",onClick:()=>oe.mutate(),disabled:oe.isPending||de.isPending,className:"text-red-400 hover:text-red-300 hover:bg-red-500/10",children:oe.isPending?r.jsxs(r.Fragment,{children:[r.jsx(lt,{className:"w-4 h-4 animate-spin"}),c("configureAmsSlot.resetting")]}):r.jsxs(r.Fragment,{children:[r.jsx(bs,{className:"w-4 h-4"}),c("configureAmsSlot.resetSlot")]})}),r.jsxs("div",{className:"flex gap-2",children:[r.jsx(Le,{variant:"secondary",onClick:e,children:c("configureAmsSlot.cancel")}),r.jsx(Le,{onClick:()=>de.mutate(),disabled:!A,children:de.isPending?r.jsxs(r.Fragment,{children:[r.jsx(lt,{className:"w-4 h-4 animate-spin"}),c("configureAmsSlot.configuring")]}):r.jsxs(r.Fragment,{children:[r.jsx(xd,{className:"w-4 h-4"}),c("configureAmsSlot.configureSlot")]})})]})]}),(de.isError||oe.isError)&&r.jsx("div",{className:"mx-4 mb-4 p-2 bg-red-500/20 border border-red-500/50 rounded text-sm text-red-400",children:de.error?.message||oe.error?.message})]})]})}function dY({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 jse({folderId:t,onClose:e,onUploadComplete:a,onFileUploaded:n,autoUpload:i,validateFile:s,accept:o}){const{t:l}=wt(),[c,d]=y.useState([]),[u,m]=y.useState(!1),[p,f]=y.useState(!1),[g,v]=y.useState(!0),[b,x]=y.useState(!1),[S,k]=y.useState(!0),[P,N]=y.useState(null),T=y.useRef(null),j=oe=>{oe.preventDefault(),m(!0)},D=oe=>{oe.preventDefault(),m(!1)},C=oe=>{oe.preventDefault(),m(!1),O(Array.from(oe.dataTransfer.files))},E=oe=>{oe.target.files&&O(Array.from(oe.target.files))},R=(oe,K)=>{d(ie=>ie.map(ue=>ue.file===oe?{...ue,...K}:ue))},I=async oe=>{f(!0);for(const K of oe)if(K.status==="pending"){R(K.file,{status:"uploading"});try{if(K.isZip){const ie=await ne.extractZipFile(K.file,t,g,b,S);R(K.file,{status:ie.errors.length>0&&ie.extracted===0?"error":"success",extractedCount:ie.extracted,error:ie.errors.length>0?l("fileManager.zipFilesFailed","{{count}} files failed",{count:ie.errors.length}):void 0})}else{const ie=await ne.uploadLibraryFile(K.file,t,S);R(K.file,{status:"success"});const ue=n?.(ie);if(ue){N(ue),d([]),f(!1);return}}}catch(ie){R(K.file,{status:"error",error:ie instanceof Error?ie.message:l("fileManager.uploadFailed","Upload failed")})}}f(!1),a(),d(K=>(K.some(ue=>ue.status==="error")||e(),K))},O=oe=>{if(N(null),s)for(const ie of oe){const ue=s(ie);if(ue){N(ue);return}}const K=oe.map(ie=>({file:ie,status:"pending",isZip:ie.name.toLowerCase().endsWith(".zip"),is3mf:ie.name.toLowerCase().endsWith(".3mf")}));d(ie=>[...ie,...K]),i&&oe.length>0&&I(K)},z=oe=>{d(K=>K.filter((ie,ue)=>ue!==oe))},X=c.some(oe=>oe.isZip&&oe.status==="pending"),ae=c.some(oe=>oe.file.name.toLowerCase().endsWith(".stl")&&oe.status==="pending"),Y=c.some(oe=>oe.is3mf&&oe.status==="pending"),ce=c.filter(oe=>oe.status==="pending").length,de=c.length>0&&ce===0&&!p;return r.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:r.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-lg border border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"p-4 border-b border-bambu-dark-tertiary flex items-center justify-between",children:[r.jsx("h2",{className:"text-lg font-semibold text-white",children:l("fileManager.uploadFiles")}),r.jsx("button",{onClick:e,className:"p-1 hover:bg-bambu-dark rounded",children:r.jsx(Ht,{className:"w-5 h-5 text-bambu-gray"})})]}),r.jsxs("div",{className:"p-4 space-y-4",children:[r.jsxs("div",{onDragOver:j,onDragLeave:D,onDrop:C,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(Sn,{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:E}),X&&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(ro,{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:oe=>v(oe.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:oe=>x(oe.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(xr,{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")})]})]})}),(ae||X)&&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(gu,{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(X&&!ae?"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:oe=>k(oe.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((oe,K)=>r.jsxs("div",{className:"flex items-center gap-3 p-2 bg-bambu-dark rounded-lg",children:[oe.isZip?r.jsx(ro,{className:"w-4 h-4 text-blue-400 flex-shrink-0"}):r.jsx(FT,{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:oe.file.name}),r.jsxs("p",{className:"text-xs text-bambu-gray",children:[(oe.file.size/1024/1024).toFixed(2)," MB",oe.isZip&&oe.status==="pending"&&r.jsxs("span",{className:"text-blue-400 ml-2",children:["• ",l("fileManager.willBeExtracted")]}),oe.extractedCount!==void 0&&r.jsxs("span",{className:"text-green-400 ml-2",children:["• ",l("fileManager.filesExtracted",{count:oe.extractedCount})]})]}),oe.status==="error"&&oe.error&&r.jsx("p",{className:"text-xs text-red-400 mt-1 break-words",children:oe.error})]}),oe.status==="pending"&&r.jsx("button",{onClick:()=>z(K),className:"p-1 hover:bg-bambu-dark-tertiary rounded",children:r.jsx(Ht,{className:"w-4 h-4 text-bambu-gray"})}),oe.status==="uploading"&&r.jsx(lt,{className:"w-4 h-4 text-bambu-green animate-spin"}),oe.status==="success"&&r.jsx(fr,{className:"w-4 h-4 text-green-500"}),oe.status==="error"&&r.jsx("span",{title:oe.error,children:r.jsx(Fr,{className:"w-4 h-4 text-red-500"})})]},K))}),P&&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(Fr,{className:"w-5 h-5 text-red-400 mt-0.5 flex-shrink-0"}),r.jsx("p",{className:"text-sm text-red-300",children:P})]})})]}),r.jsxs("div",{className:"p-4 border-t border-bambu-dark-tertiary flex justify-end gap-2",children:[r.jsx(Le,{variant:"secondary",onClick:e,children:l("common.cancel")}),!de&&r.jsx(Le,{onClick:()=>I(c),disabled:ce===0||p,children:p?r.jsxs(r.Fragment,{children:[r.jsx(lt,{className:"w-4 h-4 mr-2 animate-spin"}),l("fileManager.uploading")]}):r.jsxs(r.Fragment,{children:[r.jsx(Sn,{className:"w-4 h-4 mr-2"}),l("common.upload")," ",ce>0?`(${ce})`:""]})})]})]})})}function uY(t){if(!t)return"#808080";const e=t.replace("#","");return e.length>=8&&e.substring(6,8).toLowerCase()!=="ff"?`#${e.substring(0,8)}`:`#${e.substring(0,6)}`}function On(t){return t?t.replace("#","").toLowerCase().substring(0,6):""}const N9e=[["PA-CF","PA12-CF","PAHT-CF"]],Mse={};for(const t of N9e){const e=t[0];for(const a of t)Mse[a.toUpperCase()]=e.toUpperCase()}function M1(t){if(!t)return"";const e=t.toUpperCase();return Mse[e]??e}function TF(t,e){return M1(t)===M1(e)}function fd(t,e,a=40){const n=On(t),i=On(e);if(!n||!i||n.length<6||i.length<6)return!1;const s=parseInt(n.substring(0,2),16),o=parseInt(n.substring(2,4),16),l=parseInt(n.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)<=a&&Math.abs(o-d)<=a&&Math.abs(l-u)<=a}function yk(t,e,a,n){if(n)return"Ext";const i=String.fromCharCode(65+(t>=128?t-128:t));return a?`HT-${i}`:`${i}${e+1}`}function ib(t,e,a){return a?254+e:t>=128?t:t*4+e}function by(t){return t>50?"#00ae42":t>=15?"#f59e0b":"#ef4444"}function GP(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 mY(t,e){return(Number.isFinite(t)?Math.max(0,Math.trunc(t)):0).toString(16).toUpperCase().padStart(e,"0").slice(-e)}function T9e(t){const e=(t||"").trim().toUpperCase();let a=2166136261;for(let n=0;n>>0).toString(16).toUpperCase().padStart(8,"0")}function wm(t,e,a){return`${T9e(t)}${mY(e,4)}${mY(a,4)}`}function pY(t){if(!t)return!1;const e=Date.now()+4320*60*60*1e3;return(Ga(t)?.getTime()??0)>e}function A9e(t,e,a,n){let i=Ese(e,t.nozzle_id);n&&(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=>!a.has(c.globalTrayId)&&TF(c.type,t.type)&&On(c.color)===On(t.color)),o=s?void 0:i.find(c=>!a.has(c.globalTrayId)&&TF(c.type,t.type)&&fd(c.color,t.color)),l=s||o?void 0:i.find(c=>!a.has(c.globalTrayId)&&TF(c.type,t.type));return s??o??l}function Ese(t,e){return t.filter(a=>e==null||a.extruderId===e)}function Qs(t){return t?!!(t.tray_uuid&&t.tray_uuid!=="00000000000000000000000000000000"||t.tag_uid&&t.tag_uid!=="0000000000000000"):!1}function vk(t){const e=[],a=t?.ams_extruder_map,n=!!t?.nozzles?.[1]?.nozzle_diameter||a&&Object.keys(a).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=uY(o.tray_color);e.push({type:o.tray_type,color:l,colorName:_c(l),amsId:i.id,trayId:o.id,isHt:s,isExternal:!1,label:yk(i.id,o.id,s,!1),globalTrayId:ib(i.id,o.id,!1),trayInfoIdx:o.tray_info_idx||"",traySubBrands:o.tray_sub_brands||"",extruderId:a?.[String(i.id)],remain:o.remain??-1})}})});for(const i of t?.vt_tray??[])if(i.tray_type){const s=uY(i.tray_color),o=i.id??254,l=(t?.vt_tray?.length??0)>1;e.push({type:i.tray_type,color:s,colorName:_c(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:n?255-o:void 0,remain:i.remain??-1})}return e}function hY(t,e,a){if(!t?.filaments||t.filaments.length===0)return;const n=vk(e);if(n.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=n.filter(x=>!s.has(x.globalTrayId));d.nozzle_id!=null&&!i&&(m=m.filter(x=>x.extruderId===d.nozzle_id)),a&&(m=[...m].sort((x,S)=>{const k=x.remain>=0?x.remain:101,P=S.remain>=0?S.remain:101;return k-P}));let p,f,g,v;if(u){const x=m.filter(S=>S.trayInfoIdx===u);x.length===1?p=x[0]:x.length>1&&(a&&x.sort((S,k)=>{const P=S.remain>=0?S.remain:101,N=k.remain>=0?k.remain:101;return P-N}),f=x.find(S=>S.type?.toUpperCase()===d.type?.toUpperCase()&&On(S.color)===On(d.color)),f||(g=x.find(S=>S.type?.toUpperCase()===d.type?.toUpperCase()&&fd(S.color,d.color))),!f&&!g&&(v=x.find(S=>S.type?.toUpperCase()===d.type?.toUpperCase())))}!p&&!f&&!g&&!v&&(f=m.find(x=>x.type?.toUpperCase()===d.type?.toUpperCase()&&On(x.color)===On(d.color)),f||(g=m.find(x=>x.type?.toUpperCase()===d.type?.toUpperCase()&&fd(x.color,d.color))),!f&&!g&&(v=m.find(x=>x.type?.toUpperCase()===d.type?.toUpperCase())));const b=p||f||g||v||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 j9e(t){return y.useMemo(()=>vk(t),[t])}function Dse(t,e,a,n){const i=j9e(e),s=e?.fila_switch?.installed===!0,o=y.useMemo(()=>{if(!t?.filaments||t.filaments.length===0)return[];const u=new Set(Object.values(a));return t.filaments.map(m=>{const p=m.slot_id||0;if(p>0&&a[p]!==void 0){const D=a[p],C=i.find(E=>E.globalTrayId===D);if(C){const E=C.type?.toUpperCase()===m.type?.toUpperCase(),R=On(C.color)===On(m.color)||fd(C.color,m.color);let I;return E&&R?I="match":E?I="type_only":I="mismatch",{...m,loaded:C,hasFilament:!0,typeMatch:E,colorMatch:R,status:I,isManual:!0}}}const f=m.tray_info_idx||"";let g=i.filter(D=>!u.has(D.globalTrayId));m.nozzle_id!=null&&!s&&(g=g.filter(D=>D.extruderId===m.nozzle_id)),n&&(g=[...g].sort((D,C)=>{const E=D.remain>=0?D.remain:101,R=C.remain>=0?C.remain:101;return E-R}));let v,b,x,S;if(f){const D=g.filter(C=>C.trayInfoIdx===f);D.length===1?v=D[0]:D.length>1&&(n&&D.sort((C,E)=>{const R=C.remain>=0?C.remain:101,I=E.remain>=0?E.remain:101;return R-I}),b=D.find(C=>C.type?.toUpperCase()===m.type?.toUpperCase()&&On(C.color)===On(m.color)),b||(x=D.find(C=>C.type?.toUpperCase()===m.type?.toUpperCase()&&fd(C.color,m.color))),!b&&!x&&(S=D.find(C=>C.type?.toUpperCase()===m.type?.toUpperCase())))}!v&&!b&&!x&&!S&&(b=g.find(D=>D.type?.toUpperCase()===m.type?.toUpperCase()&&On(D.color)===On(m.color)),b||(x=g.find(D=>D.type?.toUpperCase()===m.type?.toUpperCase()&&fd(D.color,m.color))),!b&&!x&&(S=g.find(D=>D.type?.toUpperCase()===m.type?.toUpperCase())));const k=v||b||x||S||void 0;k&&u.add(k.globalTrayId);const P=!!k,N=P,T=!!v||!!b||!!x;let j;return v||b||x?j="match":S?j="type_only":j="mismatch",{...m,loaded:k,hasFilament:P,typeMatch:N,colorMatch:T,status:j,isManual:!1}})},[t,i,a,n,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 M9e(t,e,a,n){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(a));for(const u of t){const m=u.slot_id||0;if(m>0&&a[m]!==void 0){const x=a[m],S=e.find(k=>k.globalTrayId===x);if(S){const k=S.type?.toUpperCase()===u.type?.toUpperCase(),P=On(S.color)===On(u.color)||fd(S.color,u.color);k&&P?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)}n&&(p=[...p].sort((x,S)=>{const k=x.remain>=0?x.remain:101,P=S.remain>=0?S.remain:101;return k-P}));const f=p.find(x=>x.type?.toUpperCase()===u.type?.toUpperCase()&&On(x.color)===On(u.color)),g=f?void 0:p.find(x=>x.type?.toUpperCase()===u.type?.toUpperCase()&&fd(x.color,u.color)),v=f||g?void 0:p.find(x=>x.type?.toUpperCase()===u.type?.toUpperCase()),b=f??g??v;b&&l.add(b.globalTrayId),f||g?i++:v?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 E9e(t,e,a,n){if(!t?.filaments||t.filaments.length===0)return;const i=vk(e);if(i.length===0)return;const s=new Set(Object.values(a)),o=[];for(const d of t.filaments){const u=d.slot_id||0;if(u>0&&a[u]!==void 0){o.push({slot_id:u,globalTrayId:a[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)}n&&(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()&&On(b.color)===On(d.color)),f=p?void 0:m.find(b=>b.type?.toUpperCase()===d.type?.toUpperCase()&&fd(b.color,d.color)),g=p||f?void 0:m.find(b=>b.type?.toUpperCase()===d.type?.toUpperCase()),v=p??f??g;v&&s.add(v.globalTrayId),o.push({slot_id:u,globalTrayId:v?.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 fY={useDefault:!0,manualMappings:{},autoConfigured:!1};function D9e(t,e,a,n,i,s,o){const l=dp({queries:t.map(v=>({queryKey:["printer-status",v],queryFn:()=>ne.getPrinterStatus(v),enabled:t.length>0,staleTime:5e3}))}),c=y.useMemo(()=>t.map((v,b)=>{const x=l[b],S=x?.data,P=e?.find(R=>R.id===v)?.name||`Printer ${v}`,N=vk(S),T=i[v]||fY,j=hY(a,S,o),D=T.useDefault?n:T.manualMappings,C=E9e(a,S,D,o),E=M9e(a?.filaments,N,D,o);return{printerId:v,printerName:P,status:S,isLoading:x?.isLoading??!1,loadedFilaments:N,autoMapping:j,finalMapping:C,matchStatus:E.status,exactMatches:E.exactMatches,typeOnlyMatches:E.typeOnlyMatches,missingTypes:E.missingTypes,totalSlots:E.totalSlots,config:T}}),[t,l,e,a,i,n,o]),d=l.some(v=>v.isLoading),u=(v,b)=>{s(x=>({...x,[v]:{...x[v]||fY,...b}}))},m=v=>{const b=c.find(k=>k.printerId===v);if(!b||!b.status||!a?.filaments)return;const x=hY(a,b.status,o);if(!x)return;const S={};x.forEach((k,P)=>{k!==-1&&(S[P+1]=k)}),u(v,{useDefault:!1,manualMappings:S,autoConfigured:!0})},p=()=>{for(const v of t)m(v)},f=v=>c.find(x=>x.printerId===v)?.finalMapping,g=c.every(v=>v.matchStatus!=="missing");return{printerResults:c,isLoading:d,perPrinterConfigs:i,updatePrinterConfig:u,autoConfigureAll:p,autoConfigurePrinter:m,getFinalMapping:f,allPrintersReady:g}}const Fse={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 Vo(t){return Fse[t.toUpperCase()]||t}const F9e=Object.entries(Fse).map(([t,e])=>({code:t,label:`${t} (${e})`})),Vd="/img/bed",L9e={"cool plate":{icon:`${Vd}/bed_cool.png`,label:"Cool Plate"},"pc plate":{icon:`${Vd}/bed_cool.png`,label:"Cool Plate"},"cool plate (supertack)":{icon:`${Vd}/bed_cool_supertack.png`,label:"Cool Plate SuperTack"},"supertack plate":{icon:`${Vd}/bed_cool_supertack.png`,label:"Cool Plate SuperTack"},"bambu cool plate supertack":{icon:`${Vd}/bed_cool_supertack.png`,label:"Cool Plate SuperTack"},"engineering plate":{icon:`${Vd}/bed_engineering.png`,label:"Engineering Plate"},"high temp plate":{icon:`${Vd}/bed_high_templ.png`,label:"High Temp Plate"},"textured pei plate":{icon:`${Vd}/bed_pei.png`,label:"Textured PEI Plate"},"pei plate":{icon:`${Vd}/bed_pei.png`,label:"PEI Plate"},"smooth pei plate":{icon:`${Vd}/bed_pei_cool.png`,label:"Smooth PEI Plate"}};function wk(t){return t?L9e[t.trim().toLowerCase()]??null:null}function R9e(t){const e=t.trim().split(/\s+/);return e.length<=1?t.trim():e.slice(1).join(" ")}function Lse(t){const{data:e}=$e({queryKey:["builtin-filaments"],queryFn:()=>ne.getBuiltinFilaments(),staleTime:3e5}),{data:a}=$e({queryKey:["filament-id-map"],queryFn:()=>ne.getFilamentIdMap(),staleTime:300*1e3}),n=y.useMemo(()=>{const o={};for(const l of e||[])l.filament_id&&(o[l.filament_id]=l.name);for(const[l,c]of Object.entries(a||{}))l&&c&&(o[l]=c);return o},[e,a]),i=y.useMemo(()=>(t||[]).map(o=>{const l=o.tray_info_idx&&n[o.tray_info_idx]||o.type;return{resolvedName:l,materialHint:R9e(l),color:o.color}}),[t,n]),s=dp({queries:i.map(({color:o,materialHint:l})=>({queryKey:["color-by-material",o,l],queryFn:()=>ne.getColorByMaterial(o,l),enabled:!!o,staleTime:300*1e3}))});return i.map(({resolvedName:o,color:l},c)=>{const d=s[c]?.data?.color_name??null;return{resolvedName:o,colorLabel:d||_c(l)}})}function z9e({printerId:t,filamentReqs:e,manualMappings:a,onManualMappingChange:n,currencySymbol:i,defaultCostPerKg:s,defaultExpanded:o=!1,forceColorMatch:l,onForceColorMatchChange:c}){const{t:d}=wt(),u=ia(),[m,p]=y.useState(!1),[f,g]=y.useState(o),{data:v}=$e({queryKey:["printer-status",t],queryFn:()=>ne.getPrinterStatus(t),enabled:!!t}),{data:b}=$e({queryKey:["spool-assignments",t],queryFn:()=>ne.getAssignments(t),enabled:!!t}),{loadedFilaments:x,filamentComparison:S,hasTypeMismatch:k,hasColorMismatch:P}=Dse(e,v,a),N=Lse(e?.filaments),T=y.useMemo(()=>{const Y=new Map;for(const ce of b||[]){const de=ce.ams_id===255,oe=ib(ce.ams_id,ce.tray_id,de);Y.set(oe,ce.spool?.cost_per_kg??null)}return Y},[b]),j=y.useMemo(()=>{const Y=new Map;for(const ce of b||[]){const de=ce.ams_id===255,oe=ib(ce.ams_id,ce.tray_id,de),K=ce.spool;if(!K){Y.set(oe,null);continue}Y.set(oe,Math.max(0,Math.round((K.label_weight??0)-(K.weight_used??0))))}return Y},[b]),D=y.useMemo(()=>{let Y=0;for(const ce of S){const de=ce.loaded?.globalTrayId;if(de==null)continue;const K=T.get(de)??null??s;K>0&&(Y+=ce.used_grams/1e3*K)}return Y},[S,T,s]),C=y.useMemo(()=>Array.from(T.values()).some(Y=>Y!=null&&Y>0),[T]),E=e?.filaments&&e.filaments.length>0,R=e?.filaments?.some(Y=>Y.nozzle_id!=null)??!1,I=v?.fila_switch?.installed===!0,O=Y=>{const ce=v?.fila_switch;if(!ce?.installed)return null;const de=ce.in_slots.indexOf(Y);return de<0?null:ce.out_extruders[de]??null};if(!E||!v)return null;const z=k?"#f97316":P?"#facc15":"#00ae42",X=(Y,ce)=>{if(Y>0)if(ce===""){const de={...a};delete de[Y],n(de)}else n({...a,[Y]:parseInt(ce,10)})},ae=async()=>{p(!0);try{await ne.refreshPrinterStatus(t),await new Promise(Y=>setTimeout(Y,500)),await u.refetchQueries({queryKey:["printer-status",t]})}finally{p(!1)}};return r.jsxs("div",{className:"mb-4",children:[r.jsxs("button",{type:"button",onClick:()=>g(!f),className:"flex items-center gap-2 text-sm text-bambu-gray hover:text-white transition-colors w-full",children:[r.jsx(Uw,{className:"w-4 h-4",fill:z,stroke:"none"}),r.jsx("span",{children:d("printModal.filamentMapping")}),k?r.jsx("span",{className:"text-xs text-orange-400",children:"(Type not found)"}):P?r.jsx("span",{className:"text-xs text-yellow-400",children:"(Color mismatch)"}):r.jsx("span",{className:"text-xs text-bambu-green",children:"(Ready)"}),f?r.jsx(el,{className:"w-4 h-4 ml-auto"}):r.jsx(za,{className:"w-4 h-4 ml-auto"})]}),f&&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:ae,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:m,children:[r.jsx(tr,{className:`w-3 h-3 ${m?"animate-spin":""}`}),r.jsx("span",{children:"Re-read"})]})]}),S.map((Y,ce)=>{const de=Y.slot_id??0,oe=de>0&&c!=null,{resolvedName:K,colorLabel:ie}=N[ce]??{resolvedName:Y.type,colorLabel:_c(Y.color)};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 16px"},children:[r.jsx("span",{title:`Required: ${K} - ${ie}`,children:r.jsx(Uw,{className:"w-3 h-3",fill:Y.color,stroke:Y.color})}),r.jsxs("span",{className:"text-white truncate flex items-center gap-1",children:[R&&Y.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:Y.nozzle_id===1?d("printModal.leftNozzleTooltip"):d("printModal.rightNozzleTooltip"),children:Y.nozzle_id===1?d("printModal.leftNozzle"):d("printModal.rightNozzle")}),K," ",r.jsxs("span",{className:"text-bambu-gray",children:["(",Y.used_grams,"g)"]})]}),r.jsx("span",{className:"text-bambu-gray",children:"→"}),r.jsxs("select",{value:Y.loaded?.globalTrayId??"",onChange:ue=>X(de,ue.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 ${Y.status==="match"?"border-bambu-green/50 text-bambu-green":Y.status==="type_only"?"border-yellow-400/50 text-yellow-400":"border-orange-400/50 text-orange-400"} ${Y.isManual?"ring-1 ring-blue-400/50":""}`,title:Y.isManual?"Manually selected":"Auto-matched",children:[r.jsx("option",{value:"",className:"bg-bambu-dark text-bambu-gray",children:"-- Select slot --"}),x.map(ue=>{const he=j.get(ue.globalTrayId),ge=he!=null?d("printModal.slotRemainingShort",{grams:he,defaultValue:` - ${he}g left`}):"",q=I?O(ue.globalTrayId):null,Q=q==null?"":` [${d(q===1?"printModal.leftNozzle":"printModal.rightNozzle")}]`;return r.jsxs("option",{value:ue.globalTrayId,className:"bg-bambu-dark text-white",children:[ue.label,": ",ue.traySubBrands||ue.type," (",ue.colorName,")",ge,Q]},ue.globalTrayId)})]}),Y.status==="match"?r.jsx(_r,{className:"w-3 h-3 text-bambu-green"}):Y.status==="type_only"?r.jsx("span",{title:"Same type, different color",children:r.jsx(xa,{className:"w-3 h-3 text-yellow-400"})}):r.jsx("span",{title:"Filament type not loaded",children:r.jsx(xa,{className:"w-3 h-3 text-orange-400"})})]}),oe&&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:l?.[de]??!1,onChange:ue=>c(de,ue.target.checked),className:"accent-bambu-green w-3 h-3"}),r.jsx(nv,{className:"w-3 h-3"}),d("printModal.forceColorMatch")]})]},ce)}),r.jsxs("div",{className:"text-xs text-bambu-gray",children:[d("printModal.totalCost")," ",r.jsx("span",{className:"text-white",children:D>0||C?`${i}${D.toFixed(2)}`:"N/A"})]}),k&&r.jsx("p",{className:"text-xs text-orange-400 mt-2",children:"Required filament type not found in printer."})]})]})}function I9e({filamentReqs:t,availableFilaments:e,overrides:a,onChange:n,forceColorMatch:i,onForceColorMatchChange:s}){const{t:o}=wt(),l=Lse(t?.filaments),c=y.useMemo(()=>{const m={};for(const p of e){const f=M1(p.type);m[f]||(m[f]=[]),m[f].push(p)}return m},[e]),d=t?.filaments;if(!d||d.length===0||e.length===0)return null;const u=(m,p)=>{if(p===""){const f={...a};delete f[m],n(f)}else{const[f,g]=p.split("|");n({...a,[m]:{type:f,color:g}})}};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:d.map((m,p)=>{const f=a[m.slot_id],g=!!f,v=c[M1(m.type)]||[],b=m.nozzle_id!=null?v.filter(k=>k.extruder_id==null||k.extruder_id===m.nozzle_id):v,{resolvedName:x,colorLabel:S}=l[p]??{resolvedName:m.type,colorLabel:_c(m.color)};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")}: ${x} - ${S}`,children:r.jsx(Uw,{className:"w-3 h-3",fill:m.color,stroke:m.color})}),r.jsxs("span",{className:"text-white truncate",children:[x," ",r.jsxs("span",{className:"text-bambu-gray",children:["(",m.used_grams,"g)"]})]}),r.jsx("span",{className:"text-bambu-gray",children:"→"}),r.jsxs("select",{value:g?`${f.type}|${f.color}`:"",onChange:k=>u(m.slot_id,k.target.value),disabled:b.length===0,className:`flex-1 px-2 py-1 rounded border text-xs bg-bambu-dark-secondary focus:outline-none focus:ring-1 focus:ring-bambu-green ${g?"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"),": ",x," (",S,")"]}),b.map((k,P)=>r.jsxs("option",{value:`${k.type}|${k.color}`,className:"bg-bambu-dark text-white",children:[k.tray_sub_brands||k.type," (",_c(k.color),")"]},`${k.type}-${k.color}-${k.tray_sub_brands}-${P}`))]}),g?r.jsx("button",{type:"button",onClick:()=>u(m.slot_id,""),className:"text-bambu-gray hover:text-white transition-colors",title:o("printModal.resetToOriginal"),children:r.jsx(bs,{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?.[m.slot_id]??!1,onChange:k=>s?.(m.slot_id,k.target.checked),className:"accent-bambu-green w-3 h-3"}),r.jsx(nv,{className:"w-3 h-3"}),o("printModal.forceColorMatch")]})]},m.slot_id)})})]})}function O9e({plates:t,isMultiPlate:e,selectedPlates:a,onToggle:n,onSelectAll:i,onDeselectAll:s,multiSelect:o}){const{t:l}=wt();if(!e||t.length<=1)return null;const c=a.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(tn,{className:"w-4 h-4 text-bambu-gray"}),r.jsxs("span",{className:"text-sm text-bambu-gray",children:["Select Plate",o?"s":""," to Print"]}),a.size===0&&r.jsxs("span",{className:"text-xs text-orange-400 flex items-center gap-1",children:[r.jsx(xa,{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=a.has(d.index);return r.jsxs("button",{type:"button",onClick:()=>n(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(xs,{className:"w-4 h-4 text-bambu-green flex-shrink-0"}):r.jsx(so,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"})),d.has_thumbnail&&d.thumbnail_url!=null?r.jsx("img",{src:zn(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(tn,{className:"w-5 h-5 text-bambu-gray"})}),r.jsxs("div",{className:"min-w-0 flex-1",children:[r.jsx("p",{className:"text-sm text-white font-medium truncate",children: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?` • ${ds(d.print_time_seconds)}`:""]}),(()=>{const m=wk(d.bed_type);return m?r.jsxs("p",{className:"text-xs text-bambu-gray flex items-center gap-1 mt-0.5 truncate",title:m.label,children:[r.jsx("img",{src:m.icon,alt:"",className:"w-3.5 h-3.5 object-contain flex-shrink-0"}),r.jsx("span",{className:"truncate",children:m.label})]}):null})()]}),!o&&u&&r.jsx(_r,{className:"w-4 h-4 text-bambu-green flex-shrink-0"})]},d.index)})})]})}const B9e=new Set(["IDLE","FINISH","FAILED"]);function U9e({printerResult:t,filamentReqs:e,onUpdateConfig:a}){const n=ia(),[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),a({useDefault:!1,manualMappings:m,autoConfigured:!1})},l=async()=>{s(!0);try{await ne.refreshPrinterStatus(t.printerId),await new Promise(d=>setTimeout(d,500)),await n.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(v=>v.globalTrayId===m),f=!0;else{const v=new Set(Object.values(t.config.manualMappings)),b=n.getQueryData(["settings"]);p=A9e(d,t.loadedFilaments,v,b?.prefer_lowest_filament)}let g="mismatch";if(p){const v=p.type?.toUpperCase()===d.type?.toUpperCase(),b=On(p.color)===On(d.color)||fd(p.color,d.color);v&&b?g="match":v&&(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} - ${_c(d.color)}`,children:r.jsx(Uw,{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(_r,{className:"w-3 h-3 text-bambu-green"}):m==="type_only"?r.jsx("span",{title:"Same type, different color",children:r.jsx(xa,{className:"w-3 h-3 text-yellow-400"})}):r.jsx("span",{title:"Filament type not loaded",children:r.jsx(xa,{className:"w-3 h-3 text-orange-400"})})]},f))]})}function H9e({printers:t,selectedPrinterIds:e,onMultiSelect:a,isLoading:n=!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:v,onTargetLocationChange:b,slicedForModel:x}){const[S,k]=y.useState(!1),P=s?t:t.filter(ie=>ie.is_active),N=dp({queries:P.map(ie=>({queryKey:["printerStatus",ie.id],queryFn:()=>ne.getPrinterStatus(ie.id),staleTime:5e3}))}),T=y.useMemo(()=>{const ie=new Map;return P.forEach((ue,he)=>{const ge=N[he];ge?.data&&ie.set(ue.id,ge.data)}),ie},[P,N]),j=ie=>{const ue=T.get(ie);return ue?ue.connected?!B9e.has(ue.state??""):!0:!1},D=ie=>{const ue=T.get(ie);if(!ue)return null;if(!ue.connected)return"Offline";const he=ue.state;return he?he==="RUNNING"?ue.stg_cur_name||"Printing":he==="PREPARE"?"Preparing":he==="PAUSE"?"Paused":he==="IDLE"?"Idle":he==="FINISH"?"Finished":he==="FAILED"?"Failed":he:null},C=y.useMemo(()=>{if(m!=="printer"||!x||S)return P;const ie=P.filter(ue=>ue.model===x);return ie.length>0?ie:P},[P,m,x,S]),E=P.length-C.length,R=y.useMemo(()=>{const ie=P.map(ue=>ue.model).filter(ue=>!!ue);return[...new Set(ie)].sort()},[P]),I=y.useMemo(()=>{if(!f)return[];const ie=P.filter(ue=>ue.model===f&&ue.location).map(ue=>ue.location).filter(ue=>!!ue);return[...new Set(ie)].sort()},[P,f]),O=p&&g&&R.length>0,z=i&&e.length>1&&l&&c?.filaments&&c.filaments.length>0&&d&&u;if(n)return r.jsx("div",{className:"flex justify-center py-8",children:r.jsx(lt,{className:"w-6 h-6 text-bambu-green animate-spin"})});if(C.length===0)return r.jsxs("div",{className:"flex items-center gap-2 text-red-400 text-sm mb-4",children:[r.jsx(wn,{className:"w-4 h-4"}),"No ",s?"":"active ","printers available"]});const X=ie=>{o&&j(ie)||(i?e.includes(ie)?a(e.filter(ue=>ue!==ie)):a([...e,ie]):a([ie]))},ae=()=>{const ie=o?C.filter(ue=>!j(ue.id)):C;a(ie.map(ue=>ue.id))},Y=()=>{a([])},ce=(ie,ue,he)=>{he.stopPropagation(),!(!d||!u)&&(ue?d(ie):u(ie,{useDefault:!0,manualMappings:{},autoConfigured:!1}))},de=ie=>e.includes(ie),oe=e.length,K=ie=>l?.find(ue=>ue.printerId===ie);return r.jsxs("div",{className:"space-y-2 mb-6",children:[O&&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(xr,{className:"w-4 h-4"}),r.jsx("span",{className:"text-sm",children:"Specific Printer"})]}),r.jsxs("button",{type:"button",onClick:()=>{p("model"),a([]);const ie=x&&R.includes(x)?x:R[0];g(ie)},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(Sm,{className:"w-4 h-4"}),r.jsxs("span",{className:"text-sm",children:["Any ",x||"Model"]})]})]}),m==="model"&&O&&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:ie=>{g(ie.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..."}),R.map(ie=>r.jsx("option",{value:ie,children:ie},ie))]})]}),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:v||"",onChange:ie=>b(ie.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(ie=>r.jsx("option",{value:ie,children:ie},ie))]})]}),f&&r.jsxs("p",{className:"text-xs text-bambu-gray",children:["Scheduler will assign to first available idle ",f," printer",v?` in ${v}`:""]})]}),m==="printer"&&i&&C.length>1&&r.jsxs("div",{className:"flex items-center justify-between text-xs text-bambu-gray mb-2",children:[r.jsx("span",{children:oe===0?"Select printers":`${oe} printer${oe!==1?"s":""} selected`}),r.jsxs("div",{className:"flex gap-2",children:[oe0&&r.jsx("button",{type:"button",onClick:Y,className:"text-bambu-gray hover:text-white transition-colors",children:"Clear"})]})]}),m==="printer"&&C.map(ie=>{const ue=de(ie.id),he=K(ie.id),ge=he&&!he.config.useDefault,q=j(ie.id),Q=o&&q,A=D(ie.id);return r.jsxs("div",{children:[r.jsxs("button",{type:"button",onClick:()=>X(ie.id),disabled:Q,className:`w-full flex items-center gap-3 p-3 rounded-lg border transition-colors ${Q?"border-bambu-dark-tertiary bg-bambu-dark opacity-50 cursor-not-allowed":ue?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary bg-bambu-dark hover:border-bambu-gray"} ${ie.is_active?"":"opacity-60"}`,children:[r.jsx("div",{className:`p-2 rounded-lg ${Q?"bg-bambu-dark-tertiary":ue?"bg-bambu-green/20":"bg-bambu-dark-tertiary"}`,children:r.jsx(xr,{className:`w-5 h-5 ${Q?"text-bambu-gray/50":ue?"text-bambu-green":"text-bambu-gray"}`})}),r.jsxs("div",{className:"text-left flex-1",children:[r.jsxs("p",{className:`font-medium ${Q?"text-bambu-gray":"text-white"}`,children:[ie.name,!ie.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:[ie.model||"Unknown model"," • ",ie.ip_address]})]}),A&&r.jsx("span",{className:`text-xs px-2 py-0.5 rounded-full ${q?"bg-yellow-500/20 text-yellow-400":"bg-bambu-green/20 text-bambu-green"}`,children:A}),i&&r.jsx("div",{className:`w-5 h-5 rounded border-2 flex items-center justify-center transition-colors ${Q?"border-bambu-gray/30":ue?"bg-bambu-green border-bambu-green":"border-bambu-gray/50"}`,children:ue&&r.jsx(_r,{className:"w-3 h-3 text-white"})})]}),ue&&z&&he&&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:F=>F.stopPropagation(),children:[r.jsx("input",{type:"checkbox",checked:ge,onChange:F=>ce(ie.id,F.target.checked,F),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 ${he.matchStatus==="full"?"text-bambu-green":he.matchStatus==="partial"?"text-yellow-400":"text-orange-400"}`,children:["(",he.exactMatches,"/",he.totalSlots," matched)"]}),he.isLoading&&r.jsx(tr,{className:"w-3 h-3 text-bambu-gray animate-spin"}),ge&&r.jsxs("button",{type:"button",onClick:F=>{F.stopPropagation(),d(ie.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(qI,{className:"w-3 h-3"}),"Auto"]})]}),ge&&r.jsx(U9e,{printerResult:he,filamentReqs:c.filaments,onUpdateConfig:F=>u(ie.id,F)})]})]},ie.id)}),m==="printer"&&E>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(xa,{className:"w-3 h-3 text-yellow-400"}),E," other printer",E>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"&&oe===0&&r.jsxs("p",{className:"text-xs text-orange-400 mt-1 flex items-center gap-1",children:[r.jsx(wn,{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(wn,{className:"w-3 h-3"}),"Select a target printer model"]})]})}function q9e({options:t,onChange:e,defaultExpanded:a=!1,showDualNozzleOptions:n=!1}){const{t:i}=wt(),[s,o]=y.useState(a),c=[{key:"bed_levelling",label:i("settings.defaultBedLevelling"),desc:i("settings.defaultBedLevellingDesc")},{key:"flow_cali",label:i("settings.defaultFlowCali"),desc:i("settings.defaultFlowCaliDesc")},{key:"vibration_cali",label:i("settings.defaultVibrationCali"),desc:i("settings.defaultVibrationCaliDesc")},{key:"layer_inspect",label:i("settings.defaultLayerInspect"),desc:i("settings.defaultLayerInspectDesc")},{key:"timelapse",label:i("settings.defaultTimelapse"),desc:i("settings.defaultTimelapseDesc")},{key:"nozzle_offset_cali",label:i("settings.defaultNozzleOffsetCali"),desc:i("settings.defaultNozzleOffsetCaliDesc"),dualNozzleOnly:!0}].filter(u=>!u.dualNozzleOnly||n),d=u=>{e({...t,[u]:!t[u]})};return r.jsxs("div",{className:"mb-4",children:[r.jsxs("button",{type:"button",onClick:()=>o(!s),className:"flex items-center gap-2 text-sm text-bambu-gray hover:text-white transition-colors w-full",children:[r.jsx(Sy,{className:"w-4 h-4"}),r.jsx("span",{children:i("queue.bulkEdit.printOptions")}),s?r.jsx(el,{className:"w-4 h-4 ml-auto"}):r.jsx(za,{className:"w-4 h-4 ml-auto"})]}),s&&r.jsx("div",{className:"mt-2 bg-bambu-dark rounded-lg p-3 space-y-2",children:c.map(({key:u,label:m,desc:p})=>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:m}),r.jsx("p",{className:"text-xs text-bambu-gray",children:p})]}),r.jsx("div",{className:`relative w-10 h-5 rounded-full transition-colors ${t[u]?"bg-bambu-green":"bg-bambu-dark-tertiary"}`,onClick:()=>d(u),children:r.jsx("div",{className:`absolute top-0.5 w-4 h-4 rounded-full bg-white transition-transform ${t[u]?"translate-x-5":"translate-x-0.5"}`})})]},u))})]})}function V9e({options:t,onChange:e,dateFormat:a="system",timeFormat:n="system",canControlPrinter:i=!0,showStagger:s=!1,printerCount:o=0,hasGcodeSnippets:l=!1}){const{t:c}=wt(),[d,u]=y.useState(""),[m,p]=y.useState(""),[f,g]=y.useState(!0),[v,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 C;t.scheduledTime?(C=new Date(t.scheduledTime),isNaN(C.getTime())&&(C=new Date,C.setHours(C.getHours()+1,0,0,0))):(C=new Date,C.setHours(C.getHours()+1,0,0,0),e({...t,scheduledTime:b3(C)})),u(g3(C,a)),p(H8(C,n)),g(!0),b(!0)}},[t.scheduleType,t.scheduledTime,a,n,e,t]);const k=C=>{e({...t,scheduleType:C})},P=(C,E)=>{const R=D0e(C,a),I=F0e(E);g(!!R),b(!!I),R&&I&&(R.setHours(I.hours,I.minutes,0,0),R>new Date&&e({...t,scheduledTime:b3(R)}))},N=C=>{u(C),P(C,m)},T=C=>{p(C),P(d,C)},j=C=>{const E=C.target.value;if(E){const R=new Date(E);isNaN(R.getTime())||(u(g3(R,a)),p(H8(R,n)),g(!0),b(!0),e({...t,scheduledTime:E}))}},D=()=>{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(ar,{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(Cn,{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(lJ,{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:C=>N(C.target.value),placeholder:j0e(a)}),r.jsx("button",{type:"button",onClick:D,className:"absolute right-2 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white",title:"Open calendar",children:r.jsx(Cn,{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:j,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 ${v?"border-bambu-dark-tertiary focus:border-bambu-green":"border-red-500"}`,value:m,onChange:C=>T(C.target.value),placeholder:M0e(n)})})]}),(!f||!v)&&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:C=>e({...t,requirePreviousSuccess:C.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:C=>e({...t,autoOffAfter:C.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(Nu,{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:C=>e({...t,gcodeInjection:C.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(tv,{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:C=>e({...t,staggerEnabled:C.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(tn,{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:C=>e({...t,staggerGroupSize:Math.max(1,parseInt(C.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:C=>e({...t,staggerIntervalMinutes:Math.max(1,parseInt(C.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 C=Math.ceil(o/t.staggerGroupSize),E=o%t.staggerGroupSize,R=(C-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:C,size:t.staggerGroupSize,interval:t.staggerIntervalMinutes}),E!==0&&t.staggerGroupSize1?` (${c("printModal.staggerTotal","total: {{minutes}} min",{minutes:R})})`:""]})})()]})]}),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 Sl={bed_levelling:!0,flow_cali:!1,vibration_cali:!0,layer_inspect:!1,timelapse:!1,nozzle_offset_cali:!0},AF={scheduleType:"asap",scheduledTime:"",requirePreviousSuccess:!1,autoOffAfter:!1,gcodeInjection:!1,staggerEnabled:!1,staggerGroupSize:2,staggerIntervalMinutes:5};function Pc({mode:t,archiveId:e,libraryFileId:a,archiveName:n,queueItem:i,initialSelectedPrinterIds:s,onClose:o,onSuccess:l,projectId:c,cleanupLibraryAfterDispatch:d}){const{t:u}=wt(),m=ia(),{showToast:p}=da(),{hasPermission:f}=lr(),g=!!a&&!e,[v,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,[P,N]=y.useState(1),[T,j]=y.useState(()=>t==="edit-queue-item"&&i?{bed_levelling:i.bed_levelling??Sl.bed_levelling,flow_cali:i.flow_cali??Sl.flow_cali,vibration_cali:i.vibration_cali??Sl.vibration_cali,layer_inspect:i.layer_inspect??Sl.layer_inspect,timelapse:i.timelapse??Sl.timelapse,nozzle_offset_cali:i.nozzle_offset_cali??Sl.nozzle_offset_cali}:Sl),[D,C]=y.useState(()=>{if(t==="edit-queue-item"&&i){let Ce="asap";i.manual_start?Ce="manual":i.scheduled_time&&!pY(i.scheduled_time)&&(Ce="scheduled");let Ke="";if(i.scheduled_time&&!pY(i.scheduled_time)){const nt=Ga(i.scheduled_time)??new Date;Ke=b3(nt)}return{scheduleType:Ce,scheduledTime:Ke,requirePreviousSuccess:i.require_previous_success,autoOffAfter:i.auto_off_after,gcodeInjection:i.gcode_injection??!1,staggerEnabled:!1,staggerGroupSize:AF.staggerGroupSize,staggerIntervalMinutes:AF.staggerIntervalMinutes}}return AF}),[E,R]=y.useState(()=>{if(t==="edit-queue-item"&&i?.ams_mapping&&Array.isArray(i.ams_mapping)){const Ce={};return i.ams_mapping.forEach((Ke,nt)=>{Ke!==-1&&(Ce[nt+1]=Ke)}),Ce}return{}}),[I,O]=y.useState({}),[z,X]=y.useState(()=>t==="edit-queue-item"&&i?.target_model?"model":"printer"),[ae,Y]=y.useState(()=>t==="edit-queue-item"&&i?.target_model?i.target_model:null),[ce,de]=y.useState(()=>t==="edit-queue-item"&&i?.target_location?i.target_location:null),[oe,K]=y.useState(()=>{if(t==="edit-queue-item"&&i?.filament_overrides){const Ce={};for(const Ke of i.filament_overrides)Ce[Ke.slot_id]={type:Ke.type,color:Ke.color};return Ce}return{}}),[ie,ue]=y.useState(()=>{if(t==="edit-queue-item"&&i?.filament_overrides){const Ce={};for(const Ke of i.filament_overrides)Ce[Ke.slot_id]=Ke.force_color_match===!0;return Ce}return{}}),[he]=y.useState(()=>t==="edit-queue-item"&&i?.printer_id?[i.printer_id]:[]),[ge]=y.useState(()=>t==="edit-queue-item"&&i?i.plate_id:null),[q,Q]=y.useState(!1),[A,F]=y.useState({current:0,total:0}),[B,W]=y.useState(null),[H,le]=y.useState(new Set),U=v.length,G=v.length>0?v[0]:null,{data:Z}=$e({queryKey:["settings"],queryFn:ne.getSettings}),J=y.useRef(!1);y.useEffect(()=>{!Z||J.current||t==="edit-queue-item"||(J.current=!0,j({bed_levelling:Z.default_bed_levelling??Sl.bed_levelling,flow_cali:Z.default_flow_cali??Sl.flow_cali,vibration_cali:Z.default_vibration_cali??Sl.vibration_cali,layer_inspect:Z.default_layer_inspect??Sl.layer_inspect,timelapse:Z.default_timelapse??Sl.timelapse,nozzle_offset_cali:Z.default_nozzle_offset_cali??Sl.nozzle_offset_cali}))},[Z,t]);const re=y.useRef(!1);y.useEffect(()=>{!Z||re.current||t==="edit-queue-item"||(re.current=!0,C(Ce=>({...Ce,staggerGroupSize:Z.stagger_group_size??Ce.staggerGroupSize,staggerIntervalMinutes:Z.stagger_interval_minutes??Ce.staggerIntervalMinutes})))},[Z,t]);const se=Vo(Z?.currency||"USD"),fe=Z?.default_filament_cost??0,{data:me,isLoading:pe}=$e({queryKey:["printers"],queryFn:ne.getPrinters}),{data:V}=$e({queryKey:["spool-assignments"],queryFn:()=>ne.getAssignments(),staleTime:30*1e3,enabled:(t==="reprint"||t==="add-to-queue")&&z==="printer"||g&&t==="reprint"}),{data:L}=$e({queryKey:["archive",e],queryFn:()=>ne.getArchive(e),enabled:!!e&&!g}),{data:te}=$e({queryKey:["library-file",a],queryFn:()=>ne.getLibraryFile(a),enabled:g&&!!a}),be=L?.sliced_for_model||te?.sliced_for_model||null,{data:xe,isError:ve}=$e({queryKey:["archive-plates",e],queryFn:()=>ne.getArchivePlates(e),enabled:!!e&&!g,retry:!1}),{data:De}=$e({queryKey:["library-file-plates",a],queryFn:()=>ne.getLibraryFilePlates(a),enabled:g&&!!a}),je=g?De:xe,{data:Te,isError:qe}=$e({queryKey:["archive-filaments",e,k],queryFn:()=>ne.getArchiveFilamentRequirements(e,k??void 0),enabled:!!e&&!g&&(k!==null||!je?.is_multi_plate),retry:!1}),{data:Pe}=$e({queryKey:["library-file-filaments",a,k],queryFn:()=>ne.getLibraryFileFilamentRequirements(a,k??void 0),enabled:g&&!!a&&(k!==null||!je?.is_multi_plate)}),Ie=!g&&(ve||qe),Re=g?Pe:Te,Ue=y.useMemo(()=>{if(!(k===null||!je?.plates?.length))return je.plates.find(Ce=>Ce.index===k)?.name||void 0},[je,k]),{data:ze}=$e({queryKey:["available-filaments",ae,ce],queryFn:()=>ne.getAvailableFilaments(ae,ce??void 0),enabled:z==="model"&&!!ae}),{data:it}=$e({queryKey:["printer-status",G],queryFn:()=>ne.getPrinterStatus(G),enabled:!!G}),{amsMapping:Oe}=Dse(Re,it,E,Z?.prefer_lowest_filament),tt=D9e(v,me,Re,E,I,O,Z?.prefer_lowest_filament);y.useEffect(()=>{je?.plates&&je.plates.length>=1&&x.size===0&&S(new Set([je.plates[0].index]))},[je,x.size]),y.useEffect(()=>{if(t==="edit-queue-item")return;const Ce=me?.filter(Ke=>Ke.is_active)||[];Ce.length===1&&v.length===0&&b([Ce[0].id])},[t,me,v.length]),y.useEffect(()=>{t==="edit-queue-item"?(JSON.stringify(v.sort())!==JSON.stringify(he.sort())||k!==ge)&&(R({}),O({}),le(new Set)):(R({}),O({}),le(new Set))},[t,v,k,he,ge]);const[Fe,Ye]=y.useState(ae),[Ve,Me]=y.useState(k);y.useEffect(()=>{(ae!==Fe||k!==Ve)&&(Ye(ae),Me(k),(t!=="edit-queue-item"||Fe!==null)&&(K({}),ue({})))},[ae,k,Fe,Ve,t]),y.useEffect(()=>{if(!Z?.per_printer_mapping_expanded||v.length<=1)return;const Ce=v.filter(Ke=>{if(H.has(Ke))return!1;const nt=tt.printerResults.find(Ae=>Ae.printerId===Ke);return nt&&nt.status&&!nt.isLoading});Ce.length>0&&(le(Ke=>{const nt=new Set(Ke);return Ce.forEach(Ae=>nt.add(Ae)),nt}),Ce.forEach(Ke=>{tt.autoConfigurePrinter(Ke)}))},[Z?.per_printer_mapping_expanded,v,H,tt]),y.useEffect(()=>{const Ce=Ke=>{Ke.key==="Escape"&&!q&&o()};return window.addEventListener("keydown",Ce),()=>window.removeEventListener("keydown",Ce)},[o,q]);const Be=je?.is_multi_plate??!1,Qe=je?.plates??[],Ge=y.useMemo(()=>{const Ce=new Map;return V&&V.forEach(Ke=>{const nt=Ke.ams_id===255,Ae=ib(Ke.ams_id,Ke.tray_id,nt),we=Ce.get(Ke.printer_id)??new Map;we.set(Ae,Ke),Ce.set(Ke.printer_id,we)}),Ce},[V]),Ee=y.useMemo(()=>{if(!B||B.length===0)return"";const Ce=B.map(Ke=>u("printModal.insufficientFilamentLine",{printer:Ke.printerName,slot:Ke.slotLabel,required:Math.round(Ke.requiredGrams),remaining:Math.round(Ke.remainingGrams)}));return[u("printModal.insufficientFilamentMessage"),...Ce].join(` `)},[B,u]),at=rt({mutationFn:Ce=>ne.addToQueue(Ce)}),Xe=rt({mutationFn:Ce=>ne.updateQueueItem(i.id,Ce),onSuccess:()=>{m.invalidateQueries({queryKey:["queue"]}),p("Queue item updated"),l?.(),o()},onError:Ce=>{p(Ce.message||"Failed to update queue item","error")}}),Nt=D.staggerEnabled&&v.length>1,Vt=async(Ce,Ke)=>{if(Ce?.preventDefault(),!Ke?.skipFilamentCheck&&!Z?.disable_filament_warnings&&(t==="reprint"||t==="add-to-queue")&&z==="printer"){const Je=[],Ze=Re?.filaments??[];if(Ze.length>0&&Ge.size>0){const kt=(ft,_t)=>!Number.isFinite(ft)||ft<=0||!Number.isFinite(_t)||_t<0?null:Math.max(0,ft-_t);for(const ft of v){const _t=v.length>1?tt.getFinalMapping(ft):Oe;if(!_t)continue;const St=v.length>1?tt.printerResults.find(Se=>Se.printerId===ft)?.status:it,qt=vk(St),yt=new Map(qt.map(Se=>[Se.globalTrayId,Se.label])),Ot=Ge.get(ft),ua=me?.find(Se=>Se.id===ft)?.name??`Printer ${ft}`;Ot&&Ze.forEach(Se=>{if(!Se.slot_id||Se.slot_id<=0)return;const xt=_t[Se.slot_id-1];if(!Number.isFinite(xt)||xt<0)return;const Kt=Ot.get(xt)?.spool;if(!Kt)return;const Zt=kt(Kt.label_weight,Kt.weight_used);Zt!==null&&(Zt>=Se.used_grams||Je.push({printerName:ua,slotLabel:yt.get(xt)??`Slot ${Se.slot_id}`,requiredGrams:Se.used_grams,remainingGrams:Zt}))})}}if(Je.length>0){W(Je);return}}if(z==="printer"&&v.length===0){p("Please select at least one printer","error");return}if(z==="model"&&!ae){p("Please select a target printer model","error");return}Q(!0);const nt=x.size>1?Qe.filter(Je=>x.has(Je.index)):[null],Ae=z==="model"?nt.length:v.length*nt.length;F({current:0,total:Ae});const we={success:0,failed:0,errors:[]},ct=Je=>{if(v.length>1){const Ze=I[Je];if(Ze&&!Ze.useDefault)return tt.getFinalMapping(Je)}return Oe},We=(()=>{const Je=[];if(Re?.filaments)for(const Ze of Re.filaments){const kt=oe[Ze.slot_id],ft=ie[Ze.slot_id]??!1,_t=kt?.type??Ze.type,St=kt?.color??Ze.color;(kt||ft)&&Je.push({slot_id:Ze.slot_id,type:_t,color:St,color_name:_c(St),force_color_match:ft})}else for(const[Ze,{type:kt,color:ft}]of Object.entries(oe)){const _t=parseInt(Ze,10),St=ie[_t]??!1;Je.push({slot_id:_t,type:kt,color:ft,color_name:_c(ft),force_color_match:St})}return Je.length>0?Je:void 0})(),st=(Je,Ze)=>({printer_id:z==="printer"?Je:null,target_model:z==="model"?ae:null,target_location:z==="model"?ce:null,filament_overrides:z==="model"?We:void 0,archive_id:g?void 0:e,library_file_id:g?a:void 0,require_previous_success:D.requirePreviousSuccess,auto_off_after:D.autoOffAfter,gcode_injection:D.gcodeInjection,manual_start:D.scheduleType==="manual",skip_filament_check:Ke?.skipFilamentCheck===!0?!0:void 0,ams_mapping:Je?ct(Je):void 0,plate_id:Ze!==void 0?Ze:k,scheduled_time:D.scheduleType==="scheduled"&&D.scheduledTime?new Date(D.scheduledTime).toISOString():void 0,...T,project_id:c??void 0});if(z==="model"){if(t==="reprint"){p("Model-based assignment only works with queue mode","error"),Q(!1);return}let Je=0;for(const Ze of nt){Je++,F({current:Je,total:Ae});const kt=Ze?Ze.index:k;try{if(t==="edit-queue-item"&&!Ze){const ft={printer_id:null,target_model:ae,target_location:ce,filament_overrides:We||null,require_previous_success:D.requirePreviousSuccess,auto_off_after:D.autoOffAfter,gcode_injection:D.gcodeInjection,manual_start:D.scheduleType==="manual",ams_mapping:void 0,plate_id:kt,scheduled_time:D.scheduleType==="scheduled"&&D.scheduledTime?new Date(D.scheduledTime).toISOString():null,...T};await Xe.mutateAsync(ft)}else{const ft=st(null,kt);Xt>1&&(ft.quantity=Xt),await at.mutateAsync(ft)}we.success++}catch(ft){we.failed++;const _t=Ze?Ze.name||`Plate ${Ze.index}`:"";we.errors.push(_t?`${_t}: ${ft.message}`:ft.message)}}}else{const Je=D.staggerEnabled&&(t==="add-to-queue"||t==="reprint")&&v.length>1,Ze=Je?D.scheduleType==="scheduled"&&D.scheduledTime?new Date(D.scheduledTime).getTime():Date.now():0;let kt=0;for(const ft of nt){const _t=ft?ft.index:k;for(let St=0;St1){const Ot=st(qt,_t);Ot.quantity=Xt-1,await at.mutateAsync(Ot)}}else if(t==="edit-queue-item"&&kt===1){const yt=ct(qt),Ot={printer_id:qt,target_model:null,target_location:null,require_previous_success:D.requirePreviousSuccess,auto_off_after:D.autoOffAfter,gcode_injection:D.gcodeInjection,manual_start:D.scheduleType==="manual",ams_mapping:yt,plate_id:_t,scheduled_time:D.scheduleType==="scheduled"&&D.scheduledTime?new Date(D.scheduledTime).toISOString():null,...T};await Xe.mutateAsync(Ot)}else{const yt=st(qt,_t);if(Xt>1&&(yt.quantity=Xt),Je){const Ot=Math.floor(St/D.staggerGroupSize);if(Ot>0){const ua=Ot*D.staggerIntervalMinutes*6e4;yt.scheduled_time=new Date(Ze+ua).toISOString()}}await at.mutateAsync(yt)}we.success++}catch(yt){we.failed++;const Ot=me?.find(xt=>xt.id===qt)?.name||`Printer ${qt}`,ua=ft?ft.name||`Plate ${ft.index}`:"",Se=ua?`${Ot} (${ua})`:Ot;we.errors.push(`${Se}: ${yt.message}`)}}}}Q(!1),we.failed===0?(t==="reprint"&&Nt?p(u("queue.itemsQueued",{count:we.success})):t!=="reprint"&&(t==="edit-queue-item"?p("Queue item updated"):we.success===1?p(z==="model"?`Queued for any ${ae}`:u("queue.printQueued")):p(u("queue.itemsQueued",{count:we.success}))),m.invalidateQueries({queryKey:["queue"]}),l?.(),o()):we.success===0?p(`Failed: ${we.errors[0]}`,"error"):(p(`${we.success} succeeded, ${we.failed} failed`,"error"),m.invalidateQueries({queryKey:["queue"]}))},ht=q||Xe.isPending,It=y.useMemo(()=>!(ht||z==="printer"&&v.length===0||z==="model"&&!ae||z==="model"&&t==="reprint"||Be&&x.size===0),[v.length,z,ae,t,Be,x.size,ht]),Xt=z==="printer"&&v.length>1?1:P,la=(()=>{const Ce=v.length;if(t==="reprint"){const Ke=Nt&&Ce>1;let nt=Ke?u("printModal.staggerToPrinters",{count:Ce,defaultValue:"Stagger to {{count}} printers"}):Ce>1?u("queue.printToPrinters",{count:Ce}):u("queue.print");return Xt>1&&(nt=`${nt} ×${Xt}`),{title:u(g?"queue.print":"queue.reprint"),icon:xr,submitText:nt,submitIcon:Ke?Cn:xr,loadingText:A.total>1?u("queue.sendingProgress",{current:A.current,total:A.total}):u("queue.sending")}}if(t==="add-to-queue"){let Ke=u("queue.addToQueue");return x.size>1?Ke=u("queue.queueSelectedPlates",{count:x.size}):Ce>1&&(Ke=u("queue.queueToPrinters",{count:Ce})),Xt>1&&(Ke=`${Ke} ×${Xt}`),{title:u("queue.schedulePrint"),icon:Cn,submitText:Ke,submitIcon:Cn,loadingText:A.total>1?u("queue.addingProgress",{current:A.current,total:A.total}):u("queue.adding")}}return{title:u("queue.editQueueItem"),icon:ci,submitText:u("common.save"),submitIcon:ci,loadingText:A.total>1?u("queue.savingProgress",{current:A.current,total:A.total}):u("common.saving")}})(),ot=la.icon,vt=la.submitIcon,Pt=G&&x.size<=1&&(g||(Be?k!==null:!0)),ea=y.useMemo(()=>new Set(["H2D","H2DPRO","H2C","X2D"]),[]),aa=y.useMemo(()=>z==="model"?ae?ea.has(ae.toUpperCase().replace(/[\s-]/g,"")):!1:!me||v.length===0?!1:v.some(Ce=>me.find(Ke=>Ke.id===Ce)?.nozzle_count===2),[z,ae,me,v,ea]);return r.jsxs("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:q?void 0:o,children:[r.jsx(Tt,{className:"w-full max-w-2xl max-h-[90vh] overflow-y-auto",onClick:Ce=>Ce.stopPropagation(),children:r.jsxs(jt,{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(ot,{className:"w-5 h-5 text-bambu-green"}),r.jsx("h2",{className:"text-lg font-semibold text-white",children:la.title})]}),r.jsx(Le,{variant:"ghost",size:"sm",onClick:o,disabled:q,children:r.jsx(Ht,{className:"w-5 h-5"})})]}),r.jsxs("form",{onSubmit:Vt,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:n})," to"," ",s?.length===1&&me?r.jsx("span",{className:"text-white",children:me.find(Ce=>Ce.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:n})]})}),(()=>{if(!Qe.length)return null;const Ce=k!=null?Qe.find(nt=>nt.index===k):Qe[0],Ke=wk(Ce?.bed_type);return Ke?r.jsxs("p",{className:"flex items-center gap-1.5 text-xs text-bambu-gray -mt-2",title:Ke.label,children:[r.jsx("img",{src:Ke.icon,alt:"",className:"w-4 h-4 object-contain flex-shrink-0"}),r.jsx("span",{className:"truncate",children:Ke.label})]}):null})(),r.jsx(O9e,{plates:Qe,isMultiPlate:Be,selectedPlates:x,onToggle:Ce=>{S(Ke=>{const nt=new Set(Ke);return t==="add-to-queue"?nt.has(Ce)?nt.delete(Ce):nt.add(Ce):(nt.clear(),nt.add(Ce)),nt})},onSelectAll:t==="add-to-queue"?()=>S(new Set(Qe.map(Ce=>Ce.index))):void 0,onDeselectAll:t==="add-to-queue"?()=>S(new Set):void 0,multiSelect:t==="add-to-queue"}),!s?.length&&r.jsx(H9e,{printers:me||[],selectedPrinterIds:v,onMultiSelect:b,isLoading:pe,allowMultiple:!0,showInactive:t==="edit-queue-item",disableBusy:t==="reprint",printerMappingResults:tt.printerResults,filamentReqs:Re,onAutoConfigurePrinter:tt.autoConfigurePrinter,onUpdatePrinterConfig:tt.updatePrinterConfig,assignmentMode:t==="reprint"?"printer":z,onAssignmentModeChange:t!=="reprint"?X:void 0,targetModel:ae,onTargetModelChange:t!=="reprint"?Y:void 0,targetLocation:ce,onTargetLocationChange:t!=="reprint"?de:void 0,slicedForModel:be}),z==="model"&&ae&&Re&&ze&&ze.length>0&&r.jsx(I9e,{filamentReqs:Re,availableFilaments:ze,overrides:oe,onChange:K,forceColorMatch:ie,onForceColorMatchChange:(Ce,Ke)=>ue(nt=>({...nt,[Ce]:Ke}))}),be&&z==="printer"&&v.length===1&&(()=>{const Ce=me?.find(Ke=>Ke.id===v[0]);return Ce&&Ce.model&&be!==Ce.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(xa,{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 ",Ce.model]})]}):null})(),Ie&&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(wn,{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."})]}),Pt&&!Ie&&v.length===1&&r.jsx(z9e,{printerId:G,filamentReqs:Re,manualMappings:E,onManualMappingChange:R,defaultExpanded:!!s?.length||(Z?.per_printer_mapping_expanded??!1),currencySymbol:se,defaultCostPerKg:fe,forceColorMatch:ie,onForceColorMatchChange:(Ce,Ke)=>ue(nt=>({...nt,[Ce]:Ke}))}),(t==="reprint"||U>0||z==="model"&&ae)&&r.jsx(q9e,{options:T,onChange:j,defaultExpanded:!!s?.length,showDualNozzleOptions:aa}),t!=="edit-queue-item"&&(z==="model"||v.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:P,onChange:Ce=>N(Math.max(1,Math.min(999,parseInt(Ce.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"}),P>1&&r.jsx("span",{className:"text-xs text-bambu-gray",children:u("queue.quantityHint","Creates {{count}} queue items",{count:P})})]}),t==="reprint"&&z==="printer"&&v.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:D.staggerEnabled,onChange:Ce=>C({...D,staggerEnabled:Ce.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(tn,{className:"w-3.5 h-3.5"}),u("printModal.staggerPrinterStarts","Stagger printer starts")]})]}),D.staggerEnabled&&(()=>{const Ce=D.staggerGroupSize,Ke=D.staggerIntervalMinutes,nt=Math.ceil(v.length/Ce),Ae=(nt-1)*Ke;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:v.length,groups:nt,size:Ce,interval:Ke}),nt>1?` (${u("printModal.staggerTotal","total: {{minutes}} min",{minutes:Ae})})`:""]})})()]}),t!=="reprint"&&r.jsx(V9e,{options:D,onChange:C,dateFormat:Z?.date_format||"system",timeFormat:Z?.time_format||"system",canControlPrinter:f("printers:control"),showStagger:t==="add-to-queue"&&z==="printer"&&v.length>1,printerCount:v.length,hasGcodeSnippets:!!Z?.gcode_snippets}),t==="reprint"&&!!Z?.gcode_snippets&&Xt>1&&r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("input",{type:"checkbox",id:"gcodeInjectionReprint",checked:D.gcodeInjection,onChange:Ce=>C({...D,gcodeInjection:Ce.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(tv,{className:"w-3.5 h-3.5"}),u("printModal.gcodeInjection","Inject auto-print G-code")]})]}),Xe.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:Xe.error?.message||"Failed to complete operation"}),r.jsxs("div",{className:`flex gap-3 ${t==="reprint"?"":"pt-2"}`,children:[r.jsx(Le,{type:"button",variant:"secondary",onClick:o,className:"flex-1",disabled:q,children:"Cancel"}),r.jsx(Le,{type:"submit",disabled:!It,className:"flex-1",children:ht?r.jsxs(r.Fragment,{children:[r.jsx(lt,{className:"w-4 h-4 animate-spin"}),la.loadingText]}):r.jsxs(r.Fragment,{children:[r.jsx(vt,{className:"w-4 h-4"}),la.submitText]})})]})]})]})}),B&&B.length>0&&r.jsx(ka,{title:u("printModal.insufficientFilamentTitle"),message:Ee,confirmText:u("printModal.printAnyway"),cancelText:u("common.cancel"),variant:"warning",onConfirm:()=>{W(null),Vt(void 0,{skipFilamentCheck:!0})},onCancel:()=>W(null)})]})}function gY({value:t}){const{t:e}=wt(),[a,n]=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)}}n(!0),setTimeout(()=>n(!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(a?"printers.copied":"printers.copyToClipboard"),children:a?r.jsx(_r,{className:"w-3.5 h-3.5 text-bambu-green"}):r.jsx(li,{className:"w-3.5 h-3.5"})})}function G9e({printer:t,status:e,totalPrintHours:a,onClose:n}){const{t:i}=wt();y.useEffect(()=>{const o=l=>{l.key==="Escape"&&n()};return window.addEventListener("keydown",o),()=>window.removeEventListener("keydown",o)},[n]);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(gY,{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(gY,{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(RI,{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=nte(e.wifi_signal);s.push({label:i("printers.wifiSignalLabel"),value:r.jsxs("span",{className:"flex items-center gap-2",children:[r.jsx(pJ,{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")})}),a!=null&&a>0&&s.push({label:i("printers.totalPrintHours"),value:`${Math.round(a)}h`}),t.location&&s.push({label:i("printers.sort.location"),value:t.location}),s.push({label:i("printers.addedOn"),value:qg(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:n,children:r.jsx(Tt,{className:"w-full max-w-md",onClick:o=>o.stopPropagation(),children:r.jsxs(jt,{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:n,className:"p-1 hover:bg-bambu-dark rounded flex-shrink-0",children:r.jsx(Ht,{className:"w-5 h-5 text-bambu-gray"})})]}),r.jsx("div",{className:"flex justify-center mb-4",children:r.jsx("img",{src:rte(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 $9e(t){if(!t||t.length<6)return!1;const e=parseInt(t.slice(0,2),16),a=parseInt(t.slice(2,4),16),n=parseInt(t.slice(4,6),16);return(.299*e+.587*a+.114*n)/255>.6}function jF({trayColor:t,trayType:e,isEmpty:a,emptyKind:n,slotNumber:i}){const s=n==="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:a?s:"rgba(255,255,255,0.1)",borderStyle:a?"dashed":"solid"},children:r.jsx("span",{className:"text-[6px] font-bold leading-none select-none",style:{color:t&&$9e(t)?"#000":"#fff"},children:i})})}const bY=240,xY=320;function MF(t){return(t??.02).toFixed(3)}function yY({side:t}){const{mode:e}=gb(),a=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:a,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 a=t.slice(2,4);if(a==="00")return e("printers.nozzleStainlessSteel");if(a==="01")return e("printers.nozzleHardenedSteel");if(a==="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 zse(t,e){return t?t.startsWith("HH")?e("printers.nozzleHighFlow"):t.startsWith("HS")?e("printers.nozzleStandardFlow"):"":""}function Ise({slot:t,index:e,activeStatus:a,filamentName:n,children:i}){const{t:s}=wt(),[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 P=u.current.getBoundingClientRect(),N=m.current.offsetHeight,j=P.top-56,D=window.innerHeight-P.bottom;jj?d("bottom"):d("top")}},[o]);const v=()=>{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=KI(t.filament_color),S=Rse(t.nozzle_type,s),k=zse(t.nozzle_type,s);return r.jsxs("div",{ref:u,className:"relative",onMouseEnter:v,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 d27150afd..bc227e8c5 100644 --- a/static/index.html +++ b/static/index.html @@ -26,7 +26,7 @@ - +