From f7c94cbc7b22e3c8acadabe32d36216dfd12888f Mon Sep 17 00:00:00 2001 From: maziggy Date: Fri, 15 May 2026 09:47:21 +0200 Subject: [PATCH] fix(inventory): add CF/GF to subtype dropdown on the Add/Edit Spool form (#1345) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Adding a third-party PETG-CF spool via the Material=PETG + Subtype=CF flow (same shape as the existing PETG HF) hit a missing option: KNOWN_VARIANTS in spool-form/constants.ts didn't list CF or GF. Users had to type it freehand into the "create new" tail of the dropdown. Added both: CF (matches PETG-CF / PLA-CF / ASA-CF / PA-CF) and GF (the natural pair for ABS-GF / PA6-GF). parsePresetName is unaffected — its materials list is iterated longest-first, so cloud presets like "Bambu PETG-CF Black" still resolve to material=PETG-CF with empty afterMaterial. --- CHANGELOG.md | 2 ++ frontend/src/components/spool-form/constants.ts | 5 +++++ static/assets/{index-BxdzCdot.js => index-B7LxDq2k.js} | 2 +- static/index.html | 2 +- 4 files changed, 9 insertions(+), 2 deletions(-) rename static/assets/{index-BxdzCdot.js => index-B7LxDq2k.js} (98%) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7bba72ed0..021d00198 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,6 +17,8 @@ All notable changes to Bambuddy will be documented in this file. - **Slice modal: pick the build plate (#1337, reported by @digitalskies)** — Slicing a plain STL through the integrated slicer always defaulted to whatever `curr_bed_type` lived in the chosen process preset (typically `Cool Plate`), which the slicer CLI then rejected for high-temp filaments with `Plate 1: Cool Plate does not support filament 1`. The user had no way to switch plates short of cloning the process preset in BambuStudio, which defeats the point of the in-app slicer. The Slice modal now exposes a `Build plate` dropdown with the six canonical BambuStudio / OrcaSlicer plates (Cool Plate, Cool Plate SuperTack, Engineering Plate, High Temp Plate, Textured PEI Plate, Smooth PEI Plate) plus an explicit `Auto (use process preset)` option that preserves the previous behavior. The dropdown sits between Process profile and Filament rows so it stays visible regardless of how many filament slots the picked plate uses (a long filament list would otherwise push it off the modal's `max-h-[85vh]` scroll viewport) and is **always enabled** — including when the user picks a Printer Preset Bundle from the top BundlePicker. When the user picks a specific plate, the new `bed_type` field on `SliceRequest` ([`backend/app/schemas/slicer.py`](backend/app/schemas/slicer.py)) flows through the dispatcher via two paths: (1) **resolved-preset path** — the route helper `_patch_process_bed_type` in [`backend/app/api/routes/library.py`](backend/app/api/routes/library.py) overwrites `curr_bed_type` on the resolved process JSON before forwarding to the sidecar (no preset cloning required); (2) **bundle dispatch path** — `slice_with_bundle` in [`backend/app/services/slicer_api.py`](backend/app/services/slicer_api.py) adds a `bedType` form field to the sidecar multipart so the sidecar can pass `--curr_bed_type` through to the CLI, which lets the override take effect even though Bambuddy can't patch the bundle's process JSON locally (the sidecar materialises it from the stored .bbscfg). Sidecar versions that don't recognise the field silently no-op — the slice still runs, just with the bundle's default plate; the slicer-API fork at maziggy/orca-slicer-api will need the matching change for the bundle path to take full effect. **i18n parity:** 8 new keys (`slice.bedType.{label,auto,coolPlate,coolPlateSuperTack,engineering,highTemp,texturedPEI,smoothPEI}`) added to all 8 locales — full German translation, English fallbacks elsewhere per project convention. **Regression tests:** 4 in [`test_slice_request_bed_type.py`](backend/tests/unit/test_slice_request_bed_type.py) (`bed_type` defaults to None, accepts the six canonical strings, rejects overlong input via the schema's `max_length=64`; `_patch_process_bed_type` overwrites an existing value, adds the field when missing, and returns the input unchanged for malformed JSON or non-dict roots), 4 in [`test_library_slice_api.py`](backend/tests/integration/test_library_slice_api.py) (resolved-preset path: with `bed_type` set, the sidecar receives `"curr_bed_type": "Textured PEI Plate"` in the presetProfile multipart part; without it, `curr_bed_type` stays out of the body entirely. bundle dispatch path: `bedType` form field carries the override through to the sidecar; omitting `bed_type` keeps the form field out of the request so the bundle's own `curr_bed_type` is preserved), 2 in [`SliceModal.test.tsx`](frontend/src/__tests__/components/SliceModal.test.tsx) (dropdown selection puts `bed_type` on the request; leaving it on Auto omits the field). 59 backend slice tests + 34 SliceModal tests pass; build and i18n parity script clean. ### Fixed +- **Subtype dropdown on the Add/Edit Spool form now offers `CF` (carbon fiber) and `GF` (glass fiber)** ([#1345](https://github.com/maziggy/bambuddy/issues/1345), reported by @maziggy) — The Subtype dropdown in [`frontend/src/components/spool-form/FilamentSection.tsx`](frontend/src/components/spool-form/FilamentSection.tsx) is populated from the `KNOWN_VARIANTS` array in [`frontend/src/components/spool-form/constants.ts`](frontend/src/components/spool-form/constants.ts). `CF` and `GF` were missing, so a user adding a third-party PETG-CF spool via the Material=PETG + Subtype=CF flow (the same shape Bambu's "PETG HF" already used) couldn't find the subtype in the list and had to type it freehand into the "create new" tail. Added both — `CF` to match `PETG-CF` / `PLA-CF` / `ASA-CF` / `PA-CF`, and `GF` as the natural pair for `ABS-GF` / `PA6-GF`. `parsePresetName` in [`spool-form/utils.ts`](frontend/src/components/spool-form/utils.ts) is unaffected: its materials list is iterated longest-first, so a cloud preset like `Bambu PETG-CF Black` still resolves to material=`PETG-CF` with empty afterMaterial (the variant loop runs on `""` and finds nothing — no accidental Material=PETG / Subtype=CF rewrite). Frontend build clean. + - **Spool-assignment dialog stacks correctly: the material-mismatch confirmation appears above its parent, and dashboard filament hover popovers no longer get covered by sibling printer cards** ([#1336](https://github.com/maziggy/bambuddy/issues/1336) follow-up, mismatch case reported by @RosdasHH) — Two stacking-context regressions surfaced after the original z-50 → z-[100] bump on `AssignSpoolModal` landed. **(1) Material-mismatch ConfirmModal hidden behind its parent.** Assigning a spool with a different material to the one configured on the slot opens a yellow warning ConfirmModal from inside `AssignSpoolModal`. ConfirmModal's overlay was hardcoded to `z-50` in its wrapper at [`frontend/src/components/ConfirmModal.tsx`](frontend/src/components/ConfirmModal.tsx), so once the parent moved to `z-[100]` the child sat behind it — the user clicked Assign, saw the parent dim slightly, and nothing visible to confirm. Added an optional `overlayZIndex?: string` prop to `ConfirmModal` (defaults to `z-50` so all 82 other call sites are untouched), and the mismatch site at [`AssignSpoolModal.tsx:584`](frontend/src/components/AssignSpoolModal.tsx) passes `overlayZIndex="z-[110]"` so the warning sits above its parent. **(2) `FilamentHoverCard` / `EmptySlotHoverCard` covered by neighbouring printer cards.** Hovering an AMS slot on the dashboard opens a "Jade White · Bambu PETG HF · K Factor 0.024 · 87% · Open in Inventory / Configure" popover. The popover was using `position: absolute` with `z-[60]` inside its trigger — but each printer card on the dashboard creates its own stacking context (any `filter: drop-shadow` / `transform` / positioned-with-z descendant is enough), and `z-index` does not cross stacking-context boundaries: the next card in DOM order always wins regardless of how high the inner z-index goes. Visible as a "Jade White" tooltip getting half-eaten by the AMS-C tile column on the right neighbour card. Fixed by **portaling both hover cards to `document.body`** ([`FilamentHoverCard.tsx`](frontend/src/components/FilamentHoverCard.tsx) via `createPortal` from `react-dom`) with `position: fixed` and screen-space coordinates computed from `triggerRef.current.getBoundingClientRect()`. Coords are recomputed on visibility change, on `scroll` (capture phase) and on `resize` so the popover tracks the trigger when the viewport moves; a `requestAnimationFrame` re-measure after the initial paint avoids a one-frame flicker before the card has its rendered dimensions. Hover handlers wired on both the trigger AND the portaled card so moving the cursor from the slot tile onto the popover doesn't auto-dismiss it after 100 ms. The smart top/bottom placement logic (flips to below the trigger when there's not enough headroom above the fixed 56 px header) is preserved, as is the arrow pointer that points back at the slot. `z-[60]` stays — but it's now global because the popover lives at the root of the DOM, so it always beats dashboard widgets without conflicting with full-screen modals at `z-[100]`. All 20 `FilamentHoverCard`, 17 `ConfirmModal`, and 13 `AssignSpoolModal` tests pass; frontend build clean. - **Deleting a print archive no longer wipes its filament / time / cost / energy contribution from Quick Stats** ([#1343](https://github.com/maziggy/bambuddy/issues/1343), reported by @IndividualGhost1905) — Running the same model ten times and then deleting nine of the resulting archive entries (to keep the file list tidy) silently rewound the totals on the Statistics page: `total_prints`, `total_filament_grams`, `total_cost`, and per-print energy all dropped back to whatever the surviving archive contributed, as if the other nine prints had never happened. Root cause: every metric in `get_archive_stats` at [`backend/app/api/routes/archives.py`](backend/app/api/routes/archives.py) is recomputed on each render via `COUNT` / `SUM` over the live `PrintArchive` rows, so removing a row removes its contribution. (Energy in the default "Total" mode already survived archive deletion because it reads the smart-plug lifetime counters via `_sum_live_plug_totals` — that's the architectural shape we now generalise to the rest of the metrics.) **Fix: soft delete with opt-in hard purge.** New nullable `deleted_at` column on `print_archives` ([`backend/app/models/archive.py`](backend/app/models/archive.py)) tracks rows the user removed from the UI. The DELETE endpoint at [`backend/app/api/routes/archives.py`](backend/app/api/routes/archives.py) now accepts `?purge_stats=true`; **default** behaviour is to soft-delete — files removed from disk (still frees the storage), row hidden from listings, but the row stays in the table so the stats endpoint keeps counting it. Setting `?purge_stats=true` falls back to the original hard-delete path for the rare case where the user actually wants the row out of Quick Stats too (e.g. failed prints that shouldn't pollute success-rate dashboards). The migration in [`backend/app/core/database.py`](backend/app/core/database.py) adds the column dialect-conditionally — `DATETIME` on SQLite, `TIMESTAMP` on PostgreSQL (PG doesn't accept `DATETIME` on `ALTER TABLE` the way it tolerates it inside `CREATE TABLE`) — plus an index on `deleted_at` so the `WHERE deleted_at IS NULL` filter that's now sprinkled across the listing queries stays cheap on big archive tables. **Service-layer changes.** `ArchiveService.soft_delete_archive` is a new sibling of `delete_archive` that reuses the existing on-disk path-safety checks (extracted into `_resolve_archive_dir_for_delete` so soft and hard delete share the resolution rules — refuses paths outside `archive_dir`, refuses depth-zero paths) and flips `deleted_at = now()` after `shutil.rmtree`. Listing methods now filter `PrintArchive.deleted_at.is_(None)`: `ArchiveService.list_archives`, `get_duplicate_hashes_and_names` (a soft-deleted dupe must not inflate a group's count so the UI shows "1 of 1" instead of "1 of 10"), `find_duplicates` (both the exact-hash and the print-name paths), and `ArchiveComparisonService.find_similar_archives` (both name-match and content-hash paths so the "Similar archives" panel doesn't suggest something the user just removed). The stats endpoint deliberately keeps NO filter — the whole point of #1343. Route-level reads tightened too: `GET /archives/{id}` returns 404 on soft-deleted rows so stale bookmarks don't expose hidden archives, search (both the SQLite FTS5 path and the LIKE fallback) skips them, the duplicate-group enrichment query in `list_archives` filters them, and tag listing / archives-by-tag exclude them. `GET /archives/slim` and `GET /archives/stats/export` intentionally do NOT filter so the dashboard widgets in `StatsPage.tsx` keep aggregating across the full history. **Frontend.** `ConfirmModal` gained an optional `children` slot (`frontend/src/components/ConfirmModal.tsx`) so the delete-confirmation dialog can render an opt-in checkbox between the message and the action buttons without forcing a new bespoke modal. [`frontend/src/pages/ArchivesPage.tsx`](frontend/src/pages/ArchivesPage.tsx) — both the card view and the detail view — now own a `deletePurgeStats` boolean per component instance and pass it through to `api.deleteArchive(id, purgeStats)` ([`frontend/src/api/client.ts`](frontend/src/api/client.ts) appends `?purge_stats=true` only when the box is ticked). The checkbox resets to off on every modal close so the destructive option is opt-in *per delete*, never sticky. **i18n:** one new key `archives.modal.deletePurgeStats` added across all 8 locales — full German translation, English fallbacks elsewhere per project convention. **Tests** added to [`backend/tests/integration/test_archives_api.py`](backend/tests/integration/test_archives_api.py): soft delete preserves the row's contribution to total prints / filament / cost (the regression test for the reporter's exact scenario), `?purge_stats=true` drops it from Quick Stats as before, soft-deleted archives 404 on `GET /archives/{id}`, soft-deleted archives are skipped by the search endpoint. All 42 pre-existing archive integration tests stay green, including `test_delete_archive` (which already asserts post-delete 404 — semantically equivalent under soft delete). Frontend `ConfirmModal` (17 tests) and `ArchivesPage` (23 tests) suites green, full build clean. diff --git a/frontend/src/components/spool-form/constants.ts b/frontend/src/components/spool-form/constants.ts index 41b282c2c..788354552 100644 --- a/frontend/src/components/spool-form/constants.ts +++ b/frontend/src/components/spool-form/constants.ts @@ -18,6 +18,11 @@ export const DEFAULT_BRANDS = [ // Known filament variants/subtypes export const KNOWN_VARIANTS = [ 'Basic', 'Matte', 'Silk', 'Silk+', 'Tough', 'Tough+', 'HF', 'High Flow', 'Engineering', + // CF (Carbon Fiber) / GF (Glass Fiber) — match Bambu's PETG-CF / PA6-GF / + // ABS-GF naming so users adding a third-party CF/GF spool can pick the + // base material + subtype here instead of needing a -CF Material entry + // (#1345). + 'CF', 'GF', 'Galaxy', 'Glow', 'Marble', 'Metal', 'Rainbow', 'Sparkle', 'Wood', 'Translucent', 'Transparent', 'Clear', 'Lite', 'Pro', 'Plus', 'Max', 'Super', 'Ultra', 'Flex', 'Soft', 'Hard', 'Strong', 'Impact', diff --git a/static/assets/index-BxdzCdot.js b/static/assets/index-B7LxDq2k.js similarity index 98% rename from static/assets/index-BxdzCdot.js rename to static/assets/index-B7LxDq2k.js index dee9a76fd..739491da9 100644 --- a/static/assets/index-BxdzCdot.js +++ b/static/assets/index-B7LxDq2k.js @@ -8715,7 +8715,7 @@ Accuracy: ${t.time_accuracy.toFixed(0)}%`:t.actual_time_seconds?`Actual: ${ds(t. `+a.map(([s,o])=>n+" "+JSON.stringify(s)+": "+KI(o,e+1)).join(`, `)+` `+n+"}"}return String(t)}function Lat({setting:t,onClose:e,onDeleted:n,onDuplicate:a,onEdit:i,hasPermission:s,t:o}){const{showToast:l}=rn(),c=en(),[d,u]=y.useState(!1),{data:m,isLoading:p}=Ge({queryKey:["cloudSettingDetail",t.setting_id],queryFn:()=>ie.getCloudSettingDetail(t.setting_id)}),f=it({mutationFn:()=>ie.deleteCloudSetting(t.setting_id),onSuccess:()=>{l(o("profiles.presets.toast.deleted")),c.invalidateQueries({queryKey:["cloudSettings"]}),n()},onError:b=>l(b.message,"error")}),g=vS(t.setting_id),w=aU(t.name,m?.setting?.inherits);return r.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:r.jsx(Ct,{className:"w-full max-w-3xl max-h-[90vh] flex flex-col overflow-hidden",children:r.jsxs(At,{className:"p-0 flex flex-col min-h-0 flex-1",children:[r.jsxs("div",{className:"flex-shrink-0 flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("h2",{className:"text-xl font-semibold text-white truncate",children:t.name}),g&&r.jsx("span",{className:"px-2 py-0.5 text-xs font-medium bg-bambu-green/20 text-bambu-green rounded-full",children:o("profiles.presets.editable")})]}),r.jsxs("div",{className:"flex items-center gap-2 mt-1 text-sm text-bambu-gray",children:[r.jsx("span",{className:"capitalize",children:o(`profiles.presets.types.${t.type}`)}),w.printer&&r.jsxs(r.Fragment,{children:[r.jsx("span",{children:"•"}),r.jsx("span",{children:w.printer})]})]})]}),r.jsx("button",{onClick:e,className:"p-2 text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary rounded-lg transition-colors",children:r.jsx(Ht,{className:"w-5 h-5"})})]}),r.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto p-4",children:p?r.jsx("div",{className:"flex items-center justify-center py-16",children:r.jsx(pt,{className:"w-8 h-8 text-bambu-green animate-spin"})}):m?r.jsx("pre",{className:"text-xs text-bambu-gray font-mono whitespace-pre-wrap break-all bg-bambu-dark p-4 rounded-lg border border-bambu-dark-tertiary overflow-x-auto max-w-full",children:KI(m)}):r.jsx("div",{className:"text-center py-16 text-bambu-gray",children:o("profiles.presets.failedToLoadDetails")})}),d?r.jsxs("div",{className:"flex-shrink-0 p-4 border-t border-bambu-dark-tertiary bg-red-500/5",children:[r.jsxs("div",{className:"flex items-center gap-2 mb-3 text-red-400",children:[r.jsx(Nn,{className:"w-5 h-5"}),r.jsx("span",{className:"font-medium",children:o("profiles.presets.deleteConfirm")})]}),r.jsx("p",{className:"text-sm text-bambu-gray mb-4",children:o("profiles.presets.deleteWarning",{name:t.name})}),r.jsxs("div",{className:"flex gap-2",children:[r.jsx(Me,{variant:"secondary",onClick:()=>u(!1),disabled:f.isPending,className:"flex-1",children:o("common.cancel")}),r.jsxs(Me,{variant:"danger",onClick:()=>f.mutate(),disabled:f.isPending,className:"flex-1",children:[f.isPending?r.jsx(pt,{className:"w-4 h-4 animate-spin"}):r.jsx(Jt,{className:"w-4 h-4"}),o("common.delete")]})]})]}):r.jsx("div",{className:"flex-shrink-0 p-4 border-t border-bambu-dark-tertiary",children:r.jsxs("div",{className:"flex gap-2",children:[r.jsx(Me,{variant:"secondary",onClick:e,className:"flex-1",children:o("common.close")}),r.jsxs(Me,{variant:"secondary",onClick:a,disabled:!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.presets.noDuplicatePermission"),children:[r.jsx(Mi,{className:"w-4 h-4"}),o("profiles.presets.duplicate")]}),g&&r.jsxs(r.Fragment,{children:[r.jsxs(Me,{variant:"secondary",onClick:i,disabled:p||!m||!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.presets.noEditPermission"),children:[r.jsx(oi,{className:"w-4 h-4"}),o("common.edit")]}),r.jsx(Me,{variant:"danger",onClick:()=>u(!0),disabled:!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.presets.noDeletePermission"),children:r.jsx(Jt,{className:"w-4 h-4"})})]})]})})]})})})}function Ece(){try{const t=localStorage.getItem("bambusy_preset_templates");return t?JSON.parse(t):[]}catch{return[]}}function Dce(t){localStorage.setItem("bambusy_preset_templates",JSON.stringify(t))}function Iat({onClose:t,onApply:e,t:n}){const{showToast:a}=rn(),[i,s]=y.useState(Ece),[o,l]=y.useState("all"),[c,d]=y.useState(null),[u,m]=y.useState(""),[p,f]=y.useState(""),[g,w]=y.useState("{}"),[b,x]=y.useState(null),[S,N]=y.useState(null),C=o==="all"?i:i.filter(U=>U.type===o),P=U=>{s(U),Dce(U)},T=U=>{const L=i.filter(Q=>Q.id!==U);P(L),N(null),a(n("profiles.templates.toast.deleted"))},A=U=>{d(U.id),m(U.name),f(U.description),w(JSON.stringify(U.settings,null,2)),x(null)},F=()=>{if(!(!c||!u.trim()))try{const U=JSON.parse(g),L=i.map(Q=>Q.id===c?{...Q,name:u.trim(),description:p.trim(),settings:U}:Q);P(L),d(null),a(n("profiles.templates.toast.updated"))}catch(U){x(U.message)}},_=()=>{d(null),m(""),f(""),w("{}"),x(null)},E=U=>{const L=i.map(Q=>Q.id===U?{...Q,showInModal:!Q.showInModal}:Q);P(L)},H={filament:{label:n("profiles.presets.types.filament"),icon:ST,color:"text-amber-400"},print:{label:n("profiles.presets.types.process"),icon:uu,color:"text-blue-400"},printer:{label:n("profiles.presets.types.printer"),icon:pr,color:"text-purple-400"}},I=S?i.find(U=>U.id===S):null;return y.useEffect(()=>{const U=L=>{L.key==="Escape"&&(S?N(null):c?_():t())};return window.addEventListener("keydown",U),()=>window.removeEventListener("keydown",U)},[S,c,t]),r.jsxs("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:[I&&r.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-60",children:r.jsx(Ct,{className:"w-full max-w-md",children:r.jsxs(At,{className:"p-6",children:[r.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[r.jsx("div",{className:"p-2 bg-red-500/20 rounded-lg",children:r.jsx(Nn,{className:"w-6 h-6 text-red-400"})}),r.jsxs("div",{children:[r.jsx("h3",{className:"text-lg font-semibold text-white",children:n("profiles.templates.deleteTitle")}),r.jsx("p",{className:"text-sm text-bambu-gray",children:n("profiles.templates.deleteWarning")})]})]}),r.jsx("p",{className:"text-white mb-6",children:n("profiles.templates.deleteConfirm",{name:I.name})}),r.jsxs("div",{className:"flex gap-2",children:[r.jsx(Me,{variant:"secondary",onClick:()=>N(null),className:"flex-1",children:n("common.cancel")}),r.jsxs(Me,{onClick:()=>T(S),className:"flex-1 bg-red-500 hover:bg-red-600",children:[r.jsx(Jt,{className:"w-4 h-4"}),n("common.delete")]})]})]})})}),r.jsx(Ct,{className:"w-full max-w-2xl max-h-[80vh] flex flex-col",children:r.jsxs(At,{className:"p-0 flex flex-col h-full",children:[r.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[r.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[r.jsx(Dg,{className:"w-5 h-5 text-amber-400"}),n("profiles.templates.title")]}),r.jsx("button",{onClick:t,className:"text-bambu-gray hover:text-white",children:r.jsx(Ht,{className:"w-5 h-5"})})]}),r.jsxs("div",{className:"flex items-center gap-2 p-4 border-b border-bambu-dark-tertiary",children:[r.jsx("span",{className:"text-sm text-bambu-gray",children:n("profiles.templates.typeFilter")}),["all","filament","print","printer"].map(U=>r.jsx("button",{onClick:()=>l(U),className:`px-3 py-1 text-sm rounded-lg transition-colors ${o===U?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:U==="all"?n("common.all"):H[U].label},U))]}),r.jsx("div",{className:"flex-1 overflow-y-auto p-4",children:C.length===0?r.jsxs("div",{className:"text-center py-12 text-bambu-gray",children:[r.jsx(Dg,{className:"w-12 h-12 mx-auto mb-4 opacity-30"}),r.jsx("p",{children:n("profiles.templates.noTemplates")}),r.jsx("p",{className:"text-sm mt-1",children:n("profiles.templates.createFirst")})]}):r.jsx("div",{className:"space-y-2",children:C.map(U=>{const L=H[U.type],Q=L.icon;return c===U.id?r.jsxs("div",{className:"p-4 bg-bambu-dark rounded-lg border border-bambu-green",children:[r.jsxs("div",{className:"grid grid-cols-2 gap-3 mb-3",children:[r.jsx("input",{type:"text",value:u,onChange:re=>m(re.target.value),placeholder:n("profiles.templates.namePlaceholder"),className:"px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none",autoFocus:!0}),r.jsx("input",{type:"text",value:p,onChange:re=>f(re.target.value),placeholder:n("profiles.templates.descriptionPlaceholder"),className:"px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none"})]}),r.jsxs("div",{className:"mb-3",children:[r.jsx("label",{className:"text-xs text-bambu-gray mb-1 block",children:n("profiles.templates.settingsJson")}),r.jsx("textarea",{value:g,onChange:re=>{w(re.target.value),x(null)},rows:6,className:`w-full px-3 py-2 bg-bambu-dark-secondary border rounded text-white text-sm font-mono focus:outline-none ${b?"border-red-500":"border-bambu-dark-tertiary focus:border-bambu-green"}`}),b&&r.jsx("p",{className:"text-xs text-red-400 mt-1",children:b})]}),r.jsxs("div",{className:"flex gap-2",children:[r.jsxs(Me,{size:"sm",onClick:F,disabled:!u.trim(),children:[r.jsx(us,{className:"w-4 h-4"}),"Save"]}),r.jsx(Me,{size:"sm",variant:"secondary",onClick:_,children:"Cancel"})]})]},U.id):r.jsxs("div",{className:"flex items-center gap-3 p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary hover:border-bambu-gray-dark transition-colors",children:[r.jsx(Q,{className:`w-5 h-5 ${L.color} flex-shrink-0`}),r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsx("p",{className:"text-sm font-medium text-white",children:U.name}),r.jsx("p",{className:"text-xs text-bambu-gray truncate",children:U.description})]}),r.jsx("span",{className:"text-xs text-bambu-gray-dark px-2 py-1 bg-bambu-dark-secondary rounded",children:n("profiles.templates.fieldsCount",{count:Object.keys(U.settings).length})}),r.jsx("button",{onClick:()=>E(U.id),className:`p-1 transition-colors ${U.showInModal?"text-bambu-green hover:text-bambu-green/70":"text-bambu-gray hover:text-white"}`,title:U.showInModal?n("profiles.templates.shownInModals"):n("profiles.templates.hiddenInModals"),children:U.showInModal?r.jsx(Dl,{className:"w-4 h-4"}):r.jsx(sb,{className:"w-4 h-4"})}),r.jsx("button",{onClick:()=>e(U),className:"px-3 py-1 text-xs bg-bambu-green/20 text-bambu-green rounded hover:bg-bambu-green/30 transition-colors",children:n("profiles.templates.apply")}),r.jsx("button",{onClick:()=>A(U),className:"p-1 text-bambu-gray hover:text-white",title:n("common.edit"),children:r.jsx(oi,{className:"w-4 h-4"})}),r.jsx("button",{onClick:()=>N(U.id),className:"p-1 text-bambu-gray hover:text-red-400",title:n("common.delete"),children:r.jsx(Jt,{className:"w-4 h-4"})})]},U.id)})})})]})})]})}function Fce({onClose:t,leftPreset:e,rightPreset:n,leftLabel:a,rightLabel:i,t:s}){const[o,l]=y.useState("changes"),[c,d]=y.useState(""),u=y.useMemo(()=>{const g=new Set([...Object.keys(e),...Object.keys(n)]),w=[];for(const b of g){if(b==="inherits"||b==="version")continue;const x=e[b],S=n[b],N=b in e,C=b in n;let P;!N&&C?P="added":N&&!C?P="removed":JSON.stringify(x)!==JSON.stringify(S)?P="changed":P="same",w.push({key:b,left:x,right:S,status:P})}return w.sort((b,x)=>{const S={changed:0,added:1,removed:2,same:3};return S[b.status]!==S[x.status]?S[b.status]-S[x.status]:b.key.localeCompare(x.key)})},[e,n]),m=y.useMemo(()=>{let g=[...u];if(o==="changes"&&(g=g.filter(w=>w.status!=="same")),c){const w=c.toLowerCase();g=g.filter(b=>b.key.toLowerCase().includes(w)||String(b.left).toLowerCase().includes(w)||String(b.right).toLowerCase().includes(w))}return g},[u,o,c]),p=y.useMemo(()=>({added:u.filter(g=>g.status==="added").length,removed:u.filter(g=>g.status==="removed").length,changed:u.filter(g=>g.status==="changed").length,same:u.filter(g=>g.status==="same").length}),[u]),f=g=>{if(g===void 0)return"—";if(g===null)return"null";if(Array.isArray(g))return g.length===0?"[]":g.length===1?String(g[0]):g.join(", ");if(typeof g=="object")return JSON.stringify(g);const w=String(g);if(w.includes("\\n")||w.length>100){const b=w.split("\\n").length;if(b>1)return`[${b} lines of G-code/script]`;if(w.length>100)return w.substring(0,100)+"…"}return w};return y.useEffect(()=>{const g=w=>{w.key==="Escape"&&t()};return window.addEventListener("keydown",g),()=>window.removeEventListener("keydown",g)},[t]),r.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:r.jsx(Ct,{className:"w-full max-w-4xl max-h-[85vh] flex flex-col overflow-hidden",children:r.jsxs(At,{className:"p-0 flex flex-col min-h-0 flex-1",children:[r.jsxs("div",{className:"flex-shrink-0 flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[r.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[r.jsx(Zx,{className:"w-5 h-5 text-blue-400"}),s("profiles.diff.title")]}),r.jsx("button",{onClick:t,className:"text-bambu-gray hover:text-white",children:r.jsx(Ht,{className:"w-5 h-5"})})]}),r.jsxs("div",{className:"flex-shrink-0 grid grid-cols-2 gap-4 p-4 border-b border-bambu-dark-tertiary bg-bambu-dark",children:[r.jsxs("div",{className:"text-center",children:[r.jsx("span",{className:"text-sm text-bambu-gray",children:s("profiles.diff.left")}),r.jsx("p",{className:"text-white font-medium truncate",children:a})]}),r.jsxs("div",{className:"text-center",children:[r.jsx("span",{className:"text-sm text-bambu-gray",children:s("profiles.diff.right")}),r.jsx("p",{className:"text-white font-medium truncate",children:i})]})]}),r.jsxs("div",{className:"flex-shrink-0 flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"flex items-center gap-4 text-sm",children:[r.jsxs("span",{className:"flex items-center gap-1 text-green-400",children:[r.jsx(ir,{className:"w-3.5 h-3.5"}),p.added," ",s("profiles.diff.added")]}),r.jsxs("span",{className:"flex items-center gap-1 text-red-400",children:[r.jsx(tC,{className:"w-3.5 h-3.5"}),p.removed," ",s("profiles.diff.removed")]}),r.jsxs("span",{className:"flex items-center gap-1 text-amber-400",children:[r.jsx(XN,{className:"w-3.5 h-3.5"}),p.changed," ",s("profiles.diff.changed")]}),r.jsxs("span",{className:"flex items-center gap-1 text-bambu-gray",children:[r.jsx(sE,{className:"w-3.5 h-3.5"}),p.same," ",s("profiles.diff.same")]})]}),r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsxs("div",{className:"relative",children:[r.jsx(Sr,{className:"absolute left-2 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),r.jsx("input",{type:"text",value:c,onChange:g=>d(g.target.value),placeholder:s("profiles.diff.searchFields"),className:"pl-8 pr-3 py-1.5 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none w-48"})]}),p.same>0&&r.jsxs("div",{className:"flex rounded overflow-hidden border border-bambu-dark-tertiary",children:[r.jsx("button",{onClick:()=>l("changes"),className:`px-3 py-1.5 text-sm transition-colors ${o==="changes"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:s("profiles.diff.changes")}),r.jsx("button",{onClick:()=>l("all"),className:`px-3 py-1.5 text-sm transition-colors ${o==="all"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:s("common.all")})]})]})]}),r.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto",children:m.length===0?r.jsxs("div",{className:"text-center py-12 text-bambu-gray",children:[r.jsx(sE,{className:"w-12 h-12 mx-auto mb-4 opacity-30"}),r.jsx("p",{children:s(o==="changes"?"profiles.diff.noDifferences":"profiles.diff.noFieldsMatch")})]}):r.jsxs("table",{className:"w-full",children:[r.jsx("thead",{className:"sticky top-0 bg-bambu-dark-secondary",children:r.jsxs("tr",{className:"text-sm text-bambu-gray border-b border-bambu-dark-tertiary",children:[r.jsx("th",{className:"text-left p-3 w-1/3",children:s("profiles.diff.field")}),r.jsx("th",{className:"text-left p-3 w-1/3",children:a}),r.jsx("th",{className:"text-left p-3 w-1/3",children:i})]})}),r.jsx("tbody",{children:m.map(g=>{const w={added:"bg-green-500/10",removed:"bg-red-500/10",changed:"bg-amber-500/10",same:""}[g.status],b={added:r.jsx(ir,{className:"w-3.5 h-3.5 text-green-400"}),removed:r.jsx(tC,{className:"w-3.5 h-3.5 text-red-400"}),changed:r.jsx(XN,{className:"w-3.5 h-3.5 text-amber-400"}),same:r.jsx(sE,{className:"w-3.5 h-3.5 text-bambu-gray-dark"})}[g.status];return r.jsxs("tr",{className:`border-b border-bambu-dark-tertiary ${w}`,children:[r.jsx("td",{className:"p-3",children:r.jsxs("div",{className:"flex items-center gap-2",children:[b,r.jsx("span",{className:"text-sm text-white font-mono",children:g.key})]})}),r.jsx("td",{className:"p-3",children:r.jsx("span",{className:`text-sm font-mono break-all ${g.status==="removed"?"text-red-300":g.status==="changed"?"text-white":"text-bambu-gray"}`,children:f(g.left)})}),r.jsx("td",{className:"p-3",children:r.jsx("span",{className:`text-sm font-mono break-all ${g.status==="added"?"text-green-300":g.status==="changed"?"text-white":"text-bambu-gray"}`,children:f(g.right)})})]},g.key)})})]})})]})})})}function Oat({onClose:t,initialData:e,allPresets:n,t:a}){const{showToast:i}=rn(),s=en(),o=!!e?.setting_id,[l,c]=y.useState("common"),[d,u]=y.useState(e?.type||"filament"),[m,p]=y.useState(e?.name?o?e.name:`${e.name} (Copy)`:""),[f,g]=y.useState(e?.base_id||""),[w,b]=y.useState(""),[x,S]=y.useState(e?.setting||{inherits:""}),[N,C]=y.useState(JSON.stringify(e?.setting||{inherits:""},null,2)),[P,T]=y.useState(null),[A,F]=y.useState(""),[_,E]=y.useState(!1),[H,I]=y.useState(""),[U,L]=y.useState(!1),[Q,re]=y.useState(Ece),[J,ce]=y.useState(!1),[pe,ue]=y.useState(""),[X,ae]=y.useState(""),[me,ge]=y.useState(!0),[Pe,$]=y.useState(null),[W,D]=y.useState(!1),j=y.useMemo(()=>({filament:n.filament,print:n.process,printer:n.printer})[d]||[],[n,d]),B=y.useMemo(()=>j.filter(Se=>vS(Se.setting_id)),[j]),{data:Y}=Ge({queryKey:["cloudFields",d],queryFn:()=>ie.getCloudFields(d==="print"?"process":d),staleTime:1e3*60*60}),{data:O}=Ge({queryKey:["allPresetDetails",d,B.map(Se=>Se.setting_id).join(",")],queryFn:async()=>{const Se={};for(let rt=0;rt{try{const Ne=await ie.getCloudSettingDetail(nt.setting_id);return{id:nt.setting_id,detail:Ne}}catch{return null}}))).forEach(nt=>{nt&&(Se[nt.id]=nt.detail)})}return Se},enabled:B.length>0,staleTime:1e3*60*10}),{data:se,isLoading:z}=Ge({queryKey:["cloudSettingDetail",f],queryFn:()=>ie.getCloudSettingDetail(f),enabled:!!f});y.useEffect(()=>{l!=="json"&&C(JSON.stringify(x,null,2))},[x,l]);const G=y.useMemo(()=>({filament:n.filament,print:n.process,printer:n.printer}[d]||[]).filter($e=>!vS($e.setting_id)).sort(($e,rt)=>$e.name.localeCompare(rt.name)),[n,d]);y.useEffect(()=>{if(!f)return;const Se=G.find($e=>$e.setting_id===f);Se&&(b(Se.name),o||(S({inherits:Se.name}),C(JSON.stringify({inherits:Se.name},null,2))))},[f,G,o]);const K=y.useMemo(()=>{const Se=Y?.fields||[],$e=new Set(Se.map(nt=>nt.key)),rt=new Set,ot=new Set(["inherits","updated_time","compatible_printers","compatible_prints"]);O&&Object.values(O).forEach(nt=>{nt?.setting&&Object.keys(nt.setting).forEach(Ne=>{!$e.has(Ne)&&!ot.has(Ne)&&rt.add(Ne)})}),Object.keys(x).forEach(nt=>{!$e.has(nt)&&!ot.has(nt)&&rt.add(nt)});const Le=Array.from(rt).sort().map(nt=>({key:nt,label:nt.replace(/_/g," ").replace(/\b\w/g,Ne=>Ne.toUpperCase()),type:"text",category:"discovered",description:a("profiles.presets.discoveredFromPresets")}));return[...Se,...Le]},[Y,O,x,a]),Z=K.filter(Se=>Se.label.toLowerCase().includes(A.toLowerCase())||Se.key.toLowerCase().includes(A.toLowerCase())),oe=()=>{if(H.trim()){const Se=H.trim().toLowerCase().replace(/\s+/g,"_");ee(Se,""),I(""),L(!1),i(a("profiles.presets.toast.fieldAdded",{key:Se}))}},ee=(Se,$e)=>{S(rt=>{const ot={...rt};return $e===""||$e===void 0?delete ot[Se]:ot[Se]=$e,ot})},fe=Se=>{S($e=>({...$e,...Se.settings})),$(Se.name),i(a("profiles.templates.toast.applied"))},de=()=>{if(!pe.trim())return;const Se={...x};if(delete Se.inherits,Object.keys(Se).length===0){i(a("profiles.presets.noOverridesToSave"),"error");return}const $e={id:Date.now().toString(),name:pe.trim(),description:X.trim()||a("profiles.presets.customTemplate"),type:d,settings:Se,showInModal:me},rt=[...Q,$e];re(rt),Dce(rt),ce(!1),ue(""),ae(""),ge(!0),i(a("profiles.templates.toast.created"))},le=y.useMemo(()=>Q.filter(Se=>Se.type===d&&Se.showInModal),[d,Q]),q=Se=>{C(Se);try{const $e=JSON.parse(Se);S($e),T(null)}catch($e){T($e.message)}},R=Se=>{Se.preventDefault(),E(!1);const $e=Se.dataTransfer.files[0];if($e&&$e.name.endsWith(".json")){const rt=new FileReader;rt.onload=ot=>{try{const Le=ot.target?.result,nt=JSON.parse(Le),Ne=nt.setting||nt;S(Qe=>({...Qe,...Ne})),C(JSON.stringify({...x,...Ne},null,2)),i(a("profiles.presets.fileImported"))}catch{i(a("profiles.presets.invalidJsonFile"),"error")}},rt.readAsText($e)}},ne=it({mutationFn:()=>{const Se={...x},$e=d==="filament"?"filament_settings_id":d==="print"?"print_settings_id":"printer_settings_id";Se[$e]=`"${m}"`;const rt={type:d,name:m,base_id:f,setting:Se};return ie.createCloudSetting(rt)},onSuccess:async()=>{i(a("profiles.presets.toast.created")),await s.refetchQueries({queryKey:["cloudSettings"]}),t()},onError:Se=>i(Se.message,"error")}),xe=it({mutationFn:()=>{if(!e?.setting_id)throw new Error(a("profiles.presets.noSettingId"));return ie.updateCloudSetting(e.setting_id,{name:m,setting:x})},onSuccess:async()=>{i(a("profiles.presets.toast.updated")),s.removeQueries({queryKey:["cloudSettingDetail"]}),await s.refetchQueries({queryKey:["cloudSettings"]}),t()},onError:Se=>i(Se.message,"error")}),ve=o?xe:ne,Ce=se?.setting?.inherits,ye=Ce?G.find(Se=>Se.name===Ce):void 0,{data:be}=Ge({queryKey:["cloudSettingDetail",ye?.setting_id],queryFn:()=>ie.getCloudSettingDetail(ye.setting_id),enabled:!!ye?.setting_id}),Ee=y.useMemo(()=>{const Se=be?.setting||{},$e=se?.setting||{},rt=f&&O?.[f]?.setting?O[f].setting:{};return{...Se,...$e,...rt}},[f,se,be,O]),ze=Se=>{if(Se==null)return"";if(Array.isArray(Se)){const $e=[...new Set(Se.map(rt=>String(rt)))];return $e.length===1?$e[0]:Se.join(", ")}return String(Se)},Oe=Se=>{const $e=x[Se.key],rt=Ee[Se.key],ot=ze(rt),Le=z?a("common.loading"):ot||"",nt="w-full px-3 py-1.5 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none";if(Se.type==="boolean"){const Ne=$e==="1"||$e===void 0&&rt==="1";return r.jsx("button",{type:"button",onClick:()=>ee(Se.key,$e==="1"?"0":"1"),className:`w-8 h-5 rounded-full transition-colors ${Ne?"bg-bambu-green":"bg-bambu-dark-tertiary"}`,children:r.jsx("div",{className:`w-4 h-4 rounded-full bg-white shadow transition-transform ${Ne?"translate-x-3.5":"translate-x-0.5"}`})})}return Se.type==="select"?r.jsxs("select",{value:$e||"",onChange:Ne=>ee(Se.key,Ne.target.value),className:nt,children:[r.jsx("option",{value:"",children:Le}),Se.options?.map(Ne=>r.jsx("option",{value:Ne.value,children:Ne.label},Ne.value))]}):r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("input",{type:Se.type==="number"?"number":"text",value:$e!==void 0?String($e):"",onChange:Ne=>ee(Se.key,Ne.target.value),step:Se.step,min:Se.min,max:Se.max,placeholder:Le,className:nt}),Se.unit&&r.jsx("span",{className:"text-xs text-bambu-gray whitespace-nowrap",children:Se.unit})]})},Be=y.useMemo(()=>se?.setting?se.setting:{},[se]);return r.jsxs("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",onDragOver:Se=>{Se.preventDefault(),E(!0)},onDragLeave:()=>E(!1),onDrop:R,children:[W&&f&&r.jsx(Fce,{onClose:()=>D(!1),leftPreset:Be,rightPreset:x,leftLabel:a("profiles.presets.baseLabel",{name:w||f}),rightLabel:a("profiles.presets.currentLabel",{name:m||a("profiles.presets.newPreset")}),t:a}),r.jsx(Ct,{className:"w-full max-w-6xl max-h-[90vh] flex flex-col overflow-y-auto",children:r.jsxs(At,{className:"p-0 flex flex-col h-full",children:[r.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[r.jsxs("div",{children:[r.jsx("h2",{className:"text-xl font-semibold text-white",children:a(o?"profiles.presets.editPreset":e?"profiles.presets.duplicatePreset":"profiles.presets.createNewPreset")}),r.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:a("profiles.presets.customizeSettings")})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[f&&r.jsxs("button",{onClick:()=>D(!0),className:"flex items-center gap-2 px-3 py-2 text-sm text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary rounded-lg transition-colors",title:a("profiles.presets.compareWithBase"),children:[r.jsx(Zx,{className:"w-4 h-4"}),a("profiles.presets.compare")]}),r.jsx("button",{onClick:t,className:"p-2 text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary rounded-lg transition-colors",children:r.jsx(Ht,{className:"w-5 h-5"})})]})]}),_&&r.jsx("div",{className:"absolute inset-0 bg-bambu-green/10 border-2 border-dashed border-bambu-green rounded-lg flex items-center justify-center z-10",children:r.jsxs("div",{className:"text-center",children:[r.jsx(ka,{className:"w-12 h-12 text-bambu-green mx-auto mb-2"}),r.jsx("p",{className:"text-bambu-green font-medium",children:a("profiles.presets.dropJsonToImport")})]})}),r.jsxs("div",{className:"p-4 border-b border-bambu-dark-tertiary space-y-3",children:[r.jsxs("div",{className:"grid grid-cols-3 gap-4 max-[640px]:grid-cols-1",children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("common.type")}),r.jsxs("select",{value:d,onChange:Se=>{u(Se.target.value),g("")},className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[r.jsx("option",{value:"filament",children:a("profiles.presets.types.filament")}),r.jsx("option",{value:"print",children:a("profiles.presets.types.process")}),r.jsx("option",{value:"printer",children:a("profiles.presets.types.printer")})]})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("profiles.presets.basePreset")}),r.jsxs("select",{value:f,onChange:Se=>g(Se.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",children:[r.jsx("option",{value:"",children:a("profiles.presets.selectBasePreset")}),G.map(Se=>r.jsx("option",{value:Se.setting_id,children:Se.name},Se.setting_id))]})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("profiles.presets.presetName")}),r.jsx("input",{type:"text",value:m,onChange:Se=>p(Se.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",placeholder:a("profiles.presets.myCustomPreset")})]})]}),w&&r.jsx("div",{className:"text-xs text-bambu-gray",children:r.jsxs("p",{className:"flex items-center gap-1",children:[r.jsx(_r,{className:"w-3 h-3 text-bambu-green"}),a("profiles.presets.inheritsFrom")," ",r.jsx("span",{className:"text-white",children:w}),z&&r.jsx(pt,{className:"w-3 h-3 animate-spin ml-1"})]})})]}),r.jsxs("div",{className:"flex border-b border-bambu-dark-tertiary max-[640px]:flex-wrap max-[640px]:items-center",children:[r.jsxs("button",{onClick:()=>c("common"),className:`flex items-center gap-2 px-4 py-3 text-sm font-medium transition-colors border-b-2 -mb-px ${l==="common"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-white border-transparent"}`,children:[r.jsx(c6,{className:"w-4 h-4"}),a("profiles.presets.tabs.common")]}),r.jsxs("button",{onClick:()=>c("fields"),className:`flex items-center gap-2 px-4 py-3 text-sm font-medium transition-colors border-b-2 -mb-px ${l==="fields"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-white border-transparent"}`,children:[r.jsx(AS,{className:"w-4 h-4"}),a("profiles.presets.tabs.allFields")]}),r.jsxs("button",{onClick:()=>c("json"),className:`flex items-center gap-2 px-4 py-3 text-sm font-medium transition-colors border-b-2 -mb-px ${l==="json"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-white border-transparent"}`,children:[r.jsx(Gy,{className:"w-4 h-4"}),"JSON",P&&r.jsx($a,{className:"w-3 h-3 text-red-400"})]}),r.jsx("div",{className:"flex-1 max-[640px]:hidden"}),r.jsxs("button",{onClick:()=>{const Se={name:m,type:d,base_id:f,setting:x},$e=new Blob([JSON.stringify(Se,null,2)],{type:"application/json"}),rt=URL.createObjectURL($e),ot=document.createElement("a");ot.href=rt,ot.download=`${m||"preset"}.json`,document.body.appendChild(ot),ot.click(),document.body.removeChild(ot),URL.revokeObjectURL(rt),i(a("profiles.presets.toast.exported"))},className:"flex items-center gap-2 px-4 py-3 text-sm text-bambu-gray hover:text-white transition-colors",title:a("profiles.presets.exportToJson"),children:[r.jsx(Yr,{className:"w-4 h-4"}),a("common.download")]}),r.jsxs("button",{onClick:()=>document.getElementById("file-import")?.click(),className:"flex items-center gap-2 px-4 py-3 text-sm text-bambu-gray hover:text-white transition-colors",title:a("profiles.presets.importFromJson"),children:[r.jsx(ka,{className:"w-4 h-4"}),a("common.upload")]}),r.jsx("input",{id:"file-import",type:"file",accept:".json",className:"hidden",onChange:Se=>{const $e=Se.target.files?.[0];if($e){const rt=new FileReader;rt.onload=ot=>{try{const Le=JSON.parse(ot.target?.result),nt=Le.setting||Le;S(Ne=>({...Ne,...nt})),i(a("profiles.presets.fileImported"))}catch{i(a("profiles.presets.invalidJson"),"error")}},rt.readAsText($e)}}})]}),r.jsxs("div",{className:"flex-1 p-4",children:[l==="common"&&r.jsxs("div",{className:"space-y-6",children:[r.jsxs("div",{children:[r.jsxs("div",{className:"flex items-center justify-between mb-3",children:[r.jsxs("h3",{className:"text-sm font-medium text-white flex items-center gap-2",children:[r.jsx(Dg,{className:"w-4 h-4 text-amber-400"}),a("profiles.templates.title")]}),Object.keys(x).filter(Se=>Se!=="inherits").length>0&&r.jsxs("button",{onClick:()=>ce(!J),className:"text-xs text-bambu-gray hover:text-white flex items-center gap-1 transition-colors",children:[r.jsx(us,{className:"w-3 h-3"}),a("profiles.presets.saveAsTemplate")]})]}),J&&r.jsxs("div",{className:"mb-3 p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"grid grid-cols-2 gap-2 mb-2",children:[r.jsx("input",{type:"text",value:pe,onChange:Se=>ue(Se.target.value),placeholder:a("profiles.templates.namePlaceholder"),className:"px-3 py-1.5 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none",autoFocus:!0}),r.jsx("input",{type:"text",value:X,onChange:Se=>ae(Se.target.value),placeholder:a("profiles.templates.descriptionPlaceholder"),className:"px-3 py-1.5 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none"})]}),r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("div",{className:"flex gap-2",children:[r.jsxs(Me,{size:"sm",onClick:de,disabled:!pe.trim(),children:[r.jsx(us,{className:"w-3 h-3"}),a("common.save")]}),r.jsx(Me,{size:"sm",variant:"secondary",onClick:()=>ce(!1),children:a("common.cancel")})]}),r.jsxs("button",{onClick:()=>ge(!me),className:`flex items-center gap-1.5 text-xs transition-colors ${me?"text-bambu-green":"text-bambu-gray hover:text-white"}`,children:[me?r.jsx(Dl,{className:"w-3.5 h-3.5"}):r.jsx(sb,{className:"w-3.5 h-3.5"}),a(me?"profiles.templates.shownInModals":"profiles.templates.hiddenInModals")]})]})]}),Pe&&r.jsxs("div",{className:"mb-3 px-3 py-2 bg-bambu-green/10 border border-bambu-green/30 rounded-lg flex items-center gap-2",children:[r.jsx(_r,{className:"w-4 h-4 text-bambu-green"}),r.jsxs("span",{className:"text-sm text-bambu-green",children:[a("profiles.presets.templateApplied")," ",r.jsx("span",{className:"font-medium",children:Pe})]}),r.jsx("button",{onClick:()=>$(null),className:"ml-auto text-bambu-green/70 hover:text-bambu-green",children:r.jsx(Ht,{className:"w-4 h-4"})})]}),r.jsxs("div",{className:"grid grid-cols-3 gap-2",children:[le.map(Se=>r.jsxs("button",{onClick:()=>fe(Se),className:"p-3 text-left bg-bambu-dark border border-bambu-dark-tertiary rounded-lg hover:border-bambu-gray-dark transition-colors",children:[r.jsx("p",{className:"text-sm font-medium text-white",children:Se.name}),r.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:Se.description})]},Se.id)),le.length===0&&r.jsx("p",{className:"col-span-3 text-center text-bambu-gray text-sm py-4",children:a("profiles.presets.noTemplatesSelected")})]}),r.jsx("p",{className:"text-xs text-bambu-gray-dark mt-2 text-center",children:a("profiles.presets.manageTemplatesHint")})]}),r.jsxs("div",{children:[r.jsx("h3",{className:"text-sm font-medium text-white mb-3",children:a("profiles.presets.commonSettings")}),r.jsx("div",{className:"grid grid-cols-2 gap-x-6 gap-y-3",children:K.slice(0,10).map(Se=>r.jsxs("div",{className:"flex items-center justify-between gap-4 max-[640px]:flex-col max-[640px]:items-start",children:[r.jsx("label",{className:"text-sm text-bambu-gray flex-shrink-0",children:Se.label}),r.jsx("div",{className:"w-48 max-[640px]:w-full",children:Oe(Se)})]},Se.key))})]}),Object.keys(x).length>1&&r.jsxs("div",{children:[r.jsx("h3",{className:"text-sm font-medium text-white mb-3",children:a("profiles.presets.currentOverrides")}),r.jsx("div",{className:"flex flex-wrap gap-2",children:Object.entries(x).filter(([Se])=>Se!=="inherits").map(([Se,$e])=>r.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-1 bg-bambu-green/10 text-bambu-green text-xs rounded",children:[Se,": ",String($e).slice(0,20),r.jsx("button",{onClick:()=>ee(Se,void 0),className:"hover:text-white",children:r.jsx(Ht,{className:"w-3 h-3"})})]},Se))})]})]}),l==="fields"&&r.jsxs("div",{className:"grid grid-cols-2 gap-6",style:{height:"400px"},children:[r.jsxs("div",{className:"flex flex-col h-full overflow-hidden",children:[r.jsxs("div",{className:"flex items-center justify-between mb-3 flex-shrink-0",children:[r.jsx("h3",{className:"text-sm font-medium text-white",children:a("profiles.presets.availableFields")}),r.jsx("span",{className:"text-xs text-bambu-gray",children:O?a("profiles.templates.fieldsCount",{count:K.length}):a("common.loading")})]}),r.jsxs("div",{className:"relative mb-3 flex-shrink-0",children:[r.jsx(Sr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),r.jsx("input",{type:"text",value:A,onChange:Se=>F(Se.target.value),placeholder:a("profiles.presets.searchFieldsPlaceholder"),className:"w-full pl-10 pr-4 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder-bambu-gray-dark focus:border-bambu-green focus:outline-none"})]}),r.jsxs("div",{className:"flex-1 overflow-y-auto space-y-1 pr-2 min-h-0",children:[Z.filter(Se=>!(Se.key in x)).map(Se=>{const $e=Ee[Se.key],rt=ze($e);return r.jsxs("div",{onClick:()=>{S(ot=>({...ot,[Se.key]:rt||""}))},className:"flex items-center justify-between gap-2 p-2 rounded-lg hover:bg-bambu-dark-tertiary transition-colors cursor-pointer group",children:[r.jsxs("div",{className:"min-w-0 flex-1",children:[r.jsx("p",{className:"text-sm text-white truncate",children:Se.label}),r.jsx("p",{className:"text-xs text-bambu-gray-dark truncate",children:Se.key})]}),r.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[rt&&r.jsxs("span",{className:"text-xs text-bambu-gray bg-bambu-dark px-2 py-0.5 rounded max-w-32 truncate",title:rt,children:[rt.slice(0,20),rt.length>20?"...":""]}),r.jsx("div",{className:"w-6 h-6 flex items-center justify-center rounded bg-bambu-dark-tertiary group-hover:bg-bambu-green/20 transition-colors",children:r.jsx(ir,{className:"w-4 h-4 text-bambu-gray group-hover:text-bambu-green transition-colors"})})]})]},Se.key)}),Z.filter(Se=>!(Se.key in x)).length===0&&r.jsx("p",{className:"text-center text-bambu-gray py-4 text-sm",children:a(A?"profiles.presets.noMatchingFields":"profiles.presets.allFieldsAdded")})]}),r.jsx("div",{className:"pt-3 mt-3 border-t border-bambu-dark-tertiary flex-shrink-0",children:U?r.jsxs("div",{className:"flex gap-2",children:[r.jsx("input",{type:"text",value:H,onChange:Se=>I(Se.target.value),onKeyDown:Se=>Se.key==="Enter"&&oe(),placeholder:"custom_field_name",className:"flex-1 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white font-mono text-sm placeholder-bambu-gray-dark focus:border-bambu-green focus:outline-none",autoFocus:!0}),r.jsx(Me,{size:"sm",onClick:oe,disabled:!H.trim(),children:r.jsx(ir,{className:"w-4 h-4"})}),r.jsx(Me,{size:"sm",variant:"secondary",onClick:()=>{L(!1),I("")},children:r.jsx(Ht,{className:"w-4 h-4"})})]}):r.jsxs("button",{onClick:()=>L(!0),className:"w-full flex items-center justify-center gap-2 p-2 text-sm text-bambu-gray hover:text-white border border-dashed border-bambu-dark-tertiary hover:border-bambu-gray-dark rounded-lg transition-colors",children:[r.jsx(ir,{className:"w-4 h-4"}),a("profiles.presets.addCustomField")]})})]}),r.jsxs("div",{className:"flex flex-col h-full overflow-hidden",children:[r.jsxs("div",{className:"flex items-center justify-between mb-3 flex-shrink-0",children:[r.jsx("h3",{className:"text-sm font-medium text-white",children:a("profiles.presets.yourOverrides")}),r.jsx("span",{className:"text-xs text-bambu-gray",children:a("profiles.templates.fieldsCount",{count:Object.keys(x).filter(Se=>Se!=="inherits").length})})]}),r.jsxs("div",{className:"flex-1 overflow-y-auto space-y-2 pr-2 min-h-0",children:[Object.entries(x).filter(([Se])=>Se!=="inherits").map(([Se,$e])=>{const rt=K.find(ot=>ot.key===Se);return r.jsxs("div",{className:"p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"flex items-center justify-between mb-2",children:[r.jsxs("div",{children:[r.jsx("p",{className:"text-sm font-medium text-white",children:rt?.label||Se}),r.jsx("p",{className:"text-xs text-bambu-gray-dark",children:Se})]}),r.jsx("button",{onClick:()=>ee(Se,void 0),className:"p-1 text-bambu-gray hover:text-red-400 transition-colors",children:r.jsx(Ht,{className:"w-4 h-4"})})]}),rt?Oe(rt):r.jsx("input",{type:"text",value:String($e),onChange:ot=>ee(Se,ot.target.value),className:"w-full px-3 py-1.5 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none"})]},Se)}),Object.keys(x).filter(Se=>Se!=="inherits").length===0&&r.jsxs("div",{className:"text-center py-8 text-bambu-gray",children:[r.jsx(c6,{className:"w-8 h-8 mx-auto mb-2 opacity-50"}),r.jsx("p",{className:"text-sm",children:a("profiles.presets.noOverridesYet")}),r.jsx("p",{className:"text-xs mt-1",children:a("profiles.presets.clickFieldsToAdd")})]})]}),Object.keys(x).filter(Se=>Se!=="inherits").length>0&&r.jsx("div",{className:"pt-3 mt-3 border-t border-bambu-dark-tertiary flex-shrink-0",children:r.jsxs("button",{onClick:()=>{ce(!0),c("common")},className:"w-full flex items-center justify-center gap-2 p-2 text-sm text-bambu-gray hover:text-white border border-dashed border-bambu-dark-tertiary hover:border-bambu-gray-dark rounded-lg transition-colors",children:[r.jsx(us,{className:"w-4 h-4"}),a("profiles.presets.saveAsTemplate")]})})]})]}),l==="json"&&r.jsxs("div",{className:"space-y-2",children:[P&&r.jsxs("div",{className:"flex items-center gap-2 text-red-400 text-sm",children:[r.jsx($a,{className:"w-4 h-4"}),P]}),r.jsx("textarea",{value:N,onChange:Se=>q(Se.target.value),className:`w-full h-80 px-3 py-2 bg-bambu-dark border rounded-lg text-white text-xs font-mono focus:outline-none resize-none ${P?"border-red-500 focus:border-red-500":"border-bambu-dark-tertiary focus:border-bambu-green"}`,spellCheck:!1}),r.jsx("p",{className:"text-xs text-bambu-gray",children:a("profiles.presets.jsonTip")})]})]}),r.jsxs("div",{className:"p-4 border-t border-bambu-dark-tertiary flex gap-2",children:[r.jsx(Me,{variant:"secondary",onClick:t,className:"flex-1",children:a("common.cancel")}),r.jsxs(Me,{onClick:()=>ve.mutate(),disabled:ve.isPending||!m.trim()||!o&&!f||!!P,className:"flex-1",children:[ve.isPending?r.jsx(pt,{className:"w-4 h-4 animate-spin"}):o?r.jsx(us,{className:"w-4 h-4"}):r.jsx(ir,{className:"w-4 h-4"}),a(o?"common.save":e?"common.duplicate":"common.create")]})]})]})})]})}function zat({settings:t,lastSyncTime:e,onRefresh:n,isRefreshing:a,printers:i,hasPermission:s,t:o}){const[l,c]=y.useState(""),[d,u]=y.useState("all"),[m,p]=y.useState("all"),[f,g]=y.useState("all"),[w,b]=y.useState("all"),[x,S]=y.useState("all"),[N,C]=y.useState("all"),[P,T]=y.useState(null),[A,F]=y.useState(!1),[_,E]=y.useState(!1),[H,I]=y.useState(null),[U,L]=y.useState(null),[Q,re]=y.useState(null),[J,ce]=y.useState(!1),[pe,ue]=y.useState([null,null]),[X,ae]=y.useState(!1),[me,ge]=y.useState(null),Pe=en(),$=y.useMemo(()=>[...t.filament.map(oe=>({...oe,type:"filament"})),...t.printer.map(oe=>({...oe,type:"printer"})),...t.process.map(oe=>({...oe,type:"process"}))].map(oe=>({...oe,meta:aU(oe.name)})),[t]),W=y.useMemo(()=>{const Z=new Set,oe=new Set,ee=new Set;return $.forEach(fe=>{fe.meta.nozzle&&Z.add(fe.meta.nozzle),fe.meta.filamentType&&oe.add(fe.meta.filamentType),fe.meta.layerHeight&&ee.add(fe.meta.layerHeight)}),{printers:i.map(fe=>({id:fe.id.toString(),name:fe.name})),nozzles:Array.from(Z).sort((fe,de)=>parseFloat(fe)-parseFloat(de)),filaments:Array.from(oe).sort(),layerHeights:Array.from(ee).sort((fe,de)=>parseFloat(fe)-parseFloat(de))}},[$,i]),D=y.useMemo(()=>f==="all"?null:i.find(oe=>oe.id.toString()===f)?.model||null,[f,i]),j=y.useMemo(()=>$.filter(Z=>d==="all"||Z.type===d).filter(Z=>{if(m==="all")return!0;const oe=vS(Z.setting_id);return m==="custom"?oe:!oe}).filter(Z=>{if(f==="all"||!D)return!0;const oe=Z.meta.printer?.toLowerCase()||"",ee=D.toLowerCase();return oe.includes(ee)||ee.includes(oe)}).filter(Z=>w==="all"||Z.meta.nozzle===w).filter(Z=>x==="all"||Z.meta.filamentType===x).filter(Z=>N==="all"||Z.meta.layerHeight===N).filter(Z=>l===""||Z.name.toLowerCase().includes(l.toLowerCase())).sort((Z,oe)=>Z.name.localeCompare(oe.name)),[$,d,m,f,D,w,x,N,l]),B=Z=>{if(J){const oe=pe[0]?.setting_id===Z.setting_id,ee=pe[1]?.setting_id===Z.setting_id;if(oe)ue([pe[1],null]);else if(ee)ue([pe[0],null]);else if(!pe[0])ue([Z,null]);else if(pe[1]){if(pe[0].type!==Z.type)return;ue([pe[0],Z])}else{if(pe[0].type!==Z.type)return;ue([pe[0],Z])}}else T(Z)},Y=Z=>{if(pe[0]?.setting_id===Z.setting_id)return 0;if(pe[1]?.setting_id===Z.setting_id)return 1},O=async Z=>{try{const oe=await ie.getCloudSettingDetail(Z.setting_id),ee=Z.type==="process"?"print":Z.type;I({type:ee,name:Z.name,base_id:oe.base_id||"GFSA00",setting:oe.setting||{}}),T(null)}catch(oe){console.error("Failed to fetch preset details for duplication:",oe)}},se=async Z=>{try{Pe.removeQueries({queryKey:["cloudSettingDetail",Z.setting_id]});const oe=await ie.getCloudSettingDetail(Z.setting_id),ee=Z.type==="process"?"print":Z.type;L({type:ee,name:Z.name,base_id:oe.base_id||"GFSA00",setting:oe.setting||{},setting_id:Z.setting_id}),T(null)}catch(oe){console.error("Failed to fetch preset details for editing:",oe)}},z=()=>{u("all"),p("all"),g("all"),b("all"),S("all"),C("all"),c("")},G=d!=="all"||m!=="all"||f!=="all"||w!=="all"||x!=="all"||N!=="all"||l!=="",K=t.filament.length+t.printer.length+t.process.length;return r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"space-y-4 mb-6",children:[r.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[r.jsxs("div",{className:"relative flex-1",children:[r.jsx(Sr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),r.jsx("input",{type:"text",value:l,onChange:Z=>c(Z.target.value),placeholder:o("profiles.cloudView.searchPlaceholder"),className:"w-full pl-10 pr-4 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray-dark focus:border-bambu-green focus:outline-none"})]}),r.jsxs("div",{className:"flex gap-2 max-[550px]:flex-wrap max-[550px]:items-center",children:[r.jsxs(Me,{variant:J?"primary":"secondary",onClick:()=>{J?(ce(!1),ue([null,null])):ce(!0)},children:[r.jsx(Zx,{className:"w-4 h-4"}),o(J?"common.cancel":"profiles.presets.compare")]}),r.jsxs(Me,{variant:"secondary",onClick:()=>E(!0),disabled:!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.cloudView.noTemplatesPermission"),children:[r.jsx(Dg,{className:"w-4 h-4"}),o("profiles.cloudView.templates")]}),r.jsxs(Me,{variant:"secondary",onClick:n,disabled:a||!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.cloudView.noRefreshPermission"),children:[r.jsx(er,{className:`w-4 h-4 ${a?"animate-spin":""}`}),o("profiles.cloudView.refresh")]}),r.jsxs(Me,{onClick:()=>F(!0),disabled:!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.cloudView.noCreatePermission"),children:[r.jsx(ir,{className:"w-4 h-4"}),o("profiles.cloudView.newPreset")]})]})]}),r.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[r.jsx(NS,{className:"w-4 h-4 text-bambu-gray"}),r.jsx(Rx,{label:o("profiles.cloudView.filters.type"),value:d,options:[{value:"all",label:o("profiles.cloudView.filters.all"),count:K},{value:"filament",label:o("profiles.cloudView.filters.filament"),count:t.filament.length},{value:"printer",label:o("profiles.cloudView.filters.printer"),count:t.printer.length},{value:"process",label:o("profiles.cloudView.filters.process"),count:t.process.length}],onChange:Z=>u(Z)}),r.jsx(Rx,{label:o("profiles.cloudView.filters.owner"),value:m,options:[{value:"all",label:o("profiles.cloudView.filters.all")},{value:"custom",label:o("profiles.cloudView.filters.myPresets")},{value:"builtin",label:o("profiles.cloudView.filters.builtIn")}],onChange:Z=>p(Z)}),W.printers.length>0&&r.jsx(Rx,{label:o("profiles.cloudView.filters.printer"),value:f,options:[{value:"all",label:o("profiles.cloudView.filters.all")},...W.printers.map(Z=>({value:Z.id,label:Z.name}))],onChange:g}),W.nozzles.length>0&&r.jsx(Rx,{label:o("profiles.cloudView.filters.nozzle"),value:w,options:[{value:"all",label:o("profiles.cloudView.filters.all")},...W.nozzles.map(Z=>({value:Z,label:Z}))],onChange:b}),W.filaments.length>0&&(d==="all"||d==="filament")&&r.jsx(Rx,{label:o("profiles.cloudView.filters.filament"),value:x,options:[{value:"all",label:o("profiles.cloudView.filters.all")},...W.filaments.map(Z=>({value:Z,label:Z}))],onChange:S}),W.layerHeights.length>0&&(d==="all"||d==="process")&&r.jsx(Rx,{label:o("profiles.cloudView.filters.layer"),value:N,options:[{value:"all",label:o("profiles.cloudView.filters.all")},...W.layerHeights.map(Z=>({value:Z,label:Z}))],onChange:C}),G&&r.jsx("button",{onClick:z,className:"px-3 py-2 text-sm text-bambu-gray hover:text-white transition-colors",children:o("profiles.cloudView.clearFilters")})]})]}),J&&r.jsx("div",{className:"mb-4 p-3 bg-blue-500/10 border border-blue-500/30 rounded-lg",children:r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("div",{className:"flex items-center gap-4",children:[r.jsx(Zx,{className:"w-5 h-5 text-blue-400"}),r.jsx("span",{className:"text-white font-medium",children:o("profiles.cloudView.compareMode")}),r.jsx("span",{className:"text-bambu-gray",children:pe[0]?o("profiles.cloudView.selectAnotherPreset",{type:pe[0].type}):o("profiles.cloudView.clickTwoPresets")})]}),r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("span",{className:`px-2 py-1 text-sm rounded truncate max-w-[200px] ${pe[0]?"bg-blue-500/30 text-blue-700 dark:text-blue-300":"bg-bambu-dark text-bambu-gray"}`,children:pe[0]?pe[0].name:o("profiles.cloudView.selectFirst")}),r.jsx(XN,{className:"w-4 h-4 text-bambu-gray"}),r.jsx("span",{className:`px-2 py-1 text-sm rounded truncate max-w-[200px] ${pe[1]?"bg-blue-500/30 text-blue-700 dark:text-blue-300":"bg-bambu-dark text-bambu-gray"}`,children:pe[1]?pe[1].name:o("profiles.cloudView.selectSecond")})]}),pe[0]&&pe[1]&&r.jsxs(Me,{size:"sm",onClick:async()=>{try{const[Z,oe]=await Promise.all([ie.getCloudSettingDetail(pe[0].setting_id),ie.getCloudSettingDetail(pe[1].setting_id)]);ge([Z.setting||{},oe.setting||{}]),ae(!0)}catch{}},children:[r.jsx(Zx,{className:"w-4 h-4"}),o("profiles.cloudView.compareNow")]})]})]})}),r.jsxs("div",{className:"flex flex-wrap items-center gap-4 mb-4 text-sm text-bambu-gray",children:[e&&r.jsxs("div",{className:"flex items-center gap-1",children:[r.jsx(Zn,{className:"w-3 h-3"}),o("profiles.cloudView.lastSynced")," ",jh(e.toISOString(),"system",o)]}),r.jsx("span",{children:o("profiles.cloudView.showingCount",{showing:j.length,total:K})}),r.jsxs("div",{className:"flex items-center gap-1",children:[r.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-bambu-green"}),r.jsxs("span",{children:["= ",o("profiles.presets.myPreset")]})]})]}),j.length===0?r.jsxs("div",{className:"text-center py-16",children:[r.jsx(oa,{className:"w-12 h-12 text-bambu-gray-dark mx-auto mb-4"}),r.jsx("p",{className:"text-bambu-gray",children:o("profiles.cloudView.noPresetsFound")}),G&&r.jsx("button",{onClick:z,className:"mt-2 text-sm text-bambu-green hover:text-bambu-green-light",children:o("profiles.cloudView.clearFilters")})]}):r.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-6",children:[r.jsxs("div",{children:[r.jsxs("div",{className:"flex items-center gap-2 mb-3 px-1",children:[r.jsx(ST,{className:"w-4 h-4 text-amber-400"}),r.jsx("h3",{className:"text-sm font-medium text-bambu-gray",children:o("profiles.cloudView.columns.filament")}),r.jsxs("span",{className:"text-xs text-bambu-gray-dark",children:["(",j.filter(Z=>Z.type==="filament").length,")"]})]}),r.jsxs("div",{className:"space-y-1 max-h-[calc(100vh-320px)] overflow-y-auto pr-1",children:[j.filter(Z=>Z.type==="filament").map(Z=>r.jsx(uF,{setting:Z,onClick:()=>B(Z),onDuplicate:()=>O(Z),compareMode:J,isCompareSelected:Y(Z)!==void 0,compareIndex:Y(Z),compareDisabled:J&&!!pe[0]&&pe[0].type!==Z.type,t:o},Z.setting_id)),j.filter(Z=>Z.type==="filament").length===0&&r.jsx("p",{className:"text-xs text-bambu-gray-dark px-3 py-2",children:o("profiles.cloudView.noFilamentPresets")})]})]}),r.jsxs("div",{children:[r.jsxs("div",{className:"flex items-center gap-2 mb-3 px-1",children:[r.jsx(uu,{className:"w-4 h-4 text-blue-400"}),r.jsx("h3",{className:"text-sm font-medium text-bambu-gray",children:o("profiles.cloudView.columns.process")}),r.jsxs("span",{className:"text-xs text-bambu-gray-dark",children:["(",j.filter(Z=>Z.type==="process").length,")"]})]}),r.jsxs("div",{className:"space-y-1 max-h-[calc(100vh-320px)] overflow-y-auto pr-1",children:[j.filter(Z=>Z.type==="process").map(Z=>r.jsx(uF,{setting:Z,onClick:()=>B(Z),onDuplicate:()=>O(Z),compareMode:J,isCompareSelected:Y(Z)!==void 0,compareIndex:Y(Z),compareDisabled:J&&!!pe[0]&&pe[0].type!==Z.type,t:o},Z.setting_id)),j.filter(Z=>Z.type==="process").length===0&&r.jsx("p",{className:"text-xs text-bambu-gray-dark px-3 py-2",children:o("profiles.cloudView.noProcessPresets")})]})]}),r.jsxs("div",{children:[r.jsxs("div",{className:"flex items-center gap-2 mb-3 px-1",children:[r.jsx(pr,{className:"w-4 h-4 text-purple-400"}),r.jsx("h3",{className:"text-sm font-medium text-bambu-gray",children:o("profiles.cloudView.columns.printer")}),r.jsxs("span",{className:"text-xs text-bambu-gray-dark",children:["(",j.filter(Z=>Z.type==="printer").length,")"]})]}),r.jsxs("div",{className:"space-y-1 max-h-[calc(100vh-320px)] overflow-y-auto pr-1",children:[j.filter(Z=>Z.type==="printer").map(Z=>r.jsx(uF,{setting:Z,onClick:()=>B(Z),onDuplicate:()=>O(Z),compareMode:J,isCompareSelected:Y(Z)!==void 0,compareIndex:Y(Z),compareDisabled:J&&!!pe[0]&&pe[0].type!==Z.type,t:o},Z.setting_id)),j.filter(Z=>Z.type==="printer").length===0&&r.jsx("p",{className:"text-xs text-bambu-gray-dark px-3 py-2",children:o("profiles.cloudView.noPrinterPresets")})]})]})]}),P&&r.jsx(Lat,{setting:P,onClose:()=>T(null),onDeleted:()=>T(null),onDuplicate:()=>O(P),onEdit:()=>se(P),hasPermission:s,t:o}),(A||H||U||Q)&&r.jsx(Oat,{onClose:()=>{F(!1),I(null),L(null),re(null)},initialData:U||H||(Q?{type:Q.type,name:"",base_id:"",setting:Q.setting}:void 0),allPresets:t,t:o}),_&&r.jsx(Iat,{onClose:()=>E(!1),onApply:Z=>{re({type:Z.type,setting:Z.settings}),E(!1)},t:o}),X&&me&&pe[0]&&pe[1]&&r.jsx(Fce,{onClose:()=>{ae(!1),ge(null)},leftPreset:me[0],rightPreset:me[1],leftLabel:pe[0].name,rightLabel:pe[1].name,t:o})]})}function Uat(){const{t}=kt(),e=en(),{showToast:n}=rn(),{hasPermission:a}=cr(),[i,s]=y.useState("cloud"),[o,l]=y.useState(),{data:c,isLoading:d}=Ge({queryKey:["cloudStatus"],queryFn:ie.getCloudStatus}),{data:u=[]}=Ge({queryKey:["printers"],queryFn:ie.getPrinters}),{data:m,isLoading:p,refetch:f,dataUpdatedAt:g}=Ge({queryKey:["cloudSettings"],queryFn:()=>ie.getCloudSettings(),enabled:!!c?.is_authenticated,retry:!1,staleTime:1e3*60*5});y.useEffect(()=>{g&&l(new Date(g))},[g]);const w=it({mutationFn:ie.cloudLogout,onSuccess:()=>{e.invalidateQueries({queryKey:["cloudStatus"]}),e.removeQueries({queryKey:["cloudSettings"]}),n(t("profiles.toast.loggedOut"))}}),b=()=>{e.invalidateQueries({queryKey:["cloudStatus"]})};return d?r.jsx("div",{className:"p-4 md:p-8 flex items-center justify-center min-h-[400px]",children:r.jsx(pt,{className:"w-8 h-8 text-bambu-green animate-spin"})}):r.jsxs("div",{className:"p-4 md:p-8",children:[r.jsxs("div",{className:"mb-6",children:[r.jsxs("h1",{className:"text-2xl font-bold text-white flex items-center gap-3",children:[r.jsx(Hh,{className:"w-7 h-7 text-bambu-green"}),t("profiles.title")]}),r.jsx("p",{className:"text-bambu-gray mt-1",children:t("profiles.subtitle")})]}),r.jsxs("div",{className:"flex border-b border-bambu-dark-tertiary mb-6",children:[r.jsxs("button",{onClick:()=>s("cloud"),className:`flex items-center gap-2 px-4 py-3 text-sm font-medium transition-colors border-b-2 -mb-px ${i==="cloud"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-white border-transparent"}`,children:[r.jsx(Hh,{className:"w-4 h-4"}),t("profiles.tabs.cloud")]}),r.jsxs("button",{onClick:()=>s("local"),className:`flex items-center gap-2 px-4 py-3 text-sm font-medium transition-colors border-b-2 -mb-px ${i==="local"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-white border-transparent"}`,children:[r.jsx(ob,{className:"w-4 h-4"}),t("profiles.tabs.local")]}),r.jsxs("button",{onClick:()=>s("kprofiles"),className:`flex items-center gap-2 px-4 py-3 text-sm font-medium transition-colors border-b-2 -mb-px ${i==="kprofiles"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-white border-transparent"}`,children:[r.jsx(CS,{className:"w-4 h-4"}),t("profiles.tabs.kprofiles")]})]}),i==="cloud"&&r.jsxs(r.Fragment,{children:[c?.is_authenticated&&r.jsxs("div",{className:"flex items-center justify-between p-3 mb-6 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("div",{className:"w-2 h-2 rounded-full bg-bambu-green animate-pulse"}),r.jsxs("span",{className:"text-sm text-bambu-gray",children:[t("profiles.connectedAs")," ",r.jsx("span",{className:"text-white",children:c.email}),c.region&&r.jsx("span",{className:"ml-2 px-2 py-0.5 text-xs rounded bg-bambu-dark-tertiary text-bambu-gray",children:c.region==="china"?t("profiles.login.regionChina"):t("profiles.login.regionGlobal")})]})]}),r.jsxs(Me,{variant:"secondary",size:"sm",onClick:()=>w.mutate(),disabled:w.isPending||!a("cloud:auth"),title:a("cloud:auth")?void 0:t("profiles.noLogoutPermission"),children:[r.jsx(Jx,{className:"w-4 h-4"}),t("profiles.logout")]})]}),c?.is_authenticated?p?r.jsx("div",{className:"flex items-center justify-center py-16",children:r.jsx(pt,{className:"w-8 h-8 text-bambu-green animate-spin"})}):m?r.jsx(zat,{settings:m,lastSyncTime:o,onRefresh:()=>f(),isRefreshing:p,printers:u,hasPermission:a,t}):r.jsxs("div",{className:"text-center py-16",children:[r.jsx("p",{className:"text-bambu-gray mb-4",children:t("profiles.failedToLoad")}),r.jsx(Me,{onClick:()=>f(),children:t("profiles.retry")})]}):r.jsx(Fat,{onSuccess:b,t})]}),i==="local"&&r.jsx(Dat,{}),i==="kprofiles"&&r.jsx(Aat,{}),r.jsx(Rat,{})]})}function Bat(t,e){const n=(e||"").toUpperCase().replace(/[- ]/g,""),a=n.includes("X1"),i=n.includes("P1"),s=n.includes("A1MINI"),o=n.includes("A1")&&!s,l=n.includes("H2D"),c=n.includes("H2C"),d=n.includes("H2S"),u=l||c||d,m=n.includes("P2S"),p=n.includes("X2D"),f=m||p;switch(t){case"Lubricate Steel Rods":return f?"https://wiki.bambulab.com/en/p2s/maintenance/lubricate-x-y-z-axis":null;case"Clean Steel Rods":return f?"https://wiki.bambulab.com/en/p2s/maintenance/lubricate-x-y-z-axis":null;case"Lubricate Linear Rails":return s?"https://wiki.bambulab.com/en/a1-mini/maintenance/lubricate-y-axis":o?"https://wiki.bambulab.com/en/a1/maintenance/lubricate-y-axis":u?"https://wiki.bambulab.com/en/h2/maintenance/x-axis-lubrication":null;case"Clean Nozzle/Hotend":return a||i?"https://wiki.bambulab.com/en/x1/troubleshooting/nozzle-clog":s||o?"https://wiki.bambulab.com/en/a1-mini/troubleshooting/nozzle-clog":u?"https://wiki.bambulab.com/en/h2/maintenance/nozzl-cold-pull-maintenance-and-cleaning":f?"https://wiki.bambulab.com/en/p2s/maintenance/cold-pull-maintenance-hotend":"https://wiki.bambulab.com/en/x1/troubleshooting/nozzle-clog";case"Check Belt Tension":return a?"https://wiki.bambulab.com/en/x1/maintenance/belt-tension":i?"https://wiki.bambulab.com/en/p1/maintenance/p1p-maintenance":s?"https://wiki.bambulab.com/en/a1-mini/maintenance/belt_tension":o?"https://wiki.bambulab.com/en/a1/maintenance/belt_tension":l?"https://wiki.bambulab.com/en/h2/maintenance/belt-tension":c?"https://wiki.bambulab.com/en/h2c/maintenance/belt-tension":d?"https://wiki.bambulab.com/en/h2s/maintenance/belt-tension":f?"https://wiki.bambulab.com/en/p2s/maintenance/belt-tension":"https://wiki.bambulab.com/en/x1/maintenance/belt-tension";case"Clean Carbon Rods":return a||i?"https://wiki.bambulab.com/en/general/carbon-rods-clearance":null;case"Clean Linear Rails":return s?"https://wiki.bambulab.com/en/a1-mini/maintenance/lubricate-y-axis":o?"https://wiki.bambulab.com/en/a1/maintenance/lubricate-y-axis":u?"https://wiki.bambulab.com/en/h2/maintenance/x-axis-lubrication":null;case"Clean Build Plate":return"https://wiki.bambulab.com/en/filament-acc/acc/pei-plate-clean-guide";case"Check PTFE Tube":return a||i?"https://wiki.bambulab.com/en/x1/maintenance/replace-ptfe-tube":s||o?"https://wiki.bambulab.com/en/a1-mini/maintenance/ptfe-tube":l?"https://wiki.bambulab.com/en/h2/maintenance/replace-ptfe-tube-on-h2d-printer":d?"https://wiki.bambulab.com/en/h2s/maintenance/replace-ptfe-tube-on-h2s-printer":c?"https://wiki.bambulab.com/en/h2/maintenance/replace-ptfe-tube-on-h2d-printer":"https://wiki.bambulab.com/en/x1/maintenance/replace-ptfe-tube";case"Replace HEPA Filter":case"HEPA Filter":case"Replace Carbon Filter":case"Carbon Filter":return u?"https://wiki.bambulab.com/en/h2/maintenance/replace-smoke-purifier-air-filte":"https://wiki.bambulab.com/en/x1/maintenance/replace-carbon-filter";case"Lubricate Left Nozzle Rail":case"Left Nozzle Rail":return u?"https://wiki.bambulab.com/en/h2/maintenance/x-axis-lubrication":null;default:return null}}const V0={Droplet:ST,Flame:mm,Ruler:Zxe,Sparkles:Dg,Square:so,Cable:hO,Wrench:qh,Calendar:Sa,Timer:Xd,Cog:cu,Fan:TZ,Zap:Cc,Wind:HZ,Thermometer:FS,Layers:oa,Box:Ni,Target:OZ,RefreshCw:er,Settings:gy,Filter:NS,CircleDot:rge};function yw(t){return t&&V0[t]||qh}function Lx(t,e,n){if(e==="days"){if(t<1)return n?n("common.today"):"Today";if(t===1)return n?n("maintenance.day"):"1 day";if(t<7){const i=Math.round(t);return n?n("maintenance.days",{count:i}):`${i} days`}if(t<180){const i=Math.round(t/7);return i===1?n?n("maintenance.week"):"1 week":n?n("maintenance.weeks",{count:i}):`${i} weeks`}const a=Math.round(t/30);return a===1?n?n("maintenance.month"):"1 month":n?n("maintenance.months",{count:a}):`${a} months`}else{if(t<1)return`${Math.round(t*60)}m`;if(t<24)return`${t<10?t.toFixed(1):Math.round(t)}h`;const a=t/24;if(a<7)return`${a<2?a.toFixed(1):Math.round(a)}d`;const i=a/7;return i<12?`${i<2?i.toFixed(1):Math.round(i)}w`:`${Math.round(i/4)}mo`}}function mF(t,e,n){return e==="days"?t===1?n?n("maintenance.day"):"1 day":t===7?n?n("maintenance.week"):"1 week":t===14?n?n("maintenance.weeks",{count:2}):"2 weeks":t===30?n?n("maintenance.month"):"1 month":t===60?n?n("maintenance.months",{count:2}):"2 months":t===90?n?n("maintenance.months",{count:3}):"3 months":t===180?n?n("maintenance.months",{count:6}):"6 months":t===365?n?n("maintenance.year"):"1 year":n?n("maintenance.days",{count:t}):`${t} days`:`${t}h`}function Hat({item:t,onPerform:e,onToggle:n,hasPermission:a,t:i}){const s=yw(t.maintenance_type_icon),o=t.interval_type||"hours",c=(()=>{if(o==="days"){const f=t.days_since_maintenance??0;return Math.max(0,Math.min(100,f/t.interval_hours*100))}return Math.max(0,Math.min(100,(t.interval_hours-t.hours_until_due)/t.interval_hours*100))})(),d=()=>t.enabled?t.is_due?"text-red-400":t.is_warning?"text-amber-400":"text-bambu-green":"text-bambu-gray",u=()=>t.enabled?t.is_due?"bg-red-500":t.is_warning?"bg-amber-500":"bg-bambu-green":"bg-bambu-gray/30",m=()=>t.enabled?t.is_due?"bg-red-500/5 border-red-500/20":t.is_warning?"bg-amber-500/5 border-amber-500/20":"bg-bambu-dark-secondary border-bambu-dark-tertiary":"bg-bambu-dark-secondary/50",p=()=>{if(!t.enabled)return i("common.disabled");if(o==="days"){const f=t.days_until_due??0;return t.is_due?i("maintenance.overdueBy",{duration:Lx(Math.abs(f),"days",i)}):t.is_warning?i("maintenance.dueIn",{duration:Lx(f,"days",i)}):i("maintenance.timeLeft",{duration:Lx(f,"days",i)})}else return t.is_due?i("maintenance.overdueBy",{duration:Lx(Math.abs(t.hours_until_due),"hours",i)}):t.is_warning?i("maintenance.dueIn",{duration:Lx(t.hours_until_due,"hours",i)}):i("maintenance.timeLeft",{duration:Lx(t.hours_until_due,"hours",i)})};return r.jsx("div",{className:`rounded-xl border p-4 transition-all ${m()}`,children:r.jsxs("div",{className:"flex items-start gap-3 max-[550px]:flex-wrap",children:[r.jsxs("div",{className:`relative p-2.5 rounded-lg shrink-0 ${t.is_due?"bg-red-500/20":t.is_warning?"bg-amber-500/20":t.enabled?"bg-bambu-dark":"bg-bambu-dark/50"}`,children:[r.jsx(s,{className:`w-5 h-5 ${d()}`}),t.enabled&&(t.is_due||t.is_warning)&&r.jsx("span",{className:`absolute -top-1 -right-1 w-2.5 h-2.5 rounded-full ${t.is_due?"bg-red-500":"bg-amber-500"} animate-pulse`})]}),r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("h3",{className:`font-medium truncate ${t.enabled?"text-white":"text-bambu-gray"}`,children:t.maintenance_type_name}),o==="days"&&r.jsx("span",{title:i("maintenance.timeBasedInterval"),children:r.jsx(Sa,{className:"w-3.5 h-3.5 text-bambu-gray shrink-0"})}),(()=>{const f=t.maintenance_type_wiki_url||Bat(t.maintenance_type_name,t.printer_model);return f?r.jsx("a",{href:f,target:"_blank",rel:"noopener noreferrer",className:"text-bambu-gray hover:text-bambu-green transition-colors shrink-0",title:i("maintenance.viewDocumentation"),onClick:g=>g.stopPropagation(),children:r.jsx(Lr,{className:"w-3.5 h-3.5"})}):null})()]}),r.jsx("div",{className:"mt-2 mb-1.5",children:r.jsx("div",{className:"w-full h-1.5 bg-bambu-dark rounded-full overflow-hidden",children:r.jsx("div",{className:`h-full rounded-full transition-all duration-500 ${u()}`,style:{width:`${c}%`}})})}),r.jsxs("div",{className:`text-xs flex items-center gap-1 ${d()}`,children:[t.is_due&&r.jsx(Nn,{className:"w-3 h-3"}),t.is_warning&&!t.is_due&&r.jsx(Zn,{className:"w-3 h-3"}),!t.is_due&&!t.is_warning&&t.enabled&&r.jsx(_r,{className:"w-3 h-3"}),p()]})]}),r.jsxs("div",{className:"flex items-center gap-2 shrink-0 max-[550px]:w-full max-[550px]:justify-end max-[550px]:mt-1",children:[r.jsx("span",{title:a("maintenance:update")?void 0:i("maintenance.noPermissionUpdate"),children:r.jsx(En,{checked:t.enabled,onChange:f=>n(t.id,f),disabled:!a("maintenance:update")})}),r.jsxs(Me,{size:"sm",variant:t.is_due?"primary":"secondary",onClick:()=>e(t.id),disabled:!t.enabled||!a("maintenance:update"),title:a("maintenance:update")?void 0:i("maintenance.noPermissionPerform"),className:"!px-3",children:[r.jsx(gs,{className:"w-3.5 h-3.5"}),i("common.reset")]})]})]})})}function qat({overview:t,onPerform:e,onToggle:n,onSetHours:a,hasPermission:i,t:s}){const[o,l]=y.useState(!1),[c,d]=y.useState(!1),[u,m]=y.useState(t.total_print_hours.toFixed(1)),p=[...t.maintenance_items].sort((w,b)=>w.is_due&&!b.is_due?-1:!w.is_due&&b.is_due?1:w.is_warning&&!b.is_warning?-1:!w.is_warning&&b.is_warning?1:w.maintenance_type_id-b.maintenance_type_id),f=p.find(w=>w.enabled&&(w.is_due||w.is_warning)),g=()=>{const w=parseFloat(u);!isNaN(w)&&w>=0&&(a(t.printer_id,w),d(!1))};return r.jsxs(Ct,{className:"overflow-hidden",children:[r.jsxs("div",{className:"p-5",children:[r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("div",{className:"flex items-center gap-4",children:[r.jsx("h2",{className:"text-xl font-semibold text-white",children:t.printer_name}),r.jsxs("div",{className:"flex items-center gap-2",children:[t.due_count>0&&r.jsxs("span",{className:"px-2.5 py-1 bg-red-500/20 text-red-400 text-xs font-medium rounded-full flex items-center gap-1.5",children:[r.jsx(Nn,{className:"w-3 h-3"}),s("maintenance.overdueCount",{count:t.due_count})]}),t.warning_count>0&&r.jsxs("span",{className:"px-2.5 py-1 bg-amber-500/20 text-amber-400 text-xs font-medium rounded-full flex items-center gap-1.5",children:[r.jsx(Zn,{className:"w-3 h-3"}),s("maintenance.dueSoonCount",{count:t.warning_count})]}),t.due_count===0&&t.warning_count===0&&r.jsxs("span",{className:"px-2.5 py-1 bg-bambu-green/20 text-bambu-green text-xs font-medium rounded-full flex items-center gap-1.5",children:[r.jsx(_r,{className:"w-3 h-3"}),s("maintenance.allGood")]})]})]}),r.jsxs("button",{onClick:()=>l(!o),className:"flex items-center gap-1.5 px-3 py-1.5 text-sm text-bambu-gray hover:text-white hover:bg-bambu-dark rounded-lg transition-colors",children:[o?r.jsx(tl,{className:"w-4 h-4"}):r.jsx(Rn,{className:"w-4 h-4"}),s(o?"common.collapse":"common.expand")]})]}),r.jsxs("div",{className:"flex items-center gap-6 mt-4",children:[r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("div",{className:"p-2 bg-bambu-dark/50 rounded-lg",children:r.jsx(Xd,{className:"w-4 h-4 text-bambu-gray"})}),c?r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("input",{type:"number",value:u,onChange:w=>m(w.target.value),onKeyDown:w=>{w.key==="Enter"&&g(),w.key==="Escape"&&d(!1)},className:"w-24 px-2 py-1 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-sm",min:"0",step:"1",autoFocus:!0}),r.jsx("span",{className:"text-xs text-bambu-gray",children:s("common.hours")}),r.jsx(Me,{size:"sm",onClick:g,children:s("common.save")}),r.jsx(Me,{size:"sm",variant:"secondary",onClick:()=>d(!1),children:s("common.cancel")})]}):r.jsxs("button",{onClick:()=>{i("maintenance:update")&&(m(Math.round(t.total_print_hours).toString()),d(!0))},className:`group ${i("maintenance:update")?"":"cursor-not-allowed opacity-60"}`,title:i("maintenance:update")?void 0:s("maintenance.noPermissionEditHours"),children:[r.jsxs("div",{className:`text-sm font-medium text-white ${i("maintenance:update")?"group-hover:text-bambu-green":""} transition-colors flex items-center gap-1`,children:[Math.round(t.total_print_hours)," ",s("common.hours"),r.jsx(Eg,{className:`w-3 h-3 text-bambu-gray ${i("maintenance:update")?"group-hover:text-bambu-green":""}`})]}),r.jsx("div",{className:"text-xs text-bambu-gray",children:s("maintenance.totalPrintTime")})]})]}),r.jsx("div",{className:"w-px h-10 bg-bambu-dark-tertiary"}),f&&r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("div",{className:`p-2 rounded-lg ${f.is_due?"bg-red-500/20":"bg-amber-500/20"}`,children:(()=>{const w=yw(f.maintenance_type_icon);return r.jsx(w,{className:`w-4 h-4 ${f.is_due?"text-red-400":"text-amber-400"}`})})()}),r.jsxs("div",{children:[r.jsx("div",{className:`text-sm font-medium ${f.is_due?"text-red-400":"text-amber-400"}`,children:f.maintenance_type_name}),r.jsx("div",{className:`text-xs ${f.is_due?"text-red-400/70":"text-amber-400/70"}`,children:f.is_due?s("common.overdue"):s("maintenance.dueSoon")})]})]})]})]}),o&&r.jsx(At,{className:"pt-0 border-t border-bambu-dark-tertiary",children:r.jsx("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-3 pt-4",children:p.map(w=>r.jsx(Hat,{item:w,onPerform:e,onToggle:n,hasPermission:i,t:s},w.id))})})]})}function $at({overview:t,types:e,onUpdateInterval:n,onAddType:a,onUpdateType:i,onDeleteType:s,onRestoreDefaults:o,isRestoringDefaults:l,onAssignType:c,onRemoveItem:d,hasPermission:u,t:m}){const[p,f]=y.useState(null),[g,w]=y.useState(""),[b,x]=y.useState("hours"),[S,N]=y.useState(!1),[C,P]=y.useState(""),[T,A]=y.useState("100"),[F,_]=y.useState("hours"),[E,H]=y.useState("Wrench"),[I,U]=y.useState(""),[L,Q]=y.useState(new Set),[re,J]=y.useState(null),[ce,pe]=y.useState(null),ue=y.useMemo(()=>t?t.map(q=>({id:q.printer_id,name:q.printer_name})):[],[t]),X=q=>t?t.filter(R=>R.maintenance_items.some(ne=>ne.maintenance_type_id===q)).map(R=>({printerId:R.printer_id,printerName:R.printer_name,itemId:R.maintenance_items.find(ne=>ne.maintenance_type_id===q)?.id})):[],ae=q=>{if(!t)return[];const R=new Set(X(q).map(ne=>ne.printerId));return ue.filter(ne=>!R.has(ne.id))},[me,ge]=y.useState(null),[Pe,$]=y.useState(""),[W,D]=y.useState(""),[j,B]=y.useState("hours"),[Y,O]=y.useState("Wrench"),[se,z]=y.useState(""),G=q=>{ge(q),$(q.name),D(q.default_interval_hours.toString()),B(q.interval_type||"hours"),O(q.icon||"Wrench"),z(q.wiki_url||"")},K=()=>{me&&Pe.trim()&&parseFloat(W)>0&&(i(me.id,{name:Pe.trim(),default_interval_hours:parseFloat(W),interval_type:j,icon:Y,wiki_url:se.trim()||null}),ge(null))},Z=(q,R,ne)=>{const xe=parseFloat(g);if(!isNaN(xe)&&xe>0){const ve=Math.abs(xe-R)<.01?null:xe;n(q,{custom_interval_hours:ve,custom_interval_type:b!==ne?b:null})}f(null)},oe=q=>{q.preventDefault(),C.trim()&&parseFloat(T)>0&&L.size>0&&(a({name:C.trim(),default_interval_hours:parseFloat(T),interval_type:F,icon:E,wiki_url:I.trim()||null},Array.from(L)),P(""),A("100"),_("hours"),U(""),Q(new Set),N(!1))},ee=q=>{Q(R=>{const ne=new Set(R);return ne.has(q)?ne.delete(q):ne.add(q),ne})},fe=t?.map(q=>({printerId:q.printer_id,printerName:q.printer_name,items:q.maintenance_items.sort((R,ne)=>R.maintenance_type_id-ne.maintenance_type_id)})).sort((q,R)=>q.printerName.localeCompare(R.printerName))||[],de=e.filter(q=>q.is_system),le=e.filter(q=>!q.is_system);return r.jsxs("div",{className:"space-y-8",children:[r.jsxs("div",{children:[r.jsxs("div",{className:"flex items-center justify-between mb-4",children:[r.jsxs("div",{children:[r.jsx("h2",{className:"text-lg font-semibold text-white",children:m("maintenance.maintenanceTypes")}),r.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:m("maintenance.maintenanceTypesDescription")})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(Me,{variant:"secondary",onClick:o,disabled:!u("maintenance:delete")||l,title:u("maintenance:delete")?void 0:m("maintenance.noPermissionDeleteTypes"),children:m("maintenance.restoreDefaults")}),r.jsxs(Me,{onClick:()=>N(!S),disabled:!u("maintenance:create"),title:u("maintenance:create")?void 0:m("maintenance.noPermissionEditTypes"),children:[r.jsx(ir,{className:"w-4 h-4"}),m("maintenance.addCustomType")]})]})]}),S&&r.jsx(Ct,{className:"mb-6",children:r.jsx(At,{className:"py-4",children:r.jsxs("form",{onSubmit:oe,children:[r.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4",children:[r.jsxs("div",{className:"lg:col-span-2",children:[r.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:m("common.name")}),r.jsx("input",{type:"text",value:C,onChange:q=>P(q.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",placeholder:m("maintenance.exampleName"),autoFocus:!0})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:m("maintenance.intervalType")}),r.jsxs("select",{value:F,onChange:q=>{_(q.target.value),q.target.value==="days"?A("30"):A("100")},className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",children:[r.jsx("option",{value:"hours",children:m("maintenance.printHours")}),r.jsx("option",{value:"days",children:m("maintenance.calendarDays")})]})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:m("maintenance.intervalValue",{type:F==="days"?m("maintenance.calendarDays").toLowerCase():m("common.hours")})}),r.jsx("input",{type:"number",value:T,onChange:q=>A(q.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",min:"1"})]})]}),r.jsx("div",{className:"mt-4 flex items-end justify-between",children:r.jsxs("div",{children:[r.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:m("maintenance.icon")}),r.jsx("div",{className:"flex gap-1",children:Object.keys(V0).map(q=>{const R=V0[q];return r.jsx("button",{type:"button",onClick:()=>H(q),className:`p-2 rounded-lg transition-colors ${E===q?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary"}`,children:r.jsx(R,{className:"w-4 h-4"})},q)})})]})}),r.jsxs("div",{className:"mt-4",children:[r.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:m("maintenance.documentationLink")}),r.jsx("input",{type:"url",value:I,onChange:q=>U(q.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",placeholder:"https://wiki.bambulab.com/..."})]}),r.jsxs("div",{className:"mt-4",children:[r.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:m("maintenance.assignToPrinters")}),r.jsx("div",{className:"flex flex-wrap gap-2",children:ue.map(q=>r.jsx("button",{type:"button",onClick:()=>ee(q.id),className:`px-3 py-1.5 rounded-lg text-sm transition-colors ${L.has(q.id)?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary"}`,children:q.name},q.id))}),L.size===0&&r.jsx("p",{className:"text-xs text-orange-400 mt-1",children:m("maintenance.selectAtLeastOnePrinter")})]}),r.jsxs("div",{className:"mt-4 flex justify-end gap-2",children:[r.jsx(Me,{type:"button",variant:"secondary",onClick:()=>{N(!1),Q(new Set)},children:m("common.cancel")}),r.jsx(Me,{type:"submit",disabled:!C.trim()||L.size===0,children:m("maintenance.addType")})]})]})})}),r.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3",children:[de.map(q=>{const R=yw(q.icon),ne=q.interval_type||"hours";return r.jsx("div",{className:"bg-bambu-dark-secondary rounded-xl p-4 border border-bambu-dark-tertiary",children:r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("div",{className:"p-2.5 bg-bambu-dark rounded-lg",children:r.jsx(R,{className:"w-5 h-5 text-bambu-gray"})}),r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsx("div",{className:"text-sm font-medium text-white truncate",children:q.name}),r.jsxs("div",{className:"text-xs text-bambu-gray mt-0.5 flex items-center gap-1",children:[ne==="days"?r.jsx(Sa,{className:"w-3 h-3"}):r.jsx(Xd,{className:"w-3 h-3"}),mF(q.default_interval_hours,ne,m)]})]}),r.jsx("button",{onClick:()=>{u("maintenance:delete")&&pe(q)},disabled:!u("maintenance:delete"),title:u("maintenance:delete")?void 0:m("maintenance.noPermissionDeleteTypes"),className:`p-2 rounded-lg hover:bg-bambu-dark text-bambu-gray hover:text-red-400 transition-colors ${u("maintenance:delete")?"":"opacity-50 cursor-not-allowed"}`,children:r.jsx(Jt,{className:"w-4 h-4"})})]})},q.id)}),le.map(q=>{const R=yw(q.icon),ne=q.interval_type||"hours";if(me?.id===q.id)return r.jsx("div",{className:"bg-bambu-dark-secondary rounded-xl p-4 border border-bambu-green",children:r.jsxs("div",{className:"space-y-3",children:[r.jsx("input",{type:"text",value:Pe,onChange:be=>$(be.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",placeholder:m("common.name"),autoFocus:!0}),r.jsxs("div",{className:"flex gap-2",children:[r.jsxs("select",{value:j,onChange:be=>B(be.target.value),className:"flex-1 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",children:[r.jsx("option",{value:"hours",children:m("maintenance.printHours")}),r.jsx("option",{value:"days",children:m("maintenance.calendarDays")})]}),r.jsx("input",{type:"number",value:W,onChange:be=>D(be.target.value),className:"w-24 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",min:"1"})]}),r.jsx("div",{className:"flex flex-wrap gap-1",children:Object.keys(V0).map(be=>{const Ee=V0[be];return r.jsx("button",{type:"button",onClick:()=>O(be),className:`p-1.5 rounded transition-colors ${Y===be?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:r.jsx(Ee,{className:"w-3.5 h-3.5"})},be)})}),r.jsx("input",{type:"url",value:se,onChange:be=>z(be.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",placeholder:m("maintenance.documentationLink")}),r.jsxs("div",{className:"flex gap-2",children:[r.jsx(Me,{size:"sm",onClick:K,disabled:!Pe.trim(),children:m("common.save")}),r.jsx(Me,{size:"sm",variant:"secondary",onClick:()=>ge(null),children:m("common.cancel")})]})]})},q.id);const ve=X(q.id),Ce=ae(q.id),ye=re===q.id;return r.jsxs("div",{className:"bg-bambu-dark-secondary rounded-xl p-4 border border-bambu-green/30",children:[r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("div",{className:"p-2.5 bg-bambu-green/20 rounded-lg",children:r.jsx(R,{className:"w-5 h-5 text-bambu-green"})}),r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("span",{className:"text-sm font-medium text-white truncate",children:q.name}),r.jsx("span",{className:"px-1.5 py-0.5 bg-bambu-green/20 text-bambu-green text-[10px] font-medium rounded",children:m("maintenance.custom")})]}),r.jsxs("div",{className:"text-xs text-bambu-gray mt-0.5 flex items-center gap-1",children:[ne==="days"?r.jsx(Sa,{className:"w-3 h-3"}):r.jsx(Xd,{className:"w-3 h-3"}),mF(q.default_interval_hours,ne,m)]})]}),r.jsxs("button",{onClick:()=>J(ye?null:q.id),className:`px-2 py-1 rounded-lg border transition-colors flex items-center gap-1 ${ve.length>0?"border-bambu-green/50 bg-bambu-green/10 text-bambu-green hover:bg-bambu-green/20":"border-orange-400/50 bg-orange-400/10 text-orange-400 hover:bg-orange-400/20"}`,title:m("maintenance.printersAssignedClick",{count:ve.length}),children:[r.jsx(pr,{className:"w-3 h-3"}),r.jsx("span",{className:"text-xs font-medium",children:ve.length}),r.jsx(Rn,{className:`w-3 h-3 transition-transform ${ye?"rotate-180":""}`})]}),r.jsx("button",{onClick:()=>G(q),disabled:!u("maintenance:update"),title:u("maintenance:update")?void 0:m("maintenance.noPermissionEditTypes"),className:`p-2 rounded-lg hover:bg-bambu-dark text-bambu-gray hover:text-white transition-colors ${u("maintenance:update")?"":"opacity-50 cursor-not-allowed"}`,children:r.jsx(Eg,{className:"w-4 h-4"})}),r.jsx("button",{onClick:()=>{confirm(m("maintenance.deleteTypeConfirm",{name:q.name}))&&s(q.id)},disabled:!u("maintenance:delete"),title:u("maintenance:delete")?void 0:m("maintenance.noPermissionDeleteTypes"),className:`p-2 rounded-lg hover:bg-bambu-dark text-bambu-gray hover:text-red-400 transition-colors ${u("maintenance:delete")?"":"opacity-50 cursor-not-allowed"}`,children:r.jsx(Jt,{className:"w-4 h-4"})})]}),ye&&r.jsxs("div",{className:"mt-3 pt-3 border-t border-bambu-dark-tertiary",children:[r.jsx("p",{className:"text-xs text-bambu-gray mb-2",children:m("maintenance.assignedToPrinters")}),ve.length===0?r.jsx("p",{className:"text-xs text-orange-400",children:m("maintenance.noPrintersAssigned")}):r.jsx("div",{className:"flex flex-wrap gap-1 mb-2",children:ve.map(be=>r.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-1 bg-bambu-dark rounded text-xs text-white",children:[be.printerName,r.jsx("button",{onClick:()=>be.itemId&&d(be.itemId),disabled:!u("maintenance:delete"),title:u("maintenance:delete")?m("maintenance.removeFromPrinter"):m("maintenance.noPermissionRemovePrinter"),className:`ml-1 ${u("maintenance:delete")?"hover:text-red-400":"opacity-50 cursor-not-allowed"}`,children:"×"})]},be.printerId))}),Ce.length>0&&r.jsxs("div",{className:"flex flex-wrap gap-1",children:[r.jsx("span",{className:"text-xs text-bambu-gray mr-1",children:m("maintenance.addPrinterShort")}),Ce.map(be=>r.jsxs("button",{onClick:()=>c(be.id,q.id),disabled:!u("maintenance:create"),title:u("maintenance:create")?void 0:m("maintenance.noPermissionAssignPrinter"),className:`px-2 py-1 bg-bambu-dark rounded text-xs transition-colors ${u("maintenance:create")?"hover:bg-bambu-green/20 text-bambu-gray hover:text-bambu-green":"opacity-50 cursor-not-allowed text-bambu-gray"}`,children:["+ ",be.name]},be.id))]})]})]},q.id)})]})]}),fe.length>0&&r.jsxs("div",{children:[r.jsxs("div",{className:"mb-4",children:[r.jsx("h2",{className:"text-lg font-semibold text-white",children:m("maintenance.intervalOverrides")}),r.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:m("maintenance.intervalOverridesDescription")})]}),r.jsx("div",{className:"space-y-4",children:fe.map(q=>r.jsx(Ct,{children:r.jsxs(At,{className:"py-4",children:[r.jsx("h3",{className:"text-sm font-medium text-white mb-3",children:q.printerName}),r.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-2",children:q.items.map(R=>{const ne=yw(R.maintenance_type_icon),xe=e.find(Ee=>Ee.id===R.maintenance_type_id),ve=xe?.default_interval_hours||R.interval_hours,Ce=xe?.interval_type||"hours",ye=R.interval_type||"hours",be=p===R.id;return r.jsxs("div",{className:"flex items-center gap-2 p-2.5 bg-bambu-dark rounded-lg",children:[r.jsx(ne,{className:"w-4 h-4 text-bambu-gray shrink-0"}),r.jsx("span",{className:"text-xs text-bambu-gray flex-1 truncate",children:R.maintenance_type_name}),be?r.jsxs("div",{className:"flex items-center gap-1",children:[b==="days"?r.jsx(Sa,{className:"w-3.5 h-3.5 text-bambu-gray shrink-0"}):r.jsx(Xd,{className:"w-3.5 h-3.5 text-bambu-gray shrink-0"}),r.jsxs("select",{value:b,onChange:Ee=>x(Ee.target.value),className:"px-1.5 py-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-xs",children:[r.jsx("option",{value:"hours",children:m("maintenance.printHours")}),r.jsx("option",{value:"days",children:m("maintenance.calendarDays")})]}),r.jsx("input",{type:"number",value:g,onChange:Ee=>w(Ee.target.value),onKeyDown:Ee=>{Ee.key==="Enter"&&Z(R.id,ve,Ce),Ee.key==="Escape"&&f(null)},className:"w-16 px-2 py-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-xs",min:"1"}),r.jsx(Me,{size:"sm",onClick:()=>Z(R.id,ve,Ce),children:"OK"})]}):r.jsxs("button",{onClick:()=>{u("maintenance:update")&&(f(R.id),w(R.interval_hours.toString()),x(ye))},disabled:!u("maintenance:update"),title:u("maintenance:update")?void 0:m("maintenance.noPermissionEditIntervals"),className:`px-2 py-1 bg-bambu-dark-tertiary border border-bambu-dark-tertiary rounded text-xs font-medium text-white transition-colors flex items-center gap-1 ${u("maintenance:update")?"hover:bg-bambu-dark-secondary hover:border-bambu-green":"opacity-50 cursor-not-allowed"}`,children:[ye==="days"?r.jsx(Sa,{className:"w-3 h-3"}):r.jsx(Xd,{className:"w-3 h-3"}),mF(R.interval_hours,ye,m),r.jsx(Eg,{className:"w-3 h-3 text-bambu-gray"})]})]},R.id)})})]})},q.printerId))})]}),fe.length===0&&r.jsx(Ct,{children:r.jsxs(At,{className:"text-center py-12",children:[r.jsx(Zn,{className:"w-12 h-12 mx-auto mb-4 text-bambu-gray/30"}),r.jsx("p",{className:"text-bambu-gray",children:m("common.noPrinters")}),r.jsx("p",{className:"text-sm text-bambu-gray/70 mt-1",children:m("maintenance.intervalOverridesDescription")})]})}),ce&&r.jsx(vn,{title:m("maintenance.deleteSystemTypeTitle"),message:m("maintenance.deleteSystemTypeMessage",{name:ce.name}),confirmText:m("common.delete"),cancelText:m("common.cancel"),variant:"danger",cancelVariant:"primary",cardClassName:"bg-red-950/70 border border-red-800/70",onConfirm:()=>{s(ce.id),pe(null)},onCancel:()=>pe(null)})]})}function Vat(){const{t}=kt(),e=en(),{showToast:n}=rn(),{hasPermission:a}=cr(),[i,s]=y.useState("status"),{data:o,isLoading:l}=Ge({queryKey:["maintenanceOverview"],queryFn:ie.getMaintenanceOverview}),{data:c}=Ge({queryKey:["maintenanceTypes"],queryFn:ie.getMaintenanceTypes}),d=it({mutationFn:({id:T,notes:A})=>ie.performMaintenance(T,A),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]}),e.invalidateQueries({queryKey:["maintenanceSummary"]}),n(t("maintenance.maintenanceComplete"))},onError:T=>{n(T.message,"error")}}),u=it({mutationFn:({id:T,data:A})=>ie.updateMaintenanceItem(T,A),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]})},onError:T=>{n(T.message,"error")}}),m=it({mutationFn:({id:T,data:A})=>ie.updateMaintenanceType(T,A),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceTypes"]}),e.invalidateQueries({queryKey:["maintenanceOverview"]}),n(t("maintenance.typeUpdated"))},onError:T=>{n(T.message,"error")}}),p=it({mutationFn:ie.deleteMaintenanceType,onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceTypes"]}),e.invalidateQueries({queryKey:["maintenanceOverview"]}),n(t("maintenance.typeDeleted"))},onError:T=>{n(T.message,"error")}}),f=it({mutationFn:ie.restoreDefaultMaintenanceTypes,onSuccess:T=>{e.invalidateQueries({queryKey:["maintenanceTypes"]}),e.invalidateQueries({queryKey:["maintenanceOverview"]}),n(t("maintenance.defaultsRestored",{count:T.restored}))},onError:T=>{n(T.message,"error")}}),g=it({mutationFn:({printerId:T,hours:A})=>ie.setPrinterHours(T,A),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]}),e.invalidateQueries({queryKey:["maintenanceSummary"]}),n(t("maintenance.printHoursUpdated"))},onError:T=>{n(T.message,"error")}}),w=it({mutationFn:({printerId:T,typeId:A})=>ie.assignMaintenanceType(T,A),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]}),n(t("maintenance.printerAssigned"))},onError:T=>{n(T.message,"error")}}),b=it({mutationFn:ie.removeMaintenanceItem,onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]}),n(t("maintenance.printerRemoved"))},onError:T=>{n(T.message,"error")}}),x=T=>{d.mutate({id:T})},S=(T,A)=>{u.mutate({id:T,data:{enabled:A}})},N=(T,A)=>{g.mutate({printerId:T,hours:A})};if(l)return r.jsx("div",{className:"p-4 md:p-8 flex justify-center",children:r.jsx(pt,{className:"w-8 h-8 text-bambu-green animate-spin"})});const C=o?.reduce((T,A)=>T+A.due_count,0)||0,P=o?.reduce((T,A)=>T+A.warning_count,0)||0;return r.jsxs("div",{className:"p-4 md:p-8",children:[r.jsxs("div",{className:"mb-6",children:[r.jsxs("h1",{className:"text-2xl font-bold text-white flex items-center gap-3",children:[r.jsx(qh,{className:"w-7 h-7 text-bambu-green"}),t("maintenance.title")]}),r.jsx("p",{className:"text-bambu-gray mt-1",children:i==="status"?r.jsxs(r.Fragment,{children:[C>0&&r.jsx("span",{className:"text-red-400",children:t("maintenance.dueCount",{count:C})}),C>0&&P>0&&" · ",P>0&&r.jsx("span",{className:"text-amber-400",children:t("maintenance.warningCount",{count:P})}),C===0&&P===0&&r.jsx("span",{className:"text-bambu-green",children:t("maintenance.allOk")})]}):t("maintenance.configureSettings")})]}),r.jsxs("div",{className:"flex gap-1 mb-6 border-b border-bambu-dark-tertiary",children:[r.jsx("button",{onClick:()=>s("status"),className:`px-4 py-2 text-sm font-medium border-b-2 -mb-px transition-colors ${i==="status"?"text-bambu-green border-bambu-green":"text-bambu-gray border-transparent hover:text-white"}`,children:t("maintenance.statusTab")}),r.jsx("button",{onClick:()=>s("settings"),className:`px-4 py-2 text-sm font-medium border-b-2 -mb-px transition-colors ${i==="settings"?"text-bambu-green border-bambu-green":"text-bambu-gray border-transparent hover:text-white"}`,children:t("maintenance.settingsTab")})]}),i==="status"?r.jsx("div",{className:"space-y-6",children:o&&o.length>0?[...o].sort((T,A)=>{const F=T.due_count*10+T.warning_count,_=A.due_count*10+A.warning_count;return F!==_?_-F:T.printer_name.localeCompare(A.printer_name)}).map(T=>r.jsx(qat,{overview:T,onPerform:x,onToggle:S,onSetHours:N,hasPermission:a,t},T.printer_id)):r.jsx(Ct,{children:r.jsxs(At,{className:"text-center py-16",children:[r.jsx(qh,{className:"w-16 h-16 mx-auto mb-4 text-bambu-gray/30"}),r.jsx("p",{className:"text-lg font-medium text-white mb-2",children:t("common.noPrinters")}),r.jsx("p",{className:"text-bambu-gray",children:t("maintenance.configureSettings")})]})})}):r.jsx($at,{overview:o,types:c||[],onUpdateInterval:(T,A)=>u.mutate({id:T,data:A}),onAddType:async(T,A)=>{const F=await ie.createMaintenanceType(T);for(const _ of A)await ie.assignMaintenanceType(_,F.id);e.invalidateQueries({queryKey:["maintenanceTypes"]}),e.invalidateQueries({queryKey:["maintenanceOverview"]}),n(t("maintenance.typeUpdated"))},onUpdateType:(T,A)=>m.mutate({id:T,data:A}),onDeleteType:T=>p.mutate(T),onRestoreDefaults:()=>f.mutate(),isRestoringDefaults:f.isPending,onAssignType:(T,A)=>w.mutate({printerId:T,typeId:A}),onRemoveItem:T=>b.mutate(T),hasPermission:a,t})]})}const mQ=["#ef4444","#f97316","#eab308","#22c55e","#06b6d4","#3b82f6","#8b5cf6","#ec4899","#6b7280"];function Rce({project:t,onClose:e,onSave:n,isLoading:a,currencySymbol:i,t:s}){const[o,l]=y.useState(t?.name||""),[c,d]=y.useState(t?.description||""),[u,m]=y.useState(t?.color||mQ[0]),[p,f]=y.useState(t?.target_count?.toString()||""),[g,w]=y.useState(t?.target_parts_count?.toString()||""),[b,x]=y.useState(t?.status||"active"),[S,N]=y.useState(t?.tags||""),[C,P]=y.useState(t?.due_date?.split("T")[0]||""),[T,A]=y.useState(t?.priority||"normal"),[F,_]=y.useState(t?.budget?.toString()||""),[E,H]=y.useState(t?.url||""),[I,U]=y.useState(null),L=en(),[Q,re]=y.useState(t?.cover_image_filename||null),J=y.useRef(null),[ce,pe]=y.useState(!1),[ue,X]=y.useState(0),ae=async Pe=>{const $=Pe.target.files?.[0];if(!(!$||!t)){pe(!0);try{const W=await ie.uploadProjectCoverImage(t.id,$);re(W.filename),X(D=>D+1),L.invalidateQueries({queryKey:["projects"]})}catch{}finally{pe(!1),J.current&&(J.current.value="")}}},me=async()=>{if(t){pe(!0);try{await ie.deleteProjectCoverImage(t.id),re(null),X(Pe=>Pe+1),L.invalidateQueries({queryKey:["projects"]})}finally{pe(!1)}}},ge=Pe=>{Pe.preventDefault();const $=E.trim();if($&&!/^https?:\/\//i.test($)){U(s("projects.urlInvalid"));return}U(null),n({name:o.trim(),description:c.trim()||void 0,color:u,target_count:p?parseInt(p,10):void 0,target_parts_count:g?parseInt(g,10):void 0,tags:S.trim()||void 0,due_date:C||void 0,priority:T,budget:F.trim()?parseFloat(F):null,url:t?$||null:$||void 0,...t&&{status:b}})};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-md border border-bambu-dark-tertiary",children:[r.jsx("div",{className:"p-4 border-b border-bambu-dark-tertiary",children:r.jsx("h2",{className:"text-lg font-semibold text-white",children:s(t?"projects.editProject":"projects.newProject")})}),r.jsxs("form",{onSubmit:ge,className:"p-4 space-y-4",children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("common.name")}),r.jsx("input",{type:"text",value:o,onChange:Pe=>l(Pe.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:s("projects.namePlaceholder"),required:!0})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("common.description")}),r.jsx("textarea",{value:c,onChange:Pe=>d(Pe.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green resize-none",placeholder:s("projects.descriptionPlaceholder"),rows:2})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("projects.urlLabel")}),r.jsx("input",{type:"url",value:E,onChange:Pe=>{H(Pe.target.value),I&&U(null)},className:`w-full bg-bambu-dark border rounded px-3 py-2 text-white placeholder-bambu-gray focus:outline-none ${I?"border-red-500 focus:border-red-500":"border-bambu-dark-tertiary focus:border-bambu-green"}`,placeholder:s("projects.urlPlaceholder"),maxLength:2048}),I&&r.jsx("p",{className:"text-xs text-red-400 mt-1",children:I})]}),t&&r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("projects.coverImageLabel")}),r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("div",{className:"w-20 h-20 rounded bg-bambu-dark border border-bambu-dark-tertiary overflow-hidden flex items-center justify-center flex-shrink-0",children:Q?r.jsx("img",{src:`${ie.getProjectCoverImageUrl(t.id)}?v=${ue}`,alt:s("projects.coverImageAlt"),className:"w-full h-full object-cover"}):r.jsx(du,{className:"w-6 h-6 text-bambu-gray"})}),r.jsxs("div",{className:"flex flex-col gap-2",children:[r.jsx("input",{ref:J,type:"file",accept:"image/jpeg,image/png,image/gif,image/webp",onChange:ae,className:"hidden"}),r.jsxs(Me,{type:"button",variant:"secondary",onClick:()=>J.current?.click(),disabled:ce,children:[ce?r.jsx(pt,{className:"w-4 h-4 animate-spin"}):r.jsx(ka,{className:"w-4 h-4 mr-1"}),s(Q?"projects.coverImageReplace":"projects.coverImageUpload")]}),Q&&r.jsxs(Me,{type:"button",variant:"secondary",onClick:me,disabled:ce,children:[r.jsx(Ht,{className:"w-4 h-4 mr-1"}),s("projects.coverImageRemove")]})]})]})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("projects.color")}),r.jsx("div",{className:"flex gap-2 flex-wrap",children:mQ.map(Pe=>r.jsx("button",{type:"button",onClick:()=>m(Pe),className:`w-8 h-8 rounded-full transition-transform ${u===Pe?"ring-2 ring-white ring-offset-2 ring-offset-bambu-dark-secondary scale-110":""}`,style:{backgroundColor:Pe}},Pe))})]}),r.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("projects.targetPlates")}),r.jsx("input",{type:"number",value:p,onChange:Pe=>f(Pe.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:s("projects.targetPlatesPlaceholder"),min:"1"}),r.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:s("projects.targetPlatesHelp")})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("projects.targetParts")}),r.jsx("input",{type:"number",value:g,onChange:Pe=>w(Pe.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:s("projects.targetPartsPlaceholder"),min:"1"}),r.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:s("projects.targetPartsHelp")})]})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("projects.tagsLabel")}),r.jsx("input",{type:"text",value:S,onChange:Pe=>N(Pe.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:s("projects.tagsPlaceholder")})]}),r.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("projects.dueDate")}),r.jsx("input",{type:"date",value:C,onChange:Pe=>P(Pe.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white focus:outline-none focus:border-bambu-green"})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("projects.priority")}),r.jsxs("select",{value:T,onChange:Pe=>A(Pe.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white focus:outline-none focus:border-bambu-green",children:[r.jsx("option",{value:"low",children:s("projects.priorityLow")}),r.jsx("option",{value:"normal",children:s("projects.priorityNormal")}),r.jsx("option",{value:"high",children:s("projects.priorityHigh")}),r.jsx("option",{value:"urgent",children:s("projects.priorityUrgent")})]})]})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("projectDetail.cost.budget")}),r.jsxs("div",{className:"relative",children:[r.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-bambu-gray pointer-events-none",children:i}),r.jsx("input",{type:"number",step:"0.01",min:"0",value:F,onChange:Pe=>_(Pe.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded pl-8 pr-3 py-2 text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:"0.00"})]})]}),t&&r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("common.status")}),r.jsxs("select",{value:b,onChange:Pe=>x(Pe.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white focus:outline-none focus:border-bambu-green",children:[r.jsx("option",{value:"active",children:s("projects.statusActive")}),r.jsx("option",{value:"completed",children:s("projects.statusCompleted")}),r.jsx("option",{value:"archived",children:s("projects.statusArchived")})]})]}),r.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[r.jsx(Me,{type:"button",variant:"secondary",onClick:e,children:s("common.cancel")}),r.jsx(Me,{type:"submit",disabled:!o.trim()||a,children:a?r.jsx(pt,{className:"w-4 h-4 animate-spin"}):s(t?"common.save":"projects.create")})]})]})]})})}function Gat({projectId:t,altText:e}){const n=y.useRef(null),[a,i]=y.useState(!1),[s,o]=y.useState(null),l=()=>{if(!n.current)return;const d=n.current.getBoundingClientRect(),u=384,m=8,p=window.innerWidth,f=window.innerHeight;let g=d.right+m;g+u>p-8&&(g=d.left-u-m);let w=d.top;w+u>f-8&&(w=f-u-8),w<8&&(w=8),o({left:g,top:w}),i(!0)},c=()=>i(!1);return r.jsxs("div",{ref:n,className:"relative flex-shrink-0",onMouseEnter:l,onMouseLeave:c,onClick:d=>d.stopPropagation(),children:[r.jsx("div",{className:"w-10 h-10 rounded-lg overflow-hidden bg-bambu-dark border border-bambu-dark-tertiary",children:r.jsx("img",{src:ie.getProjectCoverImageUrl(t),alt:e,className:"w-full h-full object-cover",loading:"lazy"})}),a&&s&&hc.createPortal(r.jsx("div",{className:"fixed z-[100] w-96 h-96 rounded-lg overflow-hidden border border-bambu-dark-tertiary shadow-2xl bg-bambu-dark pointer-events-none",style:{left:s.left,top:s.top},"aria-hidden":"true",children:r.jsx("img",{src:ie.getProjectCoverImageUrl(t),alt:"",className:"w-full h-full object-contain",loading:"lazy"})}),document.body)]})}function Wat({project:t,onClick:e,onEdit:n,onDelete:a,hasPermission:i,t:s}){const o=t.target_count?Math.round(t.archive_count/t.target_count*100):0,l=t.target_parts_count?Math.round(t.completed_count/t.target_parts_count*100):0,c=t.status==="completed",d=t.status==="archived",[u,m]=y.useState(!1),f=c?{icon:ad,color:"text-bambu-green",bg:"bg-bambu-green/10"}:d?{icon:ro,color:"text-bambu-gray",bg:"bg-bambu-gray/10"}:t.queue_count>0?{icon:Zn,color:"text-blue-400",bg:"bg-blue-400/10"}:{icon:ao,color:"text-bambu-gray",bg:"bg-bambu-gray/10"};return r.jsxs("div",{className:"group relative bg-gradient-to-br from-bambu-card to-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary hover:border-bambu-green/50 hover:shadow-lg hover:shadow-bambu-green/5 transition-all duration-300 cursor-pointer overflow-hidden",onClick:e,children:[r.jsx("div",{className:"absolute top-0 left-0 w-1.5 h-full",style:{backgroundColor:t.color||"#6b7280",boxShadow:`0 0 12px ${t.color||"#6b7280"}40`}}),r.jsxs("div",{className:"p-5 pl-6",children:[r.jsxs("div",{className:"flex items-start justify-between mb-4",children:[r.jsxs("div",{className:"flex items-center gap-3 min-w-0 flex-1",children:[t.cover_image_filename?r.jsx(Gat,{projectId:t.id,altText:s("projects.coverImageAlt")}):r.jsx("div",{className:`p-2 rounded-lg ${f.bg} flex-shrink-0`,children:r.jsx(f.icon,{className:`w-5 h-5 ${f.color}`})}),r.jsxs("div",{className:"min-w-0 flex-1",children:[r.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[r.jsx("h3",{className:"font-semibold text-white truncate",children:t.name}),t.url&&r.jsx("a",{href:t.url,target:"_blank",rel:"noopener noreferrer",onClick:g=>g.stopPropagation(),title:t.url,"aria-label":s("projects.openExternalUrl"),className:"inline-flex items-center justify-center w-6 h-6 rounded bg-bambu-dark border border-bambu-dark-tertiary text-bambu-green hover:bg-bambu-green/10 hover:border-bambu-green transition-colors flex-shrink-0",children:r.jsx(Lr,{className:"w-3.5 h-3.5"})}),t.target_parts_count?r.jsxs("span",{className:`text-xs px-2 py-0.5 rounded-full whitespace-nowrap font-medium ${l>=100?"bg-bambu-green/20 text-bambu-green":"bg-bambu-dark text-bambu-gray"}`,children:[t.completed_count,"/",t.target_parts_count," ",s("projects.parts")]}):t.target_count?r.jsxs("span",{className:`text-xs px-2 py-0.5 rounded-full whitespace-nowrap font-medium ${o>=100?"bg-bambu-green/20 text-bambu-green":"bg-bambu-dark text-bambu-gray"}`,children:[t.archive_count,"/",t.target_count," ",s("projects.plates")]}):t.completed_count>0?r.jsxs("span",{className:"text-xs px-2 py-0.5 rounded-full whitespace-nowrap font-medium bg-bambu-dark text-bambu-gray",children:[t.completed_count," ",s("projects.parts")]}):null,c&&r.jsx("span",{className:"text-xs bg-bambu-green/20 text-bambu-green px-2 py-0.5 rounded-full whitespace-nowrap",children:s("projects.done")}),d&&r.jsx("span",{className:"text-xs bg-bambu-gray/20 text-bambu-gray px-2 py-0.5 rounded-full whitespace-nowrap",children:s("projects.statusArchived")})]}),t.description&&r.jsx("p",{className:"text-sm text-bambu-gray/70 mt-1 line-clamp-1",children:t.description}),t.archives&&t.archives.length>0&&(()=>{const g=t.archives.map(S=>S.filament_type).filter(Boolean).flatMap(S=>S.split(",").map(N=>N.trim())).filter(Boolean),w=[...new Set(g)],b=t.archives.map(S=>S.filament_color).filter(Boolean).flatMap(S=>S.split(",").map(N=>N.trim())).filter(S=>S.startsWith("#")||/^[0-9A-Fa-f]{6}$/.test(S)),x=[...new Set(b)];return w.length===0&&x.length===0?null:r.jsxs("div",{className:"flex items-center gap-2 mt-1.5",children:[w.slice(0,3).map(S=>r.jsx("span",{className:"text-[10px] px-1.5 py-0.5 bg-bambu-dark text-bambu-gray rounded",children:S},S)),x.length>0&&r.jsxs("div",{className:"flex items-center gap-0.5",children:[x.slice(0,5).map(S=>r.jsx("div",{className:"w-3 h-3 rounded-full border border-black/20",style:{backgroundColor:S.startsWith("#")?S:`#${S}`},title:S},S)),x.length>5&&r.jsxs("span",{className:"text-[10px] text-bambu-gray ml-0.5",children:["+",x.length-5]})]})]})})()]})]}),r.jsxs("div",{className:"relative",onClick:g=>g.stopPropagation(),children:[r.jsx("button",{className:"p-1.5 rounded-lg hover:bg-bambu-dark text-bambu-gray hover:text-white transition-colors opacity-0 group-hover:opacity-100",onClick:()=>m(!u),children:r.jsx(ym,{className:"w-4 h-4"})}),u&&r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>m(!1)}),r.jsxs("div",{className:"absolute right-0 top-8 z-20 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl py-1 min-w-[120px]",children:[r.jsxs("button",{className:`w-full px-3 py-2 text-left text-sm flex items-center gap-2 ${i("projects:update")?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{i("projects:update")&&(n(),m(!1))},disabled:!i("projects:update"),title:i("projects:update")?void 0:s("projects.noEditPermission"),children:[r.jsx(Eg,{className:"w-4 h-4"}),s("common.edit")]}),r.jsxs("button",{className:`w-full px-3 py-2 text-left text-sm flex items-center gap-2 ${i("projects:delete")?"text-red-400 hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{i("projects:delete")&&(a(),m(!1))},disabled:!i("projects:delete"),title:i("projects:delete")?void 0:s("projects.noDeletePermission"),children:[r.jsx(Jt,{className:"w-4 h-4"}),s("common.delete")]})]})]})]})]}),r.jsx("div",{className:"mb-4",children:t.target_count||t.target_parts_count?r.jsxs("div",{className:"space-y-3",children:[t.target_count&&r.jsxs("div",{children:[r.jsxs("div",{className:"flex items-center justify-between text-xs mb-1",children:[r.jsx("span",{className:"text-bambu-gray",children:s("projects.plates")}),r.jsxs("span",{className:o>=100?"text-bambu-green font-medium":"text-white",children:[t.archive_count," / ",t.target_count]})]}),r.jsx("div",{className:"h-2 bg-bambu-dark/80 rounded-full overflow-hidden backdrop-blur-sm",children:r.jsx("div",{className:"h-full transition-all duration-500 ease-out rounded-full relative",style:{width:`${Math.min(o,100)}%`,background:o>=100?"linear-gradient(90deg, #22c55e, #4ade80)":`linear-gradient(90deg, ${t.color||"#6b7280"}, ${t.color||"#6b7280"}cc)`,boxShadow:`0 0 8px ${o>=100?"#22c55e":t.color||"#6b7280"}60`}})})]}),t.target_parts_count&&r.jsxs("div",{children:[r.jsxs("div",{className:"flex items-center justify-between text-xs mb-1",children:[r.jsx("span",{className:"text-bambu-gray",children:s("projects.parts")}),r.jsxs("span",{className:l>=100?"text-bambu-green font-medium":"text-white",children:[t.completed_count," / ",t.target_parts_count]})]}),r.jsx("div",{className:"h-2 bg-bambu-dark/80 rounded-full overflow-hidden backdrop-blur-sm",children:r.jsx("div",{className:"h-full transition-all duration-500 ease-out rounded-full relative",style:{width:`${Math.min(l,100)}%`,background:l>=100?"linear-gradient(90deg, #22c55e, #4ade80)":`linear-gradient(90deg, ${t.color||"#6b7280"}, ${t.color||"#6b7280"}cc)`,boxShadow:`0 0 8px ${l>=100?"#22c55e":t.color||"#6b7280"}60`}})})]}),t.failed_count>0&&r.jsxs("div",{className:"text-xs text-red-400",children:[t.failed_count," ",s("projects.failed")]})]}):t.completed_count>0||t.failed_count>0?r.jsxs("div",{className:"flex items-center gap-4 text-xs",children:[t.completed_count>0&&r.jsxs("div",{className:"flex items-center gap-1.5 text-bambu-gray",children:[r.jsx(ro,{className:"w-3.5 h-3.5"}),r.jsxs("span",{children:[t.completed_count," ",s("projects.completed")]})]}),t.failed_count>0&&r.jsxs("div",{className:"flex items-center gap-1.5 text-red-400",children:[r.jsx(Nn,{className:"w-3.5 h-3.5"}),r.jsxs("span",{children:[t.failed_count," ",s("projects.failed")]})]}),t.queue_count>0&&r.jsxs("div",{className:"flex items-center gap-1.5 text-blue-400",children:[r.jsx(Zn,{className:"w-3.5 h-3.5"}),r.jsxs("span",{children:[t.queue_count," ",s("projects.inQueue")]})]})]}):r.jsx("div",{className:"text-xs text-bambu-gray/60 italic",children:s("projects.noPrintsYet")})}),t.archives&&t.archives.length>0&&r.jsxs("div",{className:"mb-4",children:[r.jsx("div",{className:"grid grid-cols-4 gap-1.5",children:t.archives.slice(0,4).map(g=>r.jsxs("div",{className:"relative aspect-square rounded-lg bg-bambu-dark overflow-hidden border border-bambu-dark-tertiary",title:g.print_name||"Unknown",children:[g.thumbnail_path?r.jsx("img",{src:ie.getArchiveThumbnail(g.id),alt:g.print_name||"",className:"w-full h-full object-cover"}):r.jsx("div",{className:"w-full h-full flex items-center justify-center text-bambu-gray/50",children:r.jsx(Br,{className:"w-6 h-6"})}),g.status==="failed"&&r.jsx("div",{className:"absolute inset-0 bg-red-500/40 flex items-center justify-center",children:r.jsx(Nn,{className:"w-4 h-4 text-white"})})]},g.id))}),t.archive_count>4&&r.jsx("p",{className:"text-xs text-bambu-gray mt-1.5 text-center",children:s("common.more",{count:t.archive_count-4})})]}),r.jsxs("div",{className:"flex items-center justify-between pt-3 border-t border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"flex items-center gap-4 text-xs text-bambu-gray",children:[r.jsxs("div",{className:"flex items-center gap-1.5",title:s("projects.printJobs"),children:[r.jsx(oa,{className:"w-3.5 h-3.5 text-blue-400"}),r.jsxs("span",{children:[t.archive_count," ",s("projects.plates")]})]}),r.jsxs("div",{className:"flex items-center gap-1.5",title:s("projects.partsPrinted"),children:[r.jsx(Br,{className:"w-3.5 h-3.5 text-bambu-green"}),r.jsxs("span",{children:[t.completed_count," ",s("projects.parts")]})]}),t.failed_count>0&&r.jsxs("div",{className:"flex items-center gap-1.5 text-red-400",title:s("projects.failedParts"),children:[r.jsx(Nn,{className:"w-3.5 h-3.5"}),r.jsx("span",{children:t.failed_count})]}),t.queue_count>0&&r.jsxs("div",{className:"flex items-center gap-1.5 text-yellow-400",title:s("projects.inQueue"),children:[r.jsx(qF,{className:"w-3.5 h-3.5"}),r.jsx("span",{children:t.queue_count})]})]}),r.jsx(Va,{className:"w-4 h-4 text-bambu-gray/50 group-hover:text-bambu-gray transition-colors"})]})]})]})}function Kat(){const{t}=kt(),e=Di(),n=en(),{showToast:a}=rn(),{hasPermission:i}=cr(),[s,o]=y.useState(!1),[l,c]=y.useState(),[d,u]=y.useState("active"),[m,p]=y.useState(null),{data:f}=Ge({queryKey:["settings"],queryFn:ie.getSettings}),g=Vo(f?.currency||"USD"),{data:w,isLoading:b}=Ge({queryKey:["projects",d==="all"?void 0:d],queryFn:()=>ie.getProjects(d==="all"?void 0:d)}),x=it({mutationFn:Q=>ie.createProject(Q),onSuccess:()=>{n.invalidateQueries({queryKey:["projects"]}),o(!1),a(t("projects.toast.created"),"success")},onError:Q=>{a(Q.message,"error")}}),S=it({mutationFn:({id:Q,data:re})=>ie.updateProject(Q,re),onSuccess:()=>{n.invalidateQueries({queryKey:["projects"]}),o(!1),c(void 0),a(t("projects.toast.updated"),"success")},onError:Q=>{a(Q.message,"error")}}),N=it({mutationFn:Q=>ie.deleteProject(Q),onSuccess:()=>{p(null),a(t("projects.toast.deleted"),"success"),setTimeout(()=>window.location.reload(),100)},onError:Q=>{p(null),a(Q.message,"error")}}),C=it({mutationFn:Q=>ie.importProject(Q),onSuccess:()=>{n.invalidateQueries({queryKey:["projects"]}),a(t("projects.toast.imported"),"success")},onError:Q=>{a(Q.message,"error")}}),P=y.useRef(null),T=async()=>{try{const Q=await ie.getProjects(),re=await Promise.all(Q.map(async ue=>await ie.exportProjectJson(ue.id))),J=new Blob([JSON.stringify(re,null,2)],{type:"application/json"}),ce=URL.createObjectURL(J),pe=document.createElement("a");pe.href=ce,pe.download=`bambuddy_projects_${new Date().toISOString().split("T")[0]}.json`,pe.click(),URL.revokeObjectURL(ce),a(t("projects.toast.exported"),"success")}catch(Q){a(Q.message,"error")}},A=()=>{P.current?.click()},F=async Q=>{const re=Q.target.files?.[0];if(re){try{if(re.name.toLowerCase().endsWith(".zip"))await ie.importProjectFile(re),n.invalidateQueries({queryKey:["projects"]}),a(t("projects.toast.imported"),"success");else{const ce=await re.text(),pe=JSON.parse(ce),ue=Array.isArray(pe)?pe:[pe];for(const X of ue)await C.mutateAsync(X);ue.length>1&&a(t("projects.toast.multipleImported",{count:ue.length}),"success")}}catch(J){a(`${t("projects.toast.importFailed")}: ${J.message}`,"error")}Q.target.value=""}},_=Q=>{l?S.mutate({id:l.id,data:Q}):x.mutate(Q)},E=Q=>{c(Q),o(!0)},H=Q=>{e(`/projects/${Q.id}`)},I=Q=>{p(Q)},U=()=>{m!==null&&N.mutate(m)},L=w?.reduce((Q,re)=>(Q[re.status]=(Q[re.status]||0)+1,Q.all=(Q.all||0)+1,Q),{})||{};return r.jsxs("div",{className:"p-4 md:p-8 space-y-8",children:[r.jsx("input",{ref:P,type:"file",accept:".json,.zip",onChange:F,className:"hidden"}),r.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4",children:[r.jsxs("div",{children:[r.jsxs("h1",{className:"text-2xl font-bold text-white flex items-center gap-3",children:[r.jsx(ao,{className:"w-7 h-7 text-bambu-green"}),t("projects.title")]}),r.jsx("p",{className:"text-bambu-gray mt-1",children:t("projects.subtitle")})]}),r.jsxs("div",{className:"flex gap-2",children:[r.jsxs(Me,{variant:"secondary",onClick:A,disabled:!i("projects:create"),title:i("projects:create")?t("projects.importProject"):t("projects.noImportPermission"),children:[r.jsx(ka,{className:"w-4 h-4 mr-2"}),t("projects.import")]}),r.jsxs(Me,{variant:"secondary",onClick:T,disabled:!i("projects:read"),title:i("projects:read")?t("projects.exportAll"):t("projects.noExportPermission"),children:[r.jsx(Yr,{className:"w-4 h-4 mr-2"}),t("projects.export")]}),r.jsxs(Me,{onClick:()=>o(!0),className:"sm:w-auto w-full",disabled:!i("projects:create"),title:i("projects:create")?void 0:t("projects.noCreatePermission"),children:[r.jsx(ir,{className:"w-4 h-4 mr-2"}),t("projects.newProject")]})]})]}),r.jsx("div",{className:"flex gap-1 p-1 bg-bambu-dark rounded-xl w-fit",children:[{key:"active",label:t("projects.statusActive"),icon:Zn},{key:"completed",label:t("projects.statusCompleted"),icon:ad},{key:"archived",label:t("projects.statusArchived"),icon:ro},{key:"all",label:t("common.all"),icon:ao}].map(({key:Q,label:re,icon:J})=>r.jsxs("button",{onClick:()=>u(Q),className:`flex items-center gap-2 px-4 py-2 text-sm rounded-lg transition-all ${d===Q?"bg-bambu-card text-white shadow-sm":"text-bambu-gray hover:text-white"}`,children:[r.jsx(J,{className:"w-4 h-4"}),r.jsx("span",{children:re}),L[Q]>0&&r.jsx("span",{className:`text-xs px-1.5 py-0.5 rounded-full ${d===Q?"bg-bambu-green/20 text-bambu-green":"bg-bambu-dark-tertiary"}`,children:L[Q]})]},Q))}),b?r.jsx("div",{className:"flex items-center justify-center py-20",children:r.jsxs("div",{className:"flex flex-col items-center gap-3",children:[r.jsx(pt,{className:"w-8 h-8 animate-spin text-bambu-green"}),r.jsx("p",{className:"text-sm text-bambu-gray",children:t("projects.loading")})]})}):w?.length===0?r.jsxs("div",{className:"flex flex-col items-center justify-center py-20 px-4",children:[r.jsx("div",{className:"p-4 bg-bambu-dark rounded-2xl mb-4",children:r.jsx(ao,{className:"w-12 h-12 text-bambu-gray/50"})}),r.jsx("h3",{className:"text-lg font-medium text-white mb-2",children:d==="all"?t("projects.noProjects"):t("projects.noProjectsFiltered",{status:d})}),r.jsx("p",{className:"text-bambu-gray text-center max-w-md mb-6",children:d==="all"?t("projects.createFirst"):t("projects.noProjectsFilteredHelp",{status:d})}),d==="all"&&r.jsxs(Me,{onClick:()=>o(!0),disabled:!i("projects:create"),title:i("projects:create")?void 0:t("projects.noCreatePermission"),children:[r.jsx(ir,{className:"w-4 h-4 mr-2"}),t("projects.createFirstButton")]})]}):r.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-8",children:w?.map(Q=>r.jsx(Wat,{project:Q,onClick:()=>H(Q),onEdit:()=>E(Q),onDelete:()=>I(Q.id),hasPermission:i,t},Q.id))}),m!==null&&r.jsx(vn,{title:t("projects.deleteProject"),message:t("projects.deleteConfirm"),confirmText:t("projects.deleteProject"),variant:"danger",onConfirm:U,onCancel:()=>p(null)}),s&&r.jsx(Rce,{project:l,onClose:()=>{o(!1),c(void 0)},onSave:_,isLoading:x.isPending||S.isPending,currencySymbol:g,t})]})}function Yat(t){const e=t.toLowerCase();return e.endsWith(".gcode")||e.endsWith(".gcode.3mf")}function Xat(t){return t>=1e3?`${(t/1e3).toFixed(2)}kg`:`${Math.round(t)}g`}function Qat({status:t,t:e}){const n={active:"bg-bambu-green/20 text-bambu-green",completed:"bg-blue-500/20 text-blue-400",archived:"bg-bambu-gray/20 text-bambu-gray"},a=n[t]||n.active,i={active:e("projectDetail.status.active"),completed:e("projectDetail.status.completed"),archived:e("projectDetail.status.archived")};return r.jsx("span",{className:`px-2 py-1 rounded text-sm font-medium ${a}`,children:i[t]||t.charAt(0).toUpperCase()+t.slice(1)})}function pQ({icon:t,label:e,value:n,subValue:a,hint:i,color:s="text-bambu-gray"}){return r.jsx(Ct,{children:r.jsx(At,{className:"p-4",children:r.jsxs("div",{className:"flex items-center gap-3",title:i,children:[r.jsx("div",{className:`p-2 rounded-lg bg-bambu-dark ${s}`,children:r.jsx(t,{className:"w-5 h-5"})}),r.jsxs("div",{children:[r.jsx("p",{className:"text-sm text-bambu-gray",children:e}),r.jsx("p",{className:"text-xl font-semibold text-white",children:n}),a&&r.jsx("p",{className:"text-xs text-bambu-gray/70",children:a})]})]})})})}function Zat({archives:t,t:e}){return t.length===0?r.jsxs("div",{className:"text-center py-8 text-bambu-gray",children:[r.jsx(Br,{className:"w-12 h-12 mx-auto mb-2 opacity-50"}),r.jsx("p",{children:e("projectDetail.noPrints")})]}):r.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6 gap-3",children:t.map(n=>r.jsxs(Is,{to:`/archives?search=${encodeURIComponent(n.print_name||"")}`,className:"group relative aspect-square rounded-lg bg-bambu-dark border border-bambu-dark-tertiary overflow-hidden hover:border-bambu-green transition-colors",children:[n.thumbnail_path?r.jsx("img",{src:ie.getArchiveThumbnail(n.id),alt:n.print_name||"Print",className:"w-full h-full object-cover"}):r.jsx("div",{className:"w-full h-full flex items-center justify-center text-bambu-gray",children:r.jsx(Br,{className:"w-8 h-8"})}),n.status==="failed"&&r.jsx("div",{className:"absolute inset-0 bg-red-500/30 flex items-center justify-center",children:r.jsx(Da,{className:"w-8 h-8 text-white"})}),n.status==="completed"&&r.jsx("div",{className:"absolute top-1 right-1",children:r.jsx(wr,{className:"w-4 h-4 text-bambu-green"})}),r.jsx("div",{className:"absolute inset-x-0 bottom-0 bg-gradient-to-t from-black/80 to-transparent p-2 opacity-0 group-hover:opacity-100 transition-opacity",children:r.jsx("p",{className:"text-xs text-white truncate",children:n.print_name||"Unknown"})})]},n.id))})}function Jat({priority:t,t:e}){const n={low:{color:"bg-gray-500/20 text-gray-400",label:e("projectDetail.priority.low")},normal:{color:"bg-blue-500/20 text-blue-400",label:e("projectDetail.priority.normal")},high:{color:"bg-orange-500/20 text-orange-400",label:e("projectDetail.priority.high")},urgent:{color:"bg-red-500/20 text-red-400",label:e("projectDetail.priority.urgent")}},{color:a,label:i}=n[t]||n.normal;return r.jsxs("span",{className:`px-2 py-1 rounded text-xs font-medium flex items-center gap-1 ${a}`,children:[t==="urgent"&&r.jsx(Nn,{className:"w-3 h-3"}),i]})}function pF(t,e){if(!t)return null;const n=Xn(t);if(!n)return null;const a=new Date,i=Math.ceil((n.getTime()-a.getTime())/(1e3*60*60*24));return i<0?{color:"text-red-400",label:e("projectDetail.dueDate.overdue")}:i===0?{color:"text-orange-400",label:e("projectDetail.dueDate.today")}:i<=3?{color:"text-yellow-400",label:e("projectDetail.dueDate.daysLeft",{count:i})}:{color:"text-bambu-gray",label:e("projectDetail.dueDate.daysLeft",{count:i})}}function eit(){const{id:t}=_S(),e=Di(),{t:n}=kt(),a=en(),{showToast:i}=rn(),{hasPermission:s}=cr(),[o,l]=y.useState(!1),[c,d]=y.useState(!1),[u,m]=y.useState(""),[p,f]=y.useState(null),[g,w]=y.useState(null),b=parseInt(t||"0",10),{data:x,isLoading:S,error:N}=Ge({queryKey:["project",b],queryFn:()=>ie.getProject(b),enabled:b>0}),{data:C,isLoading:P}=Ge({queryKey:["project-archives",b],queryFn:()=>ie.getProjectArchives(b),enabled:b>0}),{data:T,isLoading:A}=Ge({queryKey:["project-bom",b],queryFn:()=>ie.getProjectBOM(b),enabled:b>0}),{data:F,isLoading:_}=Ge({queryKey:["project-timeline",b],queryFn:()=>ie.getProjectTimeline(b,20),enabled:b>0}),{data:E}=Ge({queryKey:["settings"],queryFn:ie.getSettings}),{data:H}=Ge({queryKey:["project-folders",b],queryFn:()=>ie.getLibraryFoldersByProject(b),enabled:b>0}),{data:I,isLoading:U}=Ge({queryKey:["project-files",b],queryFn:()=>ie.getLibraryFiles(null,!1,b),enabled:b>0}),L=y.useMemo(()=>{const ke=new Map;for(const De of I??[])if(De.folder_id!=null){const Ae=ke.get(De.folder_id)??[];Ae.push(De),ke.set(De.folder_id,Ae)}return ke},[I]),Q=Vo(E?.currency||"USD"),re=E?.time_format||"system",J=it({mutationFn:ke=>ie.updateProject(b,ke),onSuccess:()=>{a.invalidateQueries({queryKey:["project",b]}),a.invalidateQueries({queryKey:["projects"]}),l(!1),d(!1),i(n("projectDetail.toast.projectUpdated"),"success")},onError:ke=>{i(ke.message,"error")}}),ce=()=>{m(x?.notes||""),d(!0)},pe=()=>{J.mutate({notes:u})},ue=()=>{d(!1),m("")},[X,ae]=y.useState(""),[me,ge]=y.useState(1),[Pe,$]=y.useState(""),[W,D]=y.useState(""),[j,B]=y.useState(""),[Y,O]=y.useState(!1),[se,z]=y.useState(!1),[G,K]=y.useState(null),[Z,oe]=y.useState(""),[ee,fe]=y.useState(1),[de,le]=y.useState(""),[q,R]=y.useState(""),[ne,xe]=y.useState(""),[ve,Ce]=y.useState({isOpen:!1,title:"",message:"",onConfirm:()=>{}}),ye=it({mutationFn:ke=>ie.createBOMItem(b,ke),onSuccess:()=>{a.invalidateQueries({queryKey:["project-bom",b]}),a.invalidateQueries({queryKey:["project",b]}),ae(""),ge(1),$(""),D(""),B(""),O(!1),i(n("projectDetail.toast.partAdded"),"success")},onError:ke=>i(ke.message,"error")}),be=it({mutationFn:({itemId:ke,data:De})=>ie.updateBOMItem(b,ke,De),onSuccess:()=>{a.invalidateQueries({queryKey:["project-bom",b]}),a.invalidateQueries({queryKey:["project",b]}),K(null)},onError:ke=>i(ke.message,"error")}),Ee=it({mutationFn:ke=>ie.deleteBOMItem(b,ke),onSuccess:()=>{a.invalidateQueries({queryKey:["project-bom",b]}),a.invalidateQueries({queryKey:["project",b]}),i(n("projectDetail.toast.partRemoved"),"success")},onError:ke=>i(ke.message,"error")}),ze=ke=>{ke.preventDefault(),X.trim()&&ye.mutate({name:X.trim(),quantity_needed:me,unit_price:Pe?parseFloat(Pe):void 0,sourcing_url:W.trim()||void 0,remarks:j.trim()||void 0})},Oe=ke=>{const De=ke.is_complete?0:ke.quantity_needed;be.mutate({itemId:ke.id,data:{quantity_acquired:De}})},Be=(ke,De)=>{Ce({isOpen:!0,title:n("projectDetail.bom.deletePart"),message:n("projectDetail.bom.deleteConfirm",{name:De}),onConfirm:()=>{Ce(Ae=>({...Ae,isOpen:!1})),Ee.mutate(ke)}})},Se=ke=>{K(ke),oe(ke.name),fe(ke.quantity_needed),le(ke.unit_price?.toString()||""),R(ke.sourcing_url||""),xe(ke.remarks||"")},$e=ke=>{ke.preventDefault(),!(!G||!Z.trim())&&be.mutate({itemId:G.id,data:{name:Z.trim(),quantity_needed:ee,unit_price:de?parseFloat(de):void 0,sourcing_url:q.trim()||void 0,remarks:ne.trim()||void 0}})},rt=()=>{K(null)},ot=async()=>{try{const{blob:ke,filename:De}=await ie.exportProjectZip(Number(b)),Ae=URL.createObjectURL(ke),Xe=document.createElement("a");Xe.href=Ae,Xe.download=De||`${x?.name||"project"}_${new Date().toISOString().split("T")[0]}.zip`,Xe.click(),URL.revokeObjectURL(Ae),i(n("projectDetail.toast.projectExported"),"success")}catch(ke){i(ke.message,"error")}},Le=it({mutationFn:()=>ie.createTemplateFromProject(b),onSuccess:()=>{a.invalidateQueries({queryKey:["projects"]}),i(n("projectDetail.toast.templateCreated"),"success")},onError:ke=>i(ke.message,"error")}),nt=ke=>Lg(ke,re,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"});if(S)return r.jsx("div",{className:"flex items-center justify-center py-24",children:r.jsx(pt,{className:"w-8 h-8 animate-spin text-bambu-green"})});if(N||!x)return r.jsxs("div",{className:"text-center py-24",children:[r.jsx("p",{className:"text-bambu-gray",children:N?`${n("common.error")}: ${N.message}`:n("projectDetail.notFound")}),r.jsx(Me,{variant:"secondary",className:"mt-4",onClick:()=>e("/projects"),children:n("projectDetail.backToProjects")})]});const Ne=x.stats,Qe=Ne?.progress_percent??0,Ue=Ne?.parts_progress_percent??0;return r.jsxs("div",{className:"p-4 md:p-8 space-y-8",children:[r.jsxs("div",{className:"flex items-center gap-2 text-sm text-bambu-gray",children:[r.jsx(Is,{to:"/projects",className:"hover:text-white transition-colors",children:n("nav.projects")}),r.jsx(Va,{className:"w-4 h-4"}),r.jsx("span",{className:"text-white",children:x.name})]}),r.jsxs("div",{className:"flex items-start justify-between",children:[r.jsxs("div",{className:"flex items-center gap-4",children:[r.jsx("button",{onClick:()=>e("/projects"),className:"p-2 rounded-lg bg-bambu-card hover:bg-bambu-dark-tertiary transition-colors",children:r.jsx(vT,{className:"w-5 h-5 text-bambu-gray"})}),r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("div",{className:"w-4 h-4 rounded-full shrink-0",style:{backgroundColor:x.color||"#6b7280"}}),r.jsxs("div",{children:[r.jsx("h1",{className:"text-2xl font-bold text-white",children:x.name}),x.description&&r.jsx("p",{className:"text-bambu-gray mt-1",children:x.description})]})]}),r.jsx(Qat,{status:x.status,t:n})]}),r.jsxs("div",{className:"flex gap-2",children:[r.jsxs(Me,{variant:"secondary",onClick:ot,disabled:!s("projects:read"),title:s("projects:read")?n("projectDetail.exportProject"):n("projectDetail.noExportPermission"),children:[r.jsx(Yr,{className:"w-4 h-4 mr-2"}),n("projectDetail.export")]}),r.jsxs(Me,{onClick:()=>l(!0),disabled:!s("projects:update"),title:s("projects:update")?void 0:n("projectDetail.noEditPermission"),children:[r.jsx(Eg,{className:"w-4 h-4 mr-2"}),n("common.edit")]})]})]}),(x.target_count||x.target_parts_count)&&r.jsx(Ct,{children:r.jsxs(At,{className:"p-4 space-y-4",children:[x.target_count&&r.jsxs("div",{children:[r.jsxs("div",{className:"flex items-center justify-between mb-2",children:[r.jsx("span",{className:"text-sm text-bambu-gray",children:n("projectDetail.progress.platesProgress")}),r.jsxs("span",{className:"text-sm font-medium text-white",children:[Ne?.total_archives||0," / ",x.target_count," ",n("projectDetail.progress.printJobs")]})]}),r.jsx("div",{className:"h-3 bg-bambu-dark rounded-full overflow-hidden",children:r.jsx("div",{className:"h-full transition-all duration-500",style:{width:`${Math.min(Qe,100)}%`,backgroundColor:Qe>=100?"#22c55e":x.color||"#6b7280"}})}),r.jsxs("div",{className:"flex justify-between mt-1",children:[r.jsx("span",{className:"text-xs text-bambu-gray/70",children:n("projectDetail.progress.percentComplete",{percent:Qe.toFixed(0)})}),Ne?.remaining_prints!=null&&Ne.remaining_prints>0&&r.jsx("span",{className:"text-xs text-bambu-gray/70",children:n("projectDetail.progress.remaining",{count:Ne.remaining_prints})})]})]}),x.target_parts_count&&r.jsxs("div",{children:[r.jsxs("div",{className:"flex items-center justify-between mb-2",children:[r.jsx("span",{className:"text-sm text-bambu-gray",children:n("projectDetail.progress.partsProgress")}),r.jsxs("span",{className:"text-sm font-medium text-white",children:[Ne?.completed_prints||0," / ",x.target_parts_count," ",n("projectDetail.progress.parts")]})]}),r.jsx("div",{className:"h-3 bg-bambu-dark rounded-full overflow-hidden",children:r.jsx("div",{className:"h-full transition-all duration-500",style:{width:`${Math.min(Ue,100)}%`,backgroundColor:Ue>=100?"#22c55e":x.color||"#6b7280"}})}),r.jsxs("div",{className:"flex justify-between mt-1",children:[r.jsx("span",{className:"text-xs text-bambu-gray/70",children:n("projectDetail.progress.percentComplete",{percent:Ue.toFixed(0)})}),Ne?.remaining_parts!=null&&Ne.remaining_parts>0&&r.jsx("span",{className:"text-xs text-bambu-gray/70",children:n("projectDetail.progress.remaining",{count:Ne.remaining_parts})})]})]})]})}),Ne&&r.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[r.jsx(Ct,{children:r.jsx(At,{className:"p-4",children:r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("div",{className:"p-2 rounded-lg bg-bambu-dark text-bambu-green",children:r.jsx(Br,{className:"w-5 h-5"})}),r.jsxs("div",{children:[r.jsx("p",{className:"text-sm text-bambu-gray",children:n("projectDetail.stats.printJobs")}),r.jsxs("p",{className:"text-xl font-semibold text-white",children:[Ne.total_archives," ",r.jsx("span",{className:"text-sm font-normal text-bambu-gray",children:n("projectDetail.stats.total")})]}),Ne.failed_prints>0&&r.jsx("p",{className:"text-sm text-status-error",children:n("projectDetail.stats.failed",{count:Ne.failed_prints})}),r.jsx("p",{className:"text-sm text-bambu-gray",children:n("projectDetail.stats.partsPrinted",{count:Ne.completed_prints})})]})]})})}),r.jsx(pQ,{icon:Zn,label:n("projectDetail.stats.printTime"),value:Lve(Ne.total_print_time_hours),color:"text-yellow-400"}),r.jsx(pQ,{icon:pr,label:n("projectDetail.stats.filamentUsed"),value:Xat(Ne.total_filament_grams),color:"text-purple-400"})]}),Ne&&(()=>{const ke=Ne.estimated_cost+Ne.total_energy_cost+Ne.bom_cost;return Ne.estimated_cost>0||ke>0||x.budget!==null})()&&r.jsx(Ct,{children:r.jsxs(At,{className:"p-4",children:[r.jsx("h2",{className:"text-lg font-semibold text-white mb-3",children:n("projectDetail.cost.title")}),r.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[r.jsxs("div",{children:[r.jsx("p",{className:"text-xs text-bambu-gray uppercase",children:n("projectDetail.cost.filamentCost")}),r.jsxs("p",{className:"text-lg font-semibold text-white",children:[Q,Ne.estimated_cost.toFixed(2)]})]}),Ne.total_energy_kwh>0&&r.jsxs("div",{children:[r.jsx("p",{className:"text-xs text-bambu-gray uppercase",children:n("projectDetail.cost.energy")}),r.jsxs("p",{className:"text-lg font-semibold text-white",children:[Ne.total_energy_kwh.toFixed(3)," kWh",Ne.total_energy_cost>0&&r.jsxs("span",{className:"text-sm text-bambu-gray ml-1",children:["(",Q,Ne.total_energy_cost.toFixed(2),")"]})]})]}),(()=>{const ke=Ne.estimated_cost+Ne.total_energy_cost+Ne.bom_cost;return ke<=0?null:r.jsxs("div",{children:[r.jsx("p",{className:"text-xs text-bambu-gray uppercase",children:n("projectDetail.cost.totalCost")}),r.jsxs("p",{className:"text-lg font-semibold text-bambu-green",children:[Q,ke.toFixed(2)]}),Ne.bom_cost>0&&r.jsx("p",{className:"text-xs text-bambu-gray/70",children:n("projectDetail.cost.includesBom")})]})})(),x.budget!==null&&(()=>{const ke=Ne.estimated_cost+Ne.total_energy_cost+Ne.bom_cost,De=x.budget-ke;return r.jsxs("div",{children:[r.jsx("p",{className:"text-xs text-bambu-gray uppercase",children:n("projectDetail.cost.budget")}),r.jsxs("p",{className:"text-sm text-bambu-gray",children:[n("projectDetail.cost.total"),": ",r.jsxs("span",{className:"text-white font-semibold",children:[Q,x.budget.toFixed(2)]})]}),r.jsxs("p",{className:`text-sm ${De>=0?"text-bambu-green":"text-red-400"}`,children:[n("projectDetail.cost.remaining"),": ",r.jsxs("span",{className:"font-semibold",children:[Q,De.toFixed(2)]})]})]})})()]})]})}),x.children&&x.children.length>0&&r.jsx(Ct,{children:r.jsxs(At,{className:"p-4",children:[r.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2 mb-3",children:[r.jsx(fbe,{className:"w-5 h-5"}),n("projectDetail.subProjects.title",{count:x.children.length})]}),r.jsx("div",{className:"space-y-2",children:x.children.map(ke=>r.jsxs(Is,{to:`/projects/${ke.id}`,className:"flex items-center justify-between p-3 bg-bambu-dark rounded-lg hover:bg-bambu-dark-tertiary transition-colors",children:[r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("div",{className:"w-3 h-3 rounded-full",style:{backgroundColor:ke.color||"#6b7280"}}),r.jsx("span",{className:"text-white",children:ke.name}),r.jsx("span",{className:`text-xs px-2 py-0.5 rounded ${ke.status==="completed"?"bg-status-ok/20 text-status-ok":ke.status==="archived"?"bg-bambu-gray/20 text-bambu-gray":"bg-blue-500/20 text-blue-400"}`,children:ke.status})]}),ke.progress_percent!==null&&r.jsxs("span",{className:"text-sm text-bambu-gray",children:[ke.progress_percent.toFixed(0),"%"]})]},ke.id))})]})}),x.parent_id&&x.parent_name&&r.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[r.jsx(oa,{className:"w-4 h-4 text-bambu-gray"}),r.jsx("span",{className:"text-bambu-gray",children:n("projectDetail.partOf")}),r.jsx(Is,{to:`/projects/${x.parent_id}`,className:"text-bambu-green hover:underline",children:x.parent_name})]}),(x.tags||x.due_date||x.priority!=="normal")&&r.jsxs("div",{className:"flex flex-wrap items-center gap-4",children:[x.priority&&x.priority!=="normal"&&r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("span",{className:"text-xs text-bambu-gray uppercase",children:n("projectDetail.priorityLabel")}),r.jsx(Jat,{priority:x.priority,t:n})]}),x.due_date&&r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(Sa,{className:"w-4 h-4 text-bambu-gray"}),r.jsx("span",{className:"text-sm text-white",children:Rg(x.due_date,{year:"numeric",month:"short",day:"numeric"})}),pF(x.due_date,n)&&r.jsxs("span",{className:`text-xs ${pF(x.due_date,n).color}`,children:["(",pF(x.due_date,n).label,")"]})]}),x.tags&&r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx($m,{className:"w-4 h-4 text-bambu-gray"}),r.jsx("div",{className:"flex flex-wrap gap-1",children:x.tags.split(",").map((ke,De)=>r.jsx("span",{className:"px-2 py-0.5 bg-bambu-dark-tertiary text-bambu-gray text-xs rounded",children:ke.trim()},De))})]})]}),r.jsx(Ct,{children:r.jsxs(At,{className:"p-4",children:[r.jsxs("div",{className:"flex items-center justify-between mb-3",children:[r.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[r.jsx(Bs,{className:"w-5 h-5"}),n("projectDetail.notes.title")]}),c?r.jsxs("div",{className:"flex gap-2",children:[r.jsxs(Me,{variant:"secondary",size:"sm",onClick:ue,disabled:J.isPending,children:[r.jsx(Ht,{className:"w-4 h-4 mr-1"}),n("common.cancel")]}),r.jsxs(Me,{size:"sm",onClick:pe,disabled:J.isPending,children:[J.isPending?r.jsx(pt,{className:"w-4 h-4 animate-spin mr-1"}):r.jsx(us,{className:"w-4 h-4 mr-1"}),n("common.save")]})]}):r.jsxs(Me,{variant:"secondary",size:"sm",onClick:ce,disabled:!s("projects:update"),title:s("projects:update")?void 0:n("projectDetail.notes.noEditPermission"),children:[r.jsx(Eg,{className:"w-4 h-4 mr-1"}),n("common.edit")]})]}),c?r.jsx(UI,{content:u,onChange:m,placeholder:n("projectDetail.notes.placeholder")}):x.notes?r.jsx("div",{className:"prose prose-invert prose-sm max-w-none",dangerouslySetInnerHTML:{__html:c5.sanitize(x.notes)}}):r.jsx("p",{className:"text-bambu-gray/70 text-sm italic",children:n("projectDetail.notes.empty")})]})}),r.jsx(Ct,{children:r.jsxs(At,{className:"p-4",children:[r.jsx("div",{className:"flex items-center justify-between mb-3",children:r.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[r.jsx(Fl,{className:"w-5 h-5"}),n("projectDetail.files.title")]})}),r.jsxs("p",{className:"text-xs text-bambu-gray mb-3",children:[r.jsx(Is,{to:"/files",className:"text-bambu-green hover:underline",children:n("projectDetail.files.linkFolders")})," ",n("projectDetail.files.forQuickAccess")]}),H&&H.length>0?r.jsx("div",{className:"space-y-4",children:H.map(ke=>{const De=L.get(ke.id)??[],Ae=U;return r.jsxs("div",{children:[r.jsxs(Is,{to:`/files?folder=${ke.id}`,className:"flex items-center justify-between p-3 bg-bambu-dark rounded-lg hover:bg-bambu-dark-tertiary transition-colors mb-2",children:[r.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[r.jsx(Fl,{className:"w-5 h-5 text-bambu-green shrink-0"}),r.jsxs("div",{className:"min-w-0",children:[r.jsx("p",{className:"text-sm text-white truncate",children:ke.name}),r.jsx("p",{className:"text-xs text-bambu-gray",children:n("projectDetail.files.fileCount",{count:ke.file_count})})]})]}),r.jsx(Va,{className:"w-4 h-4 text-bambu-gray shrink-0"})]}),Ae?r.jsx("div",{className:"flex items-center gap-2 px-3 py-2 text-bambu-gray text-sm",children:r.jsx(pt,{className:"w-4 h-4 animate-spin"})}):De.length===0?r.jsx("p",{className:"text-bambu-gray/60 text-xs italic px-3",children:n("projectDetail.files.noFiles")}):r.jsx("div",{className:"space-y-1 pl-3",children:De.map(Xe=>{const Ke=Yat(Xe.filename);return r.jsxs("div",{className:"flex items-center gap-3 p-2 rounded-lg hover:bg-bambu-dark-tertiary transition-colors",children:[r.jsx("div",{className:"w-10 h-10 shrink-0 rounded bg-bambu-dark overflow-hidden flex items-center justify-center",children:Xe.thumbnail_path?r.jsx("img",{src:ie.getLibraryFileThumbnailUrl(Xe.id),alt:Xe.print_name||Xe.filename,className:"w-full h-full object-cover"}):r.jsx(Nh,{className:"w-5 h-5 text-bambu-gray/40"})}),r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsx("p",{className:"text-sm text-white truncate",title:Xe.print_name||Xe.filename,children:Xe.print_name||Xe.filename}),r.jsx("span",{className:`text-xs px-1.5 py-0.5 rounded font-medium ${Xe.file_type==="3mf"?"bg-bambu-green/20 text-bambu-green":Xe.file_type==="gcode"?"bg-blue-500/20 text-blue-400":"bg-bambu-gray/20 text-bambu-gray"}`,children:Xe.file_type.toUpperCase()})]}),Ke&&r.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[r.jsx("button",{onClick:()=>f(Xe),title:n("projectDetail.files.print"),className:"p-1.5 rounded hover:bg-bambu-green/20 text-bambu-green transition-colors",children:r.jsx(fs,{className:"w-4 h-4"})}),r.jsx("button",{onClick:()=>w(Xe),title:n("projectDetail.files.addToQueue"),className:"p-1.5 rounded hover:bg-blue-500/20 text-blue-400 transition-colors",children:r.jsx(Ife,{className:"w-4 h-4"})})]})]},Xe.id)})})]},ke.id)})}):r.jsx("p",{className:"text-bambu-gray/70 text-sm italic",children:n("projectDetail.files.empty")})]})}),r.jsx(Ct,{children:r.jsxs(At,{className:"p-4",children:[r.jsxs("div",{className:"flex items-center justify-between mb-4",children:[r.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[r.jsx(lb,{className:"w-5 h-5"}),n("projectDetail.bom.title"),Ne&&Ne.bom_total_items>0&&r.jsxs("span",{className:"text-sm font-normal text-bambu-gray",children:["(",n("projectDetail.bom.acquired",{completed:Ne.bom_completed_items,total:Ne.bom_total_items}),")"]})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[T&&T.some(ke=>ke.is_complete)&&r.jsx("button",{onClick:()=>z(!se),className:`text-xs px-2 py-1 rounded transition-colors ${se?"bg-bambu-green/20 text-bambu-green":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:n(se?"projectDetail.bom.showAll":"projectDetail.bom.hideDone")}),!Y&&r.jsxs(Me,{variant:"secondary",size:"sm",onClick:()=>O(!0),disabled:!s("projects:update"),title:s("projects:update")?void 0:n("projectDetail.bom.noAddPermission"),children:[r.jsx(ir,{className:"w-4 h-4 mr-1"}),n("projectDetail.bom.addPart")]})]})]}),Y&&r.jsxs("form",{onSubmit:ze,className:"bg-bambu-dark rounded-lg p-4 mb-4 space-y-3",children:[r.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[r.jsx("input",{type:"text",value:X,onChange:ke=>ae(ke.target.value),className:"bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:n("projectDetail.bom.partNamePlaceholder"),autoFocus:!0}),r.jsxs("div",{className:"flex gap-2",children:[r.jsx("input",{type:"number",value:me,onChange:ke=>ge(parseInt(ke.target.value)||1),className:"w-20 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white focus:outline-none focus:border-bambu-green",min:"1",placeholder:n("projectDetail.bom.qty")}),r.jsx("input",{type:"number",step:"0.01",value:Pe,onChange:ke=>$(ke.target.value),className:"flex-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:n("projectDetail.bom.price",{currency:Q})})]})]}),r.jsx("input",{type:"url",value:W,onChange:ke=>D(ke.target.value),className:"w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:n("projectDetail.bom.sourcingUrlPlaceholder")}),r.jsx("input",{type:"text",value:j,onChange:ke=>B(ke.target.value),className:"w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:n("projectDetail.bom.remarksPlaceholder")}),r.jsxs("div",{className:"flex justify-end gap-2",children:[r.jsx(Me,{type:"button",variant:"secondary",size:"sm",onClick:()=>O(!1),children:n("common.cancel")}),r.jsx(Me,{type:"submit",size:"sm",disabled:!X.trim()||ye.isPending,children:ye.isPending?r.jsx(pt,{className:"w-4 h-4 animate-spin"}):n("projectDetail.bom.addPart")})]})]}),A?r.jsx("div",{className:"flex items-center justify-center py-4",children:r.jsx(pt,{className:"w-6 h-6 animate-spin text-bambu-green"})}):T&&T.length>0?r.jsxs("div",{className:"space-y-2",children:[T.filter(ke=>!se||!ke.is_complete).map(ke=>r.jsx("div",{className:`p-3 rounded-lg transition-colors ${ke.is_complete?"bg-status-ok/10":"bg-bambu-dark"}`,children:G?.id===ke.id?r.jsxs("form",{onSubmit:$e,className:"space-y-3",children:[r.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[r.jsx("input",{type:"text",value:Z,onChange:De=>oe(De.target.value),className:"bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:n("projectDetail.bom.partName"),autoFocus:!0}),r.jsxs("div",{className:"flex gap-2",children:[r.jsx("input",{type:"number",value:ee,onChange:De=>fe(parseInt(De.target.value)||1),className:"w-20 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white focus:outline-none focus:border-bambu-green",min:"1",placeholder:n("projectDetail.bom.qty")}),r.jsx("input",{type:"number",step:"0.01",value:de,onChange:De=>le(De.target.value),className:"flex-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:n("projectDetail.bom.price",{currency:Q})})]})]}),r.jsx("input",{type:"url",value:q,onChange:De=>R(De.target.value),className:"w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:n("projectDetail.bom.sourcingUrlPlaceholder")}),r.jsx("input",{type:"text",value:ne,onChange:De=>xe(De.target.value),className:"w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:n("projectDetail.bom.remarksPlaceholder")}),r.jsxs("div",{className:"flex justify-end gap-2",children:[r.jsx(Me,{type:"button",variant:"secondary",size:"sm",onClick:rt,children:n("common.cancel")}),r.jsx(Me,{type:"submit",size:"sm",disabled:!Z.trim()||be.isPending,children:be.isPending?r.jsx(pt,{className:"w-4 h-4 animate-spin"}):n("common.save")})]})]}):r.jsxs("div",{className:"flex items-start gap-3",children:[r.jsx("button",{onClick:()=>s("projects:update")&&Oe(ke),disabled:be.isPending||!s("projects:update"),title:s("projects:update")?void 0:n("projectDetail.bom.noUpdatePermission"),className:`w-5 h-5 mt-0.5 rounded border-2 flex items-center justify-center transition-colors shrink-0 ${ke.is_complete?"bg-status-ok border-status-ok text-white":s("projects:update")?"border-bambu-gray hover:border-bambu-green":"border-bambu-gray/50 cursor-not-allowed"}`,children:ke.is_complete&&r.jsx(wr,{className:"w-3 h-3"})}),r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsxs("div",{className:"flex items-center justify-between gap-2",children:[r.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[r.jsxs("p",{className:`text-sm font-medium ${ke.is_complete?"text-bambu-gray line-through":"text-white"}`,children:[ke.name,r.jsxs("span",{className:"text-bambu-gray font-normal ml-2",children:["x",ke.quantity_needed]})]}),ke.unit_price!==null&&r.jsxs("span",{className:"text-xs text-bambu-green whitespace-nowrap",children:[Q,(ke.unit_price*ke.quantity_needed).toFixed(2)]})]}),r.jsxs("div",{className:"flex items-center gap-1",children:[r.jsx("button",{onClick:()=>s("projects:update")&&Se(ke),disabled:!s("projects:update"),className:`p-1 rounded transition-colors shrink-0 ${s("projects:update")?"hover:bg-bambu-dark-tertiary text-bambu-gray hover:text-white":"text-bambu-gray/50 cursor-not-allowed"}`,title:s("projects:update")?n("common.edit"):n("projectDetail.bom.noEditPermission"),children:r.jsx(oi,{className:"w-4 h-4"})}),r.jsx("button",{onClick:()=>s("projects:update")&&Be(ke.id,ke.name),disabled:!s("projects:update"),className:`p-1 rounded transition-colors shrink-0 ${s("projects:update")?"hover:bg-bambu-dark-tertiary text-bambu-gray hover:text-red-400":"text-bambu-gray/50 cursor-not-allowed"}`,title:s("projects:update")?n("common.delete"):n("projectDetail.bom.noDeletePermission"),children:r.jsx(Jt,{className:"w-4 h-4"})})]})]}),ke.sourcing_url&&r.jsxs("a",{href:ke.sourcing_url,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1 mt-1 text-xs text-blue-400 hover:text-blue-300 transition-colors",onClick:De=>De.stopPropagation(),children:[r.jsx(Lr,{className:"w-3 h-3 shrink-0"}),r.jsx("span",{className:"truncate",children:(()=>{try{return new URL(ke.sourcing_url).hostname.replace("www.","")}catch{return ke.sourcing_url}})()})]}),ke.remarks&&r.jsx("p",{className:"mt-1 text-xs text-bambu-gray/80 italic",children:ke.remarks})]})]})},ke.id)),Ne&&Ne.bom_cost>0&&r.jsxs("div",{className:"pt-2 mt-2 border-t border-bambu-dark-tertiary flex justify-between text-sm",children:[r.jsx("span",{className:"text-bambu-gray",children:n("projectDetail.bom.totalCost")}),r.jsxs("span",{className:"text-white font-medium",children:[Q,Ne.bom_cost.toFixed(2)]})]})]}):r.jsx("p",{className:"text-bambu-gray/70 text-sm italic",children:n("projectDetail.bom.empty")})]})}),r.jsx(Ct,{children:r.jsxs(At,{className:"p-4",children:[r.jsx("div",{className:"flex items-center justify-between mb-3",children:r.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[r.jsx(Aw,{className:"w-5 h-5"}),n("projectDetail.timeline.title")]})}),_?r.jsx("div",{className:"flex items-center justify-center py-4",children:r.jsx(pt,{className:"w-6 h-6 animate-spin text-bambu-green"})}):F&&F.length>0?r.jsx("div",{className:"space-y-3",children:F.slice(0,10).map((ke,De)=>r.jsxs("div",{className:"flex gap-3",children:[r.jsxs("div",{className:`w-8 h-8 rounded-full flex items-center justify-center shrink-0 ${ke.event_type==="print_completed"?"bg-status-ok/20 text-status-ok":ke.event_type==="print_failed"?"bg-status-error/20 text-status-error":ke.event_type==="print_started"?"bg-yellow-500/20 text-yellow-400":"bg-bambu-dark-tertiary text-bambu-gray"}`,children:[ke.event_type==="print_completed"&&r.jsx(wr,{className:"w-4 h-4"}),ke.event_type==="print_failed"&&r.jsx(Da,{className:"w-4 h-4"}),ke.event_type==="print_started"&&r.jsx(pr,{className:"w-4 h-4"}),ke.event_type==="queued"&&r.jsx(qF,{className:"w-4 h-4"}),ke.event_type==="project_created"&&r.jsx(ir,{className:"w-4 h-4"})]}),r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsx("p",{className:"text-sm text-white",children:ke.title}),ke.description&&r.jsx("p",{className:"text-xs text-bambu-gray truncate",children:ke.description}),r.jsx("p",{className:"text-xs text-bambu-gray/70",children:nt(ke.timestamp)})]})]},De))}):r.jsx("p",{className:"text-bambu-gray/70 text-sm italic",children:n("projectDetail.timeline.empty")})]})}),!x.is_template&&r.jsx("div",{className:"flex justify-end",children:r.jsxs(Me,{variant:"secondary",size:"sm",onClick:()=>Le.mutate(),disabled:Le.isPending||!s("projects:create"),title:s("projects:create")?void 0:n("projectDetail.template.noCreatePermission"),children:[Le.isPending?r.jsx(pt,{className:"w-4 h-4 animate-spin mr-2"}):r.jsx(Mi,{className:"w-4 h-4 mr-2"}),n("projectDetail.template.saveAsTemplate")]})}),Ne&&(Ne.queued_prints>0||Ne.in_progress_prints>0)&&r.jsx(Ct,{children:r.jsxs(At,{className:"p-4",children:[r.jsxs("div",{className:"flex items-center justify-between mb-3",children:[r.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[r.jsx(qF,{className:"w-5 h-5"}),n("projectDetail.queue.title")]}),r.jsx(Is,{to:`/queue?project=${b}`,className:"text-sm text-bambu-green hover:underline",children:n("projectDetail.queue.viewAll")})]}),r.jsxs("div",{className:"flex items-center gap-4 text-sm",children:[Ne.in_progress_prints>0&&r.jsx("span",{className:"text-yellow-400",children:n("projectDetail.queue.printing",{count:Ne.in_progress_prints})}),Ne.queued_prints>0&&r.jsx("span",{className:"text-bambu-gray",children:n("projectDetail.queue.queued",{count:Ne.queued_prints})})]})]})}),r.jsxs("div",{children:[r.jsx("div",{className:"flex items-center justify-between mb-4",children:r.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[r.jsx(Br,{className:"w-5 h-5"}),n("projectDetail.prints.title",{count:C?.length||0})]})}),P?r.jsx("div",{className:"flex items-center justify-center py-8",children:r.jsx(pt,{className:"w-6 h-6 animate-spin text-bambu-green"})}):r.jsx(Zat,{archives:C||[],t:n})]}),o&&r.jsx(Rce,{t:n,currencySymbol:Q,project:{...x,archive_count:Ne?.total_archives||0,total_items:Ne?.total_items||0,completed_count:Ne?.completed_prints||0,failed_count:Ne?.failed_prints||0,queue_count:Ne?.queued_prints||0,progress_percent:Ne?.progress_percent||null,archives:[]},onClose:()=>l(!1),onSave:ke=>J.mutate(ke),isLoading:J.isPending}),ve.isOpen&&r.jsx(vn,{title:ve.title,message:ve.message,confirmText:n("common.delete"),variant:"danger",onConfirm:ve.onConfirm,onCancel:()=>Ce(ke=>({...ke,isOpen:!1}))}),p&&r.jsx(Sc,{mode:"reprint",libraryFileId:p.id,archiveName:p.print_name||p.filename,projectId:b,onClose:()=>f(null),onSuccess:()=>{f(null),a.invalidateQueries({queryKey:["archives"]})}}),g&&r.jsx(Sc,{mode:"add-to-queue",libraryFileId:g.id,archiveName:g.print_name||g.filename,projectId:b,onClose:()=>w(null),onSuccess:()=>{w(null),a.invalidateQueries({queryKey:["queue"]})}})]})}function tit({archiveId:t,libraryFileId:e,title:n,fileType:a,onClose:i}){const{t:s}=kt(),{data:o}=Ge({queryKey:["settings"],queryFn:ie.getSettings}),l=o?.preferred_slicer||"bambu_studio",c=e!=null,[d,u]=y.useState(null),[m,p]=y.useState(null),[f,g]=y.useState(!0),[w,b]=y.useState(null),[x,S]=y.useState(!1),[N,C]=y.useState(null),[P,T]=y.useState(0),[A,F]=y.useState(!1),[_,E]=y.useState(null),[H,I]=y.useState(!1),[U,L]=y.useState(!1),Q=y.useRef(null),re=y.useRef(null),J=10,ce=160,pe=240,ue=.35;y.useEffect(()=>{const de=le=>{le.key==="Escape"&&i()};return window.addEventListener("keydown",de),()=>window.removeEventListener("keydown",de)},[i]),y.useEffect(()=>{if(g(!0),c){const de=(a||"").toLowerCase(),le=de==="3mf"||de==="stl",q=de==="gcode"||de==="3mf";p({has_model:le,has_gcode:q,has_source:!1,build_volume:{x:256,y:256,z:256},filament_colors:[]}),u(le?"3d":q?"gcode":null),g(!1);return}if(!t){p(null),u(null),g(!1);return}ie.getArchiveCapabilities(t).then(de=>{p(de),de.has_model?u("3d"):de.has_gcode&&u("gcode"),g(!1)}).catch(()=>{p({has_model:!0,has_gcode:!1,has_source:!1,build_volume:{x:256,y:256,z:256},filament_colors:[]}),u("3d"),g(!1)})},[t,a,c]),y.useEffect(()=>{if(S(!0),C(null),T(0),c){const de=(a||"").toLowerCase();if(!e||de!=="3mf"){b(null),S(!1);return}ie.getLibraryFilePlates(e).then(le=>b(le)).catch(()=>b(null)).finally(()=>S(!1));return}if(!t){b(null),S(!1);return}ie.getArchivePlates(t).then(de=>b(de)).catch(()=>b(null)).finally(()=>S(!1))},[t,a,c,e]);const X=y.useMemo(()=>w?.plates??[],[w]),ae=(w?.is_multi_plate??!1)&&X.length>1,me=A&&ae,ge=N==null?null:X.find(de=>de.index===N)??null,Pe=de=>de.object_count??de.objects?.length??0,$=X.reduce((de,le)=>de+Pe(le),0),W=ge?Pe(ge):$,D=ge?s("modelViewer.plateNumber",{number:ge.index}):s("modelViewer.allPlates"),j=X.length>0,B=y.useRef(null),Y=y.useRef(null),[O,se]=y.useState(10),[z,G]=y.useState(3),K=X.length>O,Z=Math.max(1,Math.ceil(X.length/O)),oe=K?X.slice(P*O,(P+1)*O):X;y.useEffect(()=>{if(!me){se(10),G(3);return}const de=B.current,le=Y.current;if(!de||!le)return;let q=0;const R=()=>{const ve=le.clientWidth,ye=Math.floor(ve/210),be=Math.max(3,Math.min(5,ye||3));G(Le=>Le===be?Le:be);const Ee=window.getComputedStyle(de),ze=Number.parseFloat(Ee.rowGap||"0"),Be=de.querySelector("button")?.getBoundingClientRect().height??44,Se=le.clientHeight,rt=Math.max(1,Math.floor((Se+ze)/(Be+ze)))*be,ot=Math.max(1,rt-1);se(Le=>Le===ot?Le:ot)},ne=()=>{q&&cancelAnimationFrame(q),q=requestAnimationFrame(R)};ne();const xe=new ResizeObserver(ne);return xe.observe(le),xe.observe(de),()=>{q&&cancelAnimationFrame(q),xe.disconnect()}},[me,X.length]),y.useEffect(()=>{if(!K){T(0);return}T(de=>Math.min(de,Z-1))},[X.length,K,Z]),y.useEffect(()=>{if(!K||N==null)return;const de=X.findIndex(q=>q.index===N);if(de<0)return;const le=Math.floor(de/O);T(q=>q===le?q:le)},[X,O,N,K]),y.useEffect(()=>{if(!me){E(null),L(!1);return}if(U)return;const de=Q.current,le=re.current;if(!de||!le)return;const q=de.clientHeight;if(!q)return;const R=Math.max(pe,q*ue),ne=Math.max(ce,q-J-R),xe=Math.min(le.scrollHeight,ne);E(Math.max(ce,xe))},[me,U,X.length,P,J,ce,pe,ue]),y.useEffect(()=>{if(!H)return;const de=q=>{const R=Q.current;if(!R)return;const ne=R.getBoundingClientRect(),xe=ne.height;if(!xe)return;const ve=Math.max(pe,xe*ue),Ce=Math.max(ce,xe-J-ve),ye=Math.min(Ce,Math.max(ce,q.clientY-ne.top));E(ye)},le=()=>{I(!1),L(!0)};return document.addEventListener("mousemove",de),document.addEventListener("mouseup",le),document.body.style.cursor="row-resize",document.body.style.userSelect="none",()=>{document.removeEventListener("mousemove",de),document.removeEventListener("mouseup",le),document.body.style.cursor="",document.body.style.userSelect=""}},[H,J,ce,pe,ue]);const ee=c?(a||"").toLowerCase()==="3mf":!0,fe=async()=>{if(!ee)return;const de=n||"model";try{if(c){const{token:le}=await ie.createLibrarySlicerToken(e),q=ie.getLibrarySlicerDownloadUrl(e,le,de);Am(`${window.location.origin}${q}`,l)}else{const{token:le}=await ie.createArchiveSlicerToken(t),q=ie.getArchiveSlicerDownloadUrl(t,le,de);Am(`${window.location.origin}${q}`,l)}}catch{if(c){const le=`${window.location.origin}${ie.getLibraryFileDownloadUrl(e)}`;Am(le,l)}else{const le=`${window.location.origin}${ie.getArchiveForSlicer(t,de)}`;Am(le,l)}}};return r.jsx("div",{className:`fixed inset-0 bg-black/70 flex items-center justify-center z-50 ${A?"p-0":"p-8"}`,onClick:i,children:r.jsxs("div",{className:`bg-bambu-dark-secondary border border-bambu-dark-tertiary w-full flex flex-col ${A?"h-full max-w-none rounded-none":"h-[80vh] max-w-4xl rounded-xl"}`,onClick:de=>de.stopPropagation(),children:[r.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"flex items-center gap-3 min-w-0 flex-1 mr-4",children:[r.jsx("h2",{className:"text-lg font-semibold text-white truncate",children:n}),j&&r.jsxs("span",{className:"text-xs text-bambu-gray bg-bambu-dark-tertiary/70 px-2 py-1 rounded whitespace-nowrap",children:[D,": ",s("modelViewer.objectCount",{count:W})]})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsxs(Me,{variant:"secondary",size:"sm",onClick:fe,disabled:!ee,children:[r.jsx(Lr,{className:"w-4 h-4"}),s("modelViewer.openInSlicer")]}),r.jsx(Me,{variant:"secondary",size:"sm",onClick:()=>F(de=>!de),title:A?"Exit fullscreen":"Enter fullscreen",children:A?r.jsx(xO,{className:"w-4 h-4"}):r.jsx(kT,{className:"w-4 h-4"})}),r.jsx(Me,{variant:"ghost",size:"sm",onClick:i,children:r.jsx(Ht,{className:"w-5 h-5"})})]})]}),m&&r.jsxs("div",{className:"flex border-b border-bambu-dark-tertiary",children:[r.jsxs("button",{onClick:()=>m.has_model&&u("3d"),disabled:!m.has_model,className:`flex items-center gap-2 px-6 py-3 text-sm font-medium transition-colors ${d==="3d"?"text-bambu-green border-b-2 border-bambu-green":m.has_model?"text-bambu-gray hover:text-white":"text-bambu-gray/30 cursor-not-allowed"}`,children:[r.jsx(Ni,{className:"w-4 h-4"}),s("modelViewer.tabs.model"),!m.has_model&&r.jsxs("span",{className:"text-xs",children:["(",s("modelViewer.notAvailable"),")"]})]}),r.jsxs("button",{onClick:()=>m.has_gcode&&u("gcode"),disabled:!m.has_gcode,className:`flex items-center gap-2 px-6 py-3 text-sm font-medium transition-colors ${d==="gcode"?"text-bambu-green border-b-2 border-bambu-green":m.has_gcode?"text-bambu-gray hover:text-white":"text-bambu-gray/30 cursor-not-allowed"}`,children:[r.jsx(hge,{className:"w-4 h-4"}),s("modelViewer.tabs.gcode"),!m.has_gcode&&r.jsxs("span",{className:"text-xs",children:["(",s("modelViewer.notSliced"),")"]})]})]}),r.jsx("div",{className:"flex-1 overflow-hidden p-4",children:f?r.jsx("div",{className:"w-full h-full flex items-center justify-center",children:r.jsx(pt,{className:"w-8 h-8 animate-spin text-bambu-green"})}):d==="3d"&&m?r.jsxs("div",{ref:Q,className:`w-full h-full flex flex-col ${me?"gap-0 min-h-0":"gap-3"}`,children:[ae&&r.jsxs("div",{ref:re,style:me&&_!=null?{height:_}:void 0,className:`rounded-lg border border-bambu-dark-tertiary bg-bambu-dark p-3 ${me?"flex flex-col shrink-0":""}`,children:[r.jsxs("div",{className:"flex items-center gap-2 text-sm text-bambu-gray mb-2",children:[r.jsx(oa,{className:"w-4 h-4"}),s("modelViewer.plates"),x&&r.jsx(pt,{className:"w-3 h-3 animate-spin"})]}),r.jsxs("div",{className:me?"flex flex-col min-h-0 flex-1":void 0,children:[r.jsx("div",{ref:Y,className:me?"min-h-0 overflow-hidden pr-1 flex-1":void 0,children:r.jsxs("div",{ref:B,className:me?"grid gap-2":"grid grid-cols-2 md:grid-cols-3 gap-2",style:me?{gridTemplateColumns:`repeat(${z}, minmax(0, 1fr))`}:void 0,children:[r.jsxs("button",{type:"button",onClick:()=>C(null),className:`flex items-center rounded-lg border text-left transition-colors ${me?"gap-1.5 p-1.5 w-full":"gap-2 p-2"} ${N==null?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary bg-bambu-dark-secondary hover:border-bambu-gray"}`,children:[r.jsx("div",{className:`rounded bg-bambu-dark-tertiary flex items-center justify-center ${me?"w-8 h-8":"w-10 h-10"}`,children:r.jsx(oa,{className:`${me?"w-4 h-4":"w-5 h-5"} text-bambu-gray`})}),r.jsxs("div",{className:"min-w-0 flex-1",children:[r.jsx("p",{className:`${me?"text-xs":"text-sm"} text-white font-medium truncate`,children:s("modelViewer.allPlates")}),r.jsx("p",{className:`${me?"text-[10px]":"text-xs"} text-bambu-gray truncate`,children:s("modelViewer.plateCount",{count:X.length})})]}),N==null&&r.jsx(_r,{className:`${me?"w-3.5 h-3.5":"w-4 h-4"} text-bambu-green flex-shrink-0`})]}),oe.map(de=>r.jsxs("button",{type:"button",onClick:()=>C(de.index),className:`flex items-center rounded-lg border text-left transition-colors ${me?"gap-1.5 p-1.5 w-full":"gap-2 p-2"} ${N===de.index?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary bg-bambu-dark-secondary hover:border-bambu-gray"}`,children:[de.has_thumbnail&&de.thumbnail_url?r.jsx("img",{src:de.thumbnail_url,alt:`Plate ${de.index}`,className:`${me?"w-8 h-8":"w-10 h-10"} rounded object-cover bg-bambu-dark-tertiary`}):r.jsx("div",{className:`rounded bg-bambu-dark-tertiary flex items-center justify-center ${me?"w-8 h-8":"w-10 h-10"}`,children:r.jsx(oa,{className:`${me?"w-4 h-4":"w-5 h-5"} text-bambu-gray`})}),r.jsxs("div",{className:"min-w-0 flex-1",children:[r.jsx("p",{className:`${me?"text-xs":"text-sm"} text-white font-medium truncate`,children:de.name||s("modelViewer.plateNumber",{number:de.index})}),r.jsx("p",{className:`${me?"text-[10px]":"text-xs"} text-bambu-gray truncate`,children:s("modelViewer.objectCount",{count:de.object_count??de.objects?.length??0})})]}),N===de.index&&r.jsx(_r,{className:`${me?"w-3.5 h-3.5":"w-4 h-4"} text-bambu-green flex-shrink-0`})]},de.index))]})}),(ge||K)&&r.jsxs("div",{className:"mt-auto pt-3 flex items-center gap-4 text-xs text-bambu-gray overflow-x-auto",children:[ge&&r.jsxs("div",{className:"flex items-center gap-3 whitespace-nowrap",children:[r.jsx("span",{children:s("modelViewer.plateNumber",{number:ge.index})}),ge.print_time_seconds!=null&&r.jsx("span",{children:s("modelViewer.eta",{minutes:Math.round(ge.print_time_seconds/60)})}),ge.filament_used_grams!=null&&r.jsxs("span",{children:[ge.filament_used_grams.toFixed(1)," g"]}),ge.filaments.length>0&&r.jsx("span",{children:s("modelViewer.filamentCount",{count:ge.filaments.length})})]}),K&&r.jsxs("div",{className:`flex items-center gap-2 whitespace-nowrap ${ge?"ml-auto":""}`,children:[r.jsx("span",{children:s("modelViewer.pagination.pageOf",{current:P+1,total:Z})}),r.jsxs("div",{className:"flex items-center gap-1",children:[r.jsx("button",{type:"button",onClick:()=>T(de=>Math.max(de-1,0)),disabled:P===0,className:`px-2 py-1 rounded border text-xs ${P===0?"border-bambu-dark-tertiary text-bambu-gray/40 cursor-not-allowed":"border-bambu-dark-tertiary text-bambu-gray hover:text-white hover:border-bambu-gray"}`,children:s("modelViewer.pagination.prev")}),(()=>{let le=Math.max(0,P-Math.floor(2.5));const q=Math.min(Z,le+5);q-le<5&&(le=Math.max(0,q-5));const R=Array.from({length:q-le},(ne,xe)=>le+xe);return r.jsxs(r.Fragment,{children:[le>0&&r.jsx("button",{type:"button",onClick:()=>T(0),className:`px-2 py-1 rounded border text-xs ${P===0?"border-bambu-green text-bambu-green":"border-bambu-dark-tertiary text-bambu-gray hover:text-white hover:border-bambu-gray"}`,children:"1"}),le>1&&r.jsx("span",{className:"px-1",children:"…"}),R.map(ne=>r.jsx("button",{type:"button",onClick:()=>T(ne),className:`px-2 py-1 rounded border text-xs ${P===ne?"border-bambu-green text-bambu-green":"border-bambu-dark-tertiary text-bambu-gray hover:text-white hover:border-bambu-gray"}`,children:ne+1},ne)),qT(Z-1),className:`px-2 py-1 rounded border text-xs ${P===Z-1?"border-bambu-green text-bambu-green":"border-bambu-dark-tertiary text-bambu-gray hover:text-white hover:border-bambu-gray"}`,children:Z})]})})(),r.jsx("button",{type:"button",onClick:()=>T(de=>Math.min(de+1,Z-1)),disabled:P>=Z-1,className:`px-2 py-1 rounded border text-xs ${P>=Z-1?"border-bambu-dark-tertiary text-bambu-gray/40 cursor-not-allowed":"border-bambu-dark-tertiary text-bambu-gray hover:text-white hover:border-bambu-gray"}`,children:s("modelViewer.pagination.next")})]})]})]})]})]}),me&&r.jsx("div",{role:"separator","aria-orientation":"horizontal",onMouseDown:de=>{de.preventDefault(),I(!0),L(!0)},className:`h-2 cursor-row-resize flex items-center justify-center ${H?"bg-bambu-dark-tertiary":"bg-bambu-dark-secondary/60 hover:bg-bambu-dark-tertiary"}`,children:r.jsx("div",{className:"w-12 h-1 rounded-full bg-bambu-gray/50"})}),r.jsx("div",{className:`flex-1 ${me?"min-h-0":""}`,children:r.jsx(UJ,{url:c?ie.getLibraryFileDownloadUrl(e):m.has_source?ie.getSource3mfDownloadUrl(t):ie.getArchiveDownload(t),fileType:a,buildVolume:m.build_volume,filamentColors:m.filament_colors,selectedPlateId:N,className:"w-full h-full"})})]}):d==="gcode"&&m?r.jsx(See,{gcodeUrl:c?ie.getLibraryFileGcodeUrl(e):ie.getArchiveGcode(t),filamentColors:m.filament_colors,className:"w-full h-full"}):r.jsx("div",{className:"w-full h-full flex items-center justify-center text-bambu-gray",children:s("modelViewer.noPreview")})})]})})}const nit=90;function rit({onClose:t}){const{t:e}=kt(),n=en(),{showToast:a}=rn(),[i,s]=y.useState(nit),[o,l]=y.useState(!0),[c,d]=y.useState(i);y.useEffect(()=>{const b=window.setTimeout(()=>d(i),300);return()=>window.clearTimeout(b)},[i]);const u=Ge({queryKey:["library-purge-preview",c,o],queryFn:()=>ie.previewLibraryPurge(c,o),enabled:c>=1}),m=it({mutationFn:()=>ie.executeLibraryPurge(i,o),onSuccess:b=>{a(e("libraryPurge.toast.success",{count:b.moved_to_trash}),"success"),n.invalidateQueries({queryKey:["library-files"]}),n.invalidateQueries({queryKey:["library-folders"]}),n.invalidateQueries({queryKey:["library-trash"]}),n.invalidateQueries({queryKey:["library-trash-count"]}),t()},onError:b=>a(b.message||e("libraryPurge.toast.failed"),"error")});y.useEffect(()=>{const b=x=>{x.key==="Escape"&&!m.isPending&&t()};return window.addEventListener("keydown",b),()=>window.removeEventListener("keydown",b)},[t,m.isPending]);const p=u.data,f=p?.count??0,g=p?.total_bytes??0,w=f>0&&!m.isPending;return r.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4",children:r.jsxs("div",{className:"bg-white dark:bg-gray-900 rounded-lg shadow-xl max-w-lg w-full",children:[r.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-gray-200 dark:border-gray-700",children:[r.jsxs("h2",{className:"text-lg font-semibold text-gray-900 dark:text-gray-100 flex items-center gap-2",children:[r.jsx(Jt,{className:"w-5 h-5"}),e("libraryPurge.title")]}),r.jsx("button",{onClick:t,className:"text-gray-400 hover:text-gray-600 dark:hover:text-gray-200","aria-label":e("common.close"),disabled:m.isPending,children:r.jsx(Ht,{className:"w-5 h-5"})})]}),r.jsxs("div",{className:"p-4 space-y-4",children:[r.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-400",children:e("libraryPurge.description")}),r.jsxs("div",{children:[r.jsx("label",{htmlFor:"purge-days",className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1",children:e("libraryPurge.ageLabel")}),r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("input",{id:"purge-days",type:"number",min:1,max:3650,value:i,onChange:b=>s(Math.max(1,Math.min(3650,parseInt(b.target.value||"0",10)||0))),className:"w-24 rounded border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-sm px-2 py-1 text-gray-900 dark:text-gray-100"}),r.jsx("span",{className:"text-sm text-gray-600 dark:text-gray-400",children:e("libraryPurge.days")})]})]}),r.jsxs("label",{className:"flex items-center gap-2 text-sm text-gray-700 dark:text-gray-300",children:[r.jsx("input",{type:"checkbox",checked:o,onChange:b=>l(b.target.checked),className:"rounded border-gray-300"}),e("libraryPurge.includeNeverPrinted")]}),r.jsxs("div",{className:"rounded border border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-800/30 p-3",children:[r.jsx("div",{className:"text-xs font-semibold uppercase tracking-wide text-gray-600 dark:text-gray-300 mb-2",children:e("libraryPurge.effectsTitle")}),r.jsxs("ul",{className:"text-xs text-gray-700 dark:text-gray-300 space-y-1 list-disc pl-4",children:[r.jsx("li",{children:e("libraryPurge.effect1")}),r.jsx("li",{children:e("libraryPurge.effect2")}),r.jsx("li",{children:e("libraryPurge.effect3")}),r.jsx("li",{children:e("libraryPurge.effect4")})]})]}),r.jsx("div",{className:"rounded border border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-800/50 p-3",children:u.isLoading||u.isFetching?r.jsxs("div",{className:"flex items-center gap-2 text-sm text-gray-500 dark:text-gray-400",children:[r.jsx(pt,{className:"w-4 h-4 animate-spin"})," ",e("libraryPurge.previewLoading")]}):u.isError?r.jsx("div",{className:"text-sm text-red-600 dark:text-red-400",children:u.error?.message??e("libraryPurge.previewFailed")}):r.jsxs("div",{className:"text-sm text-gray-900 dark:text-gray-100",children:[r.jsx("div",{className:"font-medium",children:e("libraryPurge.previewSummary",{count:f,size:cs(g)})}),p?.sample_filenames&&p.sample_filenames.length>0&&r.jsxs("ul",{className:"mt-2 text-xs text-gray-600 dark:text-gray-400 space-y-0.5 list-disc pl-4",children:[p.sample_filenames.map(b=>r.jsx("li",{className:"truncate",children:b},b)),f>p.sample_filenames.length&&r.jsx("li",{className:"list-none italic text-gray-500",children:e("libraryPurge.andMore",{count:f-p.sample_filenames.length})})]})]})}),r.jsxs("div",{className:"flex gap-2 items-start text-xs text-amber-700 dark:text-amber-400 bg-amber-50 dark:bg-amber-900/20 rounded px-3 py-2",children:[r.jsx(Nn,{className:"w-4 h-4 mt-0.5 shrink-0"}),r.jsx("span",{children:e("libraryPurge.warning")})]})]}),r.jsxs("div",{className:"flex justify-end gap-2 p-4 border-t border-gray-200 dark:border-gray-700",children:[r.jsx(Me,{variant:"secondary",onClick:t,disabled:m.isPending,children:e("common.cancel")}),r.jsx(Me,{variant:"danger",disabled:!w,onClick:()=>m.mutate(),children:m.isPending?r.jsxs(r.Fragment,{children:[r.jsx(pt,{className:"w-4 h-4 animate-spin mr-1"}),e("libraryPurge.purging")]}):e("libraryPurge.confirmCta",{count:f})})]})]})})}function ait({parentId:t,onClose:e,onSave:n,isLoading:a,t:i}){const[s,o]=y.useState(""),l=c=>{c.preventDefault(),n({name:s.trim(),parent_id:t})};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-sm border border-bambu-dark-tertiary",children:[r.jsx("div",{className:"p-4 border-b border-bambu-dark-tertiary",children:r.jsx("h2",{className:"text-lg font-semibold text-white",children:i("fileManager.newFolder")})}),r.jsxs("form",{onSubmit:l,className:"p-4 space-y-4",children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:i("fileManager.folderName")}),r.jsx("input",{type:"text",value:s,onChange:c=>o(c.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:i("fileManager.folderNamePlaceholder"),autoFocus:!0,required:!0})]}),r.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[r.jsx(Me,{type:"button",variant:"secondary",onClick:e,children:i("common.cancel")}),r.jsx(Me,{type:"submit",disabled:!s.trim()||a,children:a?r.jsx(pt,{className:"w-4 h-4 animate-spin"}):i("common.create")})]})]})]})})}function iit({onClose:t,onSave:e,isLoading:n,t:a}){const[i,s]=y.useState(""),[o,l]=y.useState(""),[c,d]=y.useState(!0),[u,m]=y.useState(!1),p=f=>{f.preventDefault(),e({name:i.trim(),external_path:o.trim(),readonly:c,show_hidden:u})};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-md border border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"p-4 border-b border-bambu-dark-tertiary",children:[r.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[r.jsx(eC,{className:"w-5 h-5 text-bambu-green"}),a("fileManager.linkExternalFolder")]}),r.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:a("fileManager.linkExternalFolderDescription")})]}),r.jsxs("form",{onSubmit:p,className:"p-4 space-y-4",children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:a("fileManager.folderName")}),r.jsx("input",{type:"text",value:i,onChange:f=>s(f.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:a("fileManager.externalFolderNamePlaceholder"),autoFocus:!0,required:!0})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:a("fileManager.externalPath")}),r.jsx("input",{type:"text",value:o,onChange:f=>l(f.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green font-mono text-sm",placeholder:"/mnt/nas/3d-prints",required:!0}),r.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:a("fileManager.externalPathHelp")})]}),r.jsxs("div",{className:"space-y-2",children:[r.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[r.jsx("input",{type:"checkbox",checked:c,onChange:f=>d(f.target.checked),className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),r.jsx("span",{className:"text-sm text-white",children:a("fileManager.readOnly")}),r.jsxs("span",{className:"text-xs text-bambu-gray",children:["(",a("fileManager.readOnlyHelp"),")"]})]}),r.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[r.jsx("input",{type:"checkbox",checked:u,onChange:f=>m(f.target.checked),className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),r.jsx("span",{className:"text-sm text-white",children:a("fileManager.showHiddenFiles")})]})]}),r.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[r.jsx(Me,{type:"button",variant:"secondary",onClick:t,children:a("common.cancel")}),r.jsx(Me,{type:"submit",disabled:!i.trim()||!o.trim()||n,children:n?r.jsx(pt,{className:"w-4 h-4 animate-spin"}):a("fileManager.linkFolder")})]})]})]})})}function sit({type:t,currentName:e,onClose:n,onSave:a,isLoading:i,t:s}){const o=t==="file"?e.match(/(\.gcode\.3mf|\.3mf|\.gcode)$/i)?.[1]??"":"",l=t==="file"&&o?e.slice(0,-o.length):e,[c,d]=y.useState(l),u=m=>{m.preventDefault();const p=t==="file"?c.trim()+o:c.trim();c.trim()&&p!==e&&a(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-sm border border-bambu-dark-tertiary",children:[r.jsx("div",{className:"p-4 border-b border-bambu-dark-tertiary",children:r.jsx("h2",{className:"text-lg font-semibold text-white",children:s(t==="file"?"fileManager.renameFile":"fileManager.renameFolder")})}),r.jsxs("form",{onSubmit:u,className:"p-4 space-y-4",children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("common.name")}),r.jsxs("div",{className:"flex items-center bg-bambu-dark border border-bambu-dark-tertiary rounded focus-within:border-bambu-green",children:[r.jsx("input",{type:"text",value:c,onChange:m=>d(m.target.value),className:"flex-1 bg-transparent px-3 py-2 text-white placeholder-bambu-gray focus:outline-none min-w-0",autoFocus:!0,required:!0}),o&&r.jsx("span",{className:"pr-3 text-bambu-gray text-sm select-none whitespace-nowrap",children:o})]})]}),r.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[r.jsx(Me,{type:"button",variant:"secondary",onClick:n,children:s("common.cancel")}),r.jsx(Me,{type:"submit",disabled:!c.trim()||c.trim()===l||i,children:i?r.jsx(pt,{className:"w-4 h-4 animate-spin"}):s("common.rename")})]})]})]})})}function oit({folders:t,selectedFiles:e,currentFolderId:n,onClose:a,onMove:i,isLoading:s,t:o}){const[l,c]=y.useState(null),d=(m,p=0)=>{const f=[];for(const g of m)f.push({id:g.id,name:g.name,depth:p}),g.children.length>0&&f.push(...d(g.children,p+1));return f},u=[{id:null,name:o("fileManager.rootNoFolder"),depth:0},...d(t)];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-sm border border-bambu-dark-tertiary",children:[r.jsx("div",{className:"p-4 border-b border-bambu-dark-tertiary",children:r.jsx("h2",{className:"text-lg font-semibold text-white",children:o("fileManager.moveFiles",{count:e.length})})}),r.jsxs("div",{className:"p-4 space-y-4",children:[r.jsx("div",{className:"max-h-64 overflow-y-auto space-y-1",children:u.map(m=>r.jsxs("button",{onClick:()=>c(m.id),disabled:m.id===n,className:`w-full text-left px-3 py-2 rounded transition-colors flex items-center gap-2 ${l===m.id?"bg-bambu-green/20 text-bambu-green":m.id===n?"opacity-50 cursor-not-allowed text-bambu-gray":"hover:bg-bambu-dark text-white"}`,style:{paddingLeft:`${12+m.depth*16}px`},children:[r.jsx(Fl,{className:"w-4 h-4"}),m.name,m.id===n&&r.jsxs("span",{className:"text-xs text-bambu-gray ml-auto",children:["(",o("fileManager.current"),")"]})]},m.id??"root"))}),r.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[r.jsx(Me,{type:"button",variant:"secondary",onClick:a,children:o("common.cancel")}),r.jsx(Me,{onClick:()=>i(l),disabled:s,children:s?r.jsx(pt,{className:"w-4 h-4 animate-spin"}):o("common.move")})]})]})]})})}function lit({folder:t,onClose:e,onLink:n,isLoading:a,t:i}){const[s,o]=y.useState("project"),[l,c]=y.useState(t.project_id||t.archive_id||null);y.useState(()=>{t.archive_id&&o("archive")});const{data:d}=Ge({queryKey:["projects"],queryFn:()=>ie.getProjects(),select:g=>[...g].sort((w,b)=>w.name.localeCompare(b.name))}),{data:u}=Ge({queryKey:["archives-for-link"],queryFn:()=>ie.getArchives(void 0,void 0,100)}),m=()=>{n(s==="project"?{project_id:l,archive_id:0}:{project_id:0,archive_id:l})},p=()=>{n({project_id:0,archive_id:0})},f=t.project_id||t.archive_id;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-md 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.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[r.jsx(Th,{className:"w-5 h-5 text-bambu-green"}),i("fileManager.linkFolder")]}),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.jsx("p",{className:"text-sm text-bambu-gray",children:i("fileManager.linkFolderDescription",{name:t.name})}),r.jsxs("div",{className:"flex gap-2",children:[r.jsxs("button",{onClick:()=>{o("project"),c(null)},className:`flex-1 flex items-center justify-center gap-2 px-3 py-2 rounded-lg border transition-colors ${s==="project"?"border-bambu-green bg-bambu-green/10 text-bambu-green":"border-bambu-dark-tertiary text-bambu-gray hover:text-white"}`,children:[r.jsx(CZ,{className:"w-4 h-4"}),i("fileManager.project")]}),r.jsxs("button",{onClick:()=>{o("archive"),c(null)},className:`flex-1 flex items-center justify-center gap-2 px-3 py-2 rounded-lg border transition-colors ${s==="archive"?"border-bambu-green bg-bambu-green/10 text-bambu-green":"border-bambu-dark-tertiary text-bambu-gray hover:text-white"}`,children:[r.jsx(ro,{className:"w-4 h-4"}),i("fileManager.archive")]})]}),r.jsx("div",{className:"max-h-64 overflow-y-auto space-y-1 bg-bambu-dark rounded-lg p-2",children:s==="project"?d&&d.length>0?d.map(g=>r.jsxs("button",{onClick:()=>c(g.id),className:`w-full text-left px-3 py-2 rounded transition-colors flex items-center gap-2 ${l===g.id?"bg-bambu-green/20 text-bambu-green":"hover:bg-bambu-dark-tertiary text-white"}`,children:[r.jsx("div",{className:"w-3 h-3 rounded-full flex-shrink-0",style:{backgroundColor:g.color||"#00ae42"}}),r.jsx("span",{className:"truncate",children:g.name})]},g.id)):r.jsx("p",{className:"text-sm text-bambu-gray text-center py-4",children:i("fileManager.noProjectsFound")}):u&&u.length>0?u.map(g=>r.jsxs("button",{onClick:()=>c(g.id),className:`w-full text-left px-3 py-2 rounded transition-colors flex items-center gap-2 ${l===g.id?"bg-bambu-green/20 text-bambu-green":"hover:bg-bambu-dark-tertiary text-white"}`,children:[r.jsx(Nh,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"}),r.jsx("span",{className:"truncate",children:g.print_name||g.filename})]},g.id)):r.jsx("p",{className:"text-sm text-bambu-gray text-center py-4",children:i("fileManager.noArchivesFound")})})]}),r.jsxs("div",{className:"p-4 border-t border-bambu-dark-tertiary flex justify-between",children:[f&&r.jsxs(Me,{variant:"danger",onClick:p,disabled:a,children:[r.jsx(iu,{className:"w-4 h-4 mr-2"}),i("fileManager.unlink")]}),r.jsxs("div",{className:`flex gap-2 ${f?"":"ml-auto"}`,children:[r.jsx(Me,{variant:"secondary",onClick:e,children:i("common.cancel")}),r.jsx(Me,{onClick:m,disabled:!l||a,children:a?r.jsx(pt,{className:"w-4 h-4 animate-spin"}):i("fileManager.link")})]})]})]})})}function Lce({folder:t,selectedFolderId:e,onSelect:n,onDelete:a,onLink:i,onRename:s,depth:o=0,wrapNames:l=!1,defaultExpanded:c=!0,hasPermission:d,t:u}){const[m,p]=y.useState(c),[f,g]=y.useState(!1),w=t.children.length>0,b=t.project_id||t.archive_id,x=t.is_external;return r.jsxs("div",{children:[r.jsxs("div",{className:`group flex items-center gap-1 px-2 py-1.5 rounded cursor-pointer transition-colors ${e===t.id?"bg-bambu-green/20 text-bambu-green":"hover:bg-bambu-dark text-white"}`,style:{paddingLeft:`${8+o*12}px`},onClick:()=>n(t.id),children:[w?r.jsx("button",{onClick:S=>{S.stopPropagation(),p(!m)},className:"p-0.5 hover:bg-bambu-dark-tertiary rounded",children:r.jsx(Va,{className:`w-3.5 h-3.5 transition-transform ${m?"rotate-90":""}`})}):r.jsx("div",{className:"w-4.5"}),x?r.jsx(eC,{className:"w-4 h-4 text-purple-400 flex-shrink-0"}):r.jsx(Fl,{className:"w-4 h-4 text-bambu-green flex-shrink-0"}),r.jsx("span",{className:`text-sm flex-1 min-w-0 ${l?"break-all":"truncate"}`,title:t.name,children:t.name}),b&&r.jsxs("button",{onClick:S=>{S.stopPropagation(),i(t)},className:"flex-shrink-0 flex items-center gap-1 text-xs px-1.5 py-0.5 rounded bg-blue-500/20 text-blue-400 hover:bg-blue-500/30 transition-colors",title:`${t.project_name?`Project: ${t.project_name}`:`Archive: ${t.archive_name}`} (click to change)`,children:[r.jsx(Th,{className:"w-3 h-3"}),t.project_name?r.jsx(CZ,{className:"w-3 h-3"}):r.jsx(ro,{className:"w-3 h-3"})]}),x&&t.external_readonly&&r.jsx("span",{title:u("fileManager.readOnly"),children:r.jsx(lc,{className:"w-3 h-3 text-amber-400 flex-shrink-0"})}),t.file_count>0&&r.jsx("span",{className:"flex-shrink-0 text-xs text-bambu-gray",children:t.file_count}),!b&&!x&&r.jsx("button",{onClick:S=>{S.stopPropagation(),i(t)},className:"flex-shrink-0 p-1 rounded hover:bg-bambu-dark-tertiary",title:u("fileManager.linkToProjectOrArchive"),children:r.jsx(Th,{className:"w-3.5 h-3.5 text-bambu-gray hover:text-bambu-green"})}),r.jsx("div",{className:`flex-shrink-0 flex items-center gap-0.5 transition-opacity ${l?"":"opacity-0 group-hover:opacity-100"}`,onClick:S=>S.stopPropagation(),children:r.jsxs("div",{className:"relative",children:[r.jsx("button",{onClick:()=>g(!f),className:"p-1 rounded hover:bg-bambu-dark-tertiary",children:r.jsx(ym,{className:"w-3.5 h-3.5 text-bambu-gray"})}),f&&r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>g(!1)}),r.jsxs("div",{className:"absolute right-0 top-full mt-1 z-20 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl py-1 min-w-[120px]",children:[r.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${d("library:update_all")?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{d("library:update_all")&&(s(t),g(!1))},disabled:!d("library:update_all"),title:d("library:update_all")?void 0:u("fileManager.noPermissionRenameFolder"),children:[r.jsx(oi,{className:"w-3.5 h-3.5"}),u("common.rename")]}),r.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${d("library:update_all")?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{d("library:update_all")&&(i(t),g(!1))},disabled:!d("library:update_all"),title:d("library:update_all")?void 0:u("fileManager.noPermissionLinkFolder"),children:[r.jsx(Th,{className:"w-3.5 h-3.5"}),u(b?"fileManager.changeLink":"fileManager.linkTo")]}),r.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${d("library:delete_all")?"text-red-400 hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{d("library:delete_all")&&(a(t.id),g(!1))},disabled:!d("library:delete_all"),title:d("library:delete_all")?void 0:u("fileManager.noPermissionDeleteFolder"),children:[r.jsx(Jt,{className:"w-3.5 h-3.5"}),u("common.delete")]})]})]})]})})]}),w&&m&&r.jsx("div",{children:t.children.map(S=>r.jsx(Lce,{folder:S,selectedFolderId:e,onSelect:n,onDelete:a,onLink:i,onRename:s,depth:o+1,wrapNames:l,defaultExpanded:c,hasPermission:d,t:u},S.id))})]})}function vw(t){const e=t.toLowerCase();return e.endsWith(".gcode")||e.endsWith(".gcode.3mf")}function Ice(t){const e=t.toLowerCase();return e.endsWith(".gcode")||e.endsWith(".gcode.3mf")?!1:e.endsWith(".stl")||e.endsWith(".3mf")||e.endsWith(".step")||e.endsWith(".stp")}function cit({file:t,isSelected:e,isMobile:n,onSelect:a,onDelete:i,onDownload:s,onAddToQueue:o,onPrint:l,onSlice:c,useSlicerApi:d,onPreview3d:u,onRename:m,onGenerateThumbnail:p,thumbnailVersion:f,hasPermission:g,canModify:w,authEnabled:b,t:x}){const[S,N]=y.useState(!1);return r.jsxs("div",{className:`group relative bg-bambu-dark-secondary rounded-lg border transition-all cursor-pointer overflow-hidden ${e?"border-bambu-green ring-1 ring-bambu-green":"border-bambu-dark-tertiary hover:border-bambu-green/50"}`,onClick:()=>a(t.id),children:[r.jsxs("div",{className:"aspect-square bg-bambu-dark flex items-center justify-center overflow-hidden",children:[t.thumbnail_path?r.jsx("img",{src:`${ie.getLibraryFileThumbnailUrl(t.id)}${f?(ie.getLibraryFileThumbnailUrl(t.id).includes("?")?"&":"?")+`v=${f}`:""}`,alt:t.filename,className:"w-full h-full object-cover"}):r.jsx(Nh,{className:"w-12 h-12 text-bambu-gray/30"}),r.jsx("div",{className:`absolute top-2 right-2 text-xs px-1.5 py-0.5 rounded font-medium ${t.file_type==="3mf"?"bg-bambu-green/90 text-white":t.file_type==="gcode"?"bg-blue-500/90 text-white":t.file_type==="stl"?"bg-purple-500/90 text-white":"bg-bambu-gray/90 text-white"}`,children:t.file_type.toUpperCase()})]}),r.jsxs("div",{className:"p-3",children:[r.jsx("h3",{className:"text-sm font-medium text-white truncate",title:t.print_name||t.filename,children:t.print_name||t.filename}),r.jsxs("div",{className:"flex items-center gap-3 mt-1 text-xs text-bambu-gray",children:[r.jsx("span",{children:cs(t.file_size)}),t.print_time_seconds&&r.jsxs("span",{className:"flex items-center gap-1",children:[r.jsx(Zn,{className:"w-3 h-3"}),ds(t.print_time_seconds)]})]}),t.sliced_for_model&&r.jsxs("div",{className:"mt-1 text-xs text-bambu-gray flex items-center gap-1",children:[r.jsx(pr,{className:"w-3 h-3"}),t.sliced_for_model]}),t.print_count>0&&r.jsx("div",{className:"mt-1 text-xs text-bambu-green",children:x("fileManager.printedCount",{count:t.print_count})}),b&&t.created_by_username&&r.jsxs("div",{className:"mt-1 text-xs text-bambu-gray flex items-center gap-1",children:[r.jsx(Vm,{className:"w-3 h-3"}),t.created_by_username]})]}),r.jsxs("div",{className:`absolute bottom-2 right-2 transition-opacity ${n?"opacity-100":"opacity-0 group-hover:opacity-100"}`,onClick:C=>C.stopPropagation(),children:[r.jsx("button",{onClick:()=>N(!S),className:"p-1.5 rounded bg-bambu-dark-secondary/90 hover:bg-bambu-dark-tertiary",children:r.jsx(ym,{className:"w-4 h-4 text-bambu-gray"})}),S&&r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>N(!1)}),r.jsxs("div",{className:"absolute right-0 bottom-8 z-20 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl py-1 min-w-[140px]",children:[l&&vw(t.filename)&&r.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${g("printers:control")?"text-bambu-green hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{g("printers:control")&&(l(t),N(!1))},disabled:!g("printers:control"),title:g("printers:control")?void 0:x("fileManager.noPermissionPrint"),children:[r.jsx(pr,{className:"w-3.5 h-3.5"}),x("common.print")]}),o&&vw(t.filename)&&r.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${g("queue:create")?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{g("queue:create")&&(o(t.id),N(!1))},disabled:!g("queue:create"),title:g("queue:create")?void 0:x("fileManager.noPermissionAddToQueue"),children:[r.jsx(Zn,{className:"w-3.5 h-3.5"}),x("fileManager.schedulePrint")]}),c&&d&&Ice(t.filename)&&r.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${g("library:upload")?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{g("library:upload")&&(c(t),N(!1))},disabled:!g("library:upload"),title:g("library:upload")?void 0:x("fileManager.noPermissionSlice"),children:[r.jsx(cu,{className:"w-3.5 h-3.5"}),x("slice.action")]}),u&&(t.file_type==="3mf"||t.file_type==="gcode"||t.file_type==="stl")&&r.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${g("library:read")?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{g("library:read")&&(u(t),N(!1))},disabled:!g("library:read"),title:g("library:read")?void 0:"You do not have permission to preview files",children:[r.jsx(Ni,{className:"w-3.5 h-3.5"}),"3D Preview"]}),r.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${g("library:read")?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{g("library:read")&&(s(t.id),N(!1))},disabled:!g("library:read"),title:g("library:read")?void 0:x("fileManager.noPermissionDownload"),children:[r.jsx(Yr,{className:"w-3.5 h-3.5"}),x("common.download")]}),m&&r.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${w("library","update",t.created_by_id)?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{w("library","update",t.created_by_id)&&(m(t),N(!1))},disabled:!w("library","update",t.created_by_id),title:w("library","update",t.created_by_id)?void 0:x("fileManager.noPermissionRenameFile"),children:[r.jsx(oi,{className:"w-3.5 h-3.5"}),x("common.rename")]}),p&&t.file_type==="stl"&&r.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${w("library","update",t.created_by_id)?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{w("library","update",t.created_by_id)&&(p(t),N(!1))},disabled:!w("library","update",t.created_by_id),title:w("library","update",t.created_by_id)?void 0:x("fileManager.noPermissionGenerateThumbnail"),children:[r.jsx(du,{className:"w-3.5 h-3.5"}),x("fileManager.generateThumbnail")]}),r.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${w("library","delete",t.created_by_id)?"text-red-400 hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{w("library","delete",t.created_by_id)&&(i(t.id),N(!1))},disabled:!w("library","delete",t.created_by_id),title:w("library","delete",t.created_by_id)?void 0:x("fileManager.noPermissionDeleteFile"),children:[r.jsx(Jt,{className:"w-3.5 h-3.5"}),x("common.delete")]})]})]})]}),r.jsx("div",{className:`absolute top-2 left-2 w-5 h-5 rounded border-2 flex items-center justify-center transition-all ${e?"bg-bambu-green border-bambu-green":`border-white/30 bg-black/30 ${n?"opacity-100":"opacity-0 group-hover:opacity-100"}`}`,children:e&&r.jsx("div",{className:"w-2 h-2 bg-white rounded-sm"})})]})}function dit(){const{t}=kt(),e=en(),{showToast:n}=rn(),{hasPermission:a,hasAnyPermission:i,canModify:s,authEnabled:o}=cr(),[l]=ab(),c=Di(),d=l.get("folder"),u=d?parseInt(d,10):null,[m,p]=y.useState(u),[f,g]=y.useState([]),[w,b]=y.useState(!1),[x,S]=y.useState(!1),[N,C]=y.useState(!1),[P,T]=y.useState(!1),[A,F]=y.useState(!1),[_,E]=y.useState(null),[H,I]=y.useState(null),[U,L]=y.useState(null),[Q,re]=y.useState(null),[J,ce]=y.useState(null),[pe,ue]=y.useState(null),[X,ae]=y.useState(null),[me,ge]=y.useState({}),[Pe,$]=y.useState(null),[W,D]=y.useState(()=>localStorage.getItem("library-view-mode")||"grid"),[j,B]=y.useState(()=>localStorage.getItem("library-wrap-folders")==="true"),[Y,O]=y.useState(()=>localStorage.getItem("library-collapse-folders")==="true"),[se,z]=y.useState(()=>{const je=localStorage.getItem("library-sidebar-width");return je?parseInt(je,10):256}),[G,K]=y.useState(!1),Z=y.useRef(null);y.useEffect(()=>{if(!G)return;document.body.style.userSelect="none",document.body.style.cursor="col-resize";const je=et=>{if(!Z.current)return;const Ie=Z.current.parentElement?.getBoundingClientRect();if(!Ie)return;const mt=et.clientX-Ie.left,he=Math.min(500,Math.max(200,mt));z(he)},Ve=()=>{K(!1),document.body.style.userSelect="",document.body.style.cursor="",localStorage.setItem("library-sidebar-width",String(se))};return document.addEventListener("mousemove",je),document.addEventListener("mouseup",Ve),()=>{document.removeEventListener("mousemove",je),document.removeEventListener("mouseup",Ve),document.body.style.userSelect="",document.body.style.cursor=""}},[G,se]);const[oe,ee]=y.useState(""),[fe,de]=y.useState("all"),[le,q]=y.useState(""),[R,ne]=y.useState(()=>localStorage.getItem("library-sort-field")||"name"),[xe,ve]=y.useState(()=>localStorage.getItem("library-sort-direction")||"asc"),Ce=Qie();y.useEffect(()=>{const je=l.get("folder");if(je){const Ve=parseInt(je,10);p(Ve)}},[l]);const{data:ye}=Ge({queryKey:["settings"],queryFn:()=>ie.getSettings()}),{data:be,isLoading:Ee}=Ge({queryKey:["library-folders"],queryFn:()=>ie.getLibraryFolders()}),{data:ze}=Ge({queryKey:["library-trash-count"],queryFn:async()=>{try{return(await ie.listLibraryTrash(1,0)).total}catch{return 0}},staleTime:3e4}),{data:Oe,isLoading:Be}=Ge({queryKey:["library-files",m],queryFn:()=>ie.getLibraryFiles(m,m===null)}),{data:Se}=Ge({queryKey:["library-stats"],queryFn:()=>ie.getLibraryStats()}),{data:$e}=Ge({queryKey:["users"],queryFn:()=>ie.getUsers()}),rt=y.useMemo(()=>{if(!Oe)return[];const je=new Set(Oe.map(Ve=>Ve.file_type));return Array.from(je).sort()},[Oe]),ot=y.useMemo(()=>{if(!Oe)return[];let je=[...Oe];if(oe.trim()){const Ve=oe.toLowerCase();je=je.filter(et=>et.filename.toLowerCase().includes(Ve)||et.print_name&&et.print_name.toLowerCase().includes(Ve))}if(fe!=="all"&&(je=je.filter(Ve=>Ve.file_type===fe)),le.trim()){const Ve=le.toLowerCase();je=je.filter(et=>et.created_by_username&&et.created_by_username.toLowerCase().includes(Ve))}return je.sort((Ve,et)=>{let Ie=0;switch(R){case"name":Ie=(Ve.print_name||Ve.filename).localeCompare(et.print_name||et.filename);break;case"date":Ie=(Xn(Ve.created_at)?.getTime()??0)-(Xn(et.created_at)?.getTime()??0);break;case"size":Ie=Ve.file_size-et.file_size;break;case"type":Ie=Ve.file_type.localeCompare(et.file_type);break;case"prints":Ie=Ve.print_count-et.print_count;break}return xe==="asc"?Ie:-Ie}),je},[Oe,oe,fe,le,R,xe]),Le=y.useMemo(()=>{if(!Se||!ye)return!1;const je=(ye.library_disk_warning_gb||5)*1024*1024*1024;return Se.disk_free_bytesie.createLibraryFolder(je),onSuccess:()=>{e.invalidateQueries({queryKey:["library-folders"]}),b(!1),n(t("fileManager.toast.folderCreated"),"success")},onError:je=>n(je.message,"error")}),Ne=it({mutationFn:async je=>{const Ve=await ie.createExternalFolder(je);return await ie.scanExternalFolder(Ve.id),Ve},onSuccess:je=>{e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-stats"]}),S(!1),p(je.id),n(t("fileManager.toast.externalFolderLinked"),"success")},onError:je=>n(je.message,"error")}),Qe=it({mutationFn:je=>ie.scanExternalFolder(je),onSuccess:je=>{e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-stats"]}),n(t("fileManager.toast.folderScanned",{added:je.added,removed:je.removed}),"success")},onError:je=>n(je.message,"error")}),Ue=it({mutationFn:je=>ie.deleteLibraryFolder(je),onSuccess:()=>{e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-stats"]}),m===H?.id&&p(null),I(null),n(t("fileManager.toast.folderDeleted"),"success")},onError:je=>{I(null),n(je.message,"error")}}),ke=it({mutationFn:je=>ie.deleteLibraryFile(je),onSuccess:()=>{e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-stats"]}),e.invalidateQueries({queryKey:["library-trash-count"]}),g(je=>je.filter(Ve=>Ve!==H?.id)),I(null),n(t("fileManager.toast.fileDeleted"),"success")},onError:je=>{I(null),n(je.message,"error")}}),De=it({mutationFn:je=>ie.bulkDeleteLibrary(je,[]),onSuccess:(je,Ve)=>{e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-stats"]}),e.invalidateQueries({queryKey:["library-trash-count"]}),n(t("fileManager.toast.filesDeleted",{count:Ve.length}),"success"),g([]),I(null)},onError:je=>{I(null),n(je.message,"error")}}),Ae=it({mutationFn:({fileIds:je,folderId:Ve})=>ie.moveLibraryFiles(je,Ve),onSuccess:()=>{e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-folders"]}),g([]),C(!1),n(t("fileManager.toast.filesMoved"),"success")},onError:je=>n(je.message,"error")}),Xe=it({mutationFn:({id:je,data:Ve})=>ie.updateLibraryFolder(je,Ve),onSuccess:(je,Ve)=>{e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["project-folders"]}),e.invalidateQueries({queryKey:["archive-folders"]}),E(null);const et=Ve.data.project_id===0&&Ve.data.archive_id===0;n(t(et?"fileManager.toast.folderUnlinked":"fileManager.toast.folderLinked"),"success")},onError:je=>n(je.message,"error")}),Ke=it({mutationFn:({id:je,filename:Ve})=>ie.updateLibraryFile(je,{filename:Ve}),onSuccess:()=>{e.invalidateQueries({queryKey:["library-files"]}),ae(null),n(t("fileManager.toast.fileRenamed"),"success")},onError:je=>{ae(null),n(je.message,"error")}}),gt=it({mutationFn:({id:je,name:Ve})=>ie.updateLibraryFolder(je,{name:Ve}),onSuccess:()=>{e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-files"]}),ae(null),n(t("fileManager.toast.folderRenamed"),"success")},onError:je=>{ae(null),n(je.message,"error")}}),ct=it({mutationFn:()=>ie.batchGenerateStlThumbnails({all_missing:!0}),onSuccess:je=>{if(e.invalidateQueries({queryKey:["library-files"]}),je.succeeded>0){const Ve=Date.now(),et={};je.results.forEach(Ie=>{Ie.success&&(et[Ie.file_id]=Ve)}),ge(Ie=>({...Ie,...et}))}je.succeeded>0&&je.failed===0?n(t("fileManager.toast.thumbnailsGenerated",{count:je.succeeded}),"success"):je.succeeded>0&&je.failed>0?n(t("fileManager.toast.thumbnailsGeneratedPartial",{succeeded:je.succeeded,failed:je.failed}),"success"):je.processed===0?n(t("fileManager.toast.noStlMissingThumbnails"),"info"):n(t("fileManager.toast.failedToGenerateThumbnails",{error:je.results[0]?.error||"Unknown error"}),"error")},onError:je=>n(je.message,"error")}),at=it({mutationFn:je=>ie.batchGenerateStlThumbnails({file_ids:[je]}),onSuccess:je=>{if(e.invalidateQueries({queryKey:["library-files"]}),je.succeeded>0){const Ve=je.results[0]?.file_id;Ve&&ge(et=>({...et,[Ve]:Date.now()})),n(t("fileManager.toast.thumbnailGenerated"),"success")}else n(t("fileManager.toast.failedToGenerateThumbnail",{error:je.results[0]?.error||"Unknown error"}),"error")},onError:je=>n(je.message,"error")}),Ot=y.useCallback(je=>{const Ve=je.toLowerCase();return Ve.endsWith(".gcode")||Ve.includes(".gcode.")},[]),Wt=y.useMemo(()=>Oe?Oe.filter(je=>f.includes(je.id)&&Ot(je.filename)):[],[Oe,f,Ot]),Zt=y.useCallback(je=>{g(Ve=>Ve.includes(je)?Ve.filter(et=>et!==je):[...Ve,je])},[]),Yt=y.useCallback(()=>{ot.length>0&&g(ot.map(je=>je.id))},[ot]),un=y.useCallback(()=>{g([])},[]),bn=()=>{e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-stats"]})},dt=je=>{ie.downloadLibraryFile(je).catch(Ve=>{console.error("Library file download failed:",Ve)})},st=()=>{H&&(H.type==="file"?ke.mutate(H.id):H.type==="folder"?Ue.mutate(H.id):H.type==="bulk"&&De.mutate(f))},vt=Ue.isPending||ke.isPending||De.isPending,_t=je=>{D(je),localStorage.setItem("library-view-mode",je)},Dt=Ee||Be,Fe=y.useMemo(()=>{if(!m||!be)return null;const je=Ve=>{for(const et of Ve){if(et.id===m)return et;const Ie=je(et.children);if(Ie)return Ie}return null};return je(be)},[m,be]);return r.jsxs("div",{className:"p-4 md:p-8 min-h-[calc(100vh-64px)] lg:h-[calc(100vh-64px)] flex flex-col",children:[r.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4 mb-6",children:[r.jsxs("div",{children:[r.jsxs("h1",{className:"text-2xl font-bold text-white flex items-center gap-3",children:[r.jsx(Fl,{className:"w-7 h-7 text-bambu-green"}),t("fileManager.title")]}),r.jsx("p",{className:"text-bambu-gray mt-1",children:t("fileManager.subtitle")})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsxs("div",{className:"flex items-center bg-bambu-dark rounded-lg p-1",children:[r.jsx("button",{onClick:()=>_t("grid"),className:`p-1.5 rounded transition-colors ${W==="grid"?"bg-bambu-dark-secondary text-white":"text-bambu-gray hover:text-white"}`,title:t("fileManager.gridView"),children:r.jsx(TS,{className:"w-4 h-4"})}),r.jsx("button",{onClick:()=>_t("list"),className:`p-1.5 rounded transition-colors ${W==="list"?"bg-bambu-dark-secondary text-white":"text-bambu-gray hover:text-white"}`,title:t("fileManager.listView"),children:r.jsx(AS,{className:"w-4 h-4"})})]}),r.jsxs(Me,{variant:"secondary",onClick:()=>ct.mutate(),disabled:ct.isPending||!i("library:update_own","library:update_all"),title:i("library:update_own","library:update_all")?t("fileManager.generateThumbnailsForMissing"):t("fileManager.noPermissionGenerateThumbnail"),children:[ct.isPending?r.jsx(pt,{className:"w-4 h-4 mr-2 animate-spin"}):r.jsx(du,{className:"w-4 h-4 mr-2"}),t("fileManager.generateThumbnails")]}),r.jsxs(Me,{variant:"secondary",onClick:()=>S(!0),disabled:!a("library:upload"),title:a("library:upload")?t("fileManager.linkExternalFolder"):t("fileManager.noPermissionCreateFolder"),children:[r.jsx(eC,{className:"w-4 h-4 mr-2"}),t("fileManager.linkExternal")]}),r.jsxs(Me,{variant:"secondary",onClick:()=>b(!0),disabled:!a("library:upload"),title:a("library:upload")?void 0:t("fileManager.noPermissionCreateFolder"),children:[r.jsx(mbe,{className:"w-4 h-4 mr-2"}),t("fileManager.newFolder")]}),a("library:purge")&&r.jsxs(Me,{variant:"secondary",onClick:()=>F(!0),title:t("libraryPurge.headerTooltip"),children:[r.jsx(Jt,{className:"w-4 h-4 mr-2"}),t("libraryPurge.headerButton")]}),i("library:delete_own","library:delete_all")&&r.jsxs(Is,{to:"/files/trash",className:"inline-flex items-center px-3 py-1.5 text-sm rounded bg-bambu-dark-secondary text-bambu-gray hover:text-white hover:bg-bambu-dark transition-colors",title:t("libraryTrash.headerTooltip"),children:[r.jsx(Jt,{className:"w-4 h-4 mr-2"}),t("libraryTrash.headerButton"),typeof ze=="number"&&ze>0&&r.jsx("span",{className:"ml-1.5 px-1.5 py-0.5 text-xs rounded-full bg-bambu-green/20 text-bambu-green",children:ze})]}),r.jsxs(Me,{onClick:()=>T(!0),disabled:!a("library:upload"),title:a("library:upload")?void 0:t("fileManager.noPermissionUpload"),children:[r.jsx(ka,{className:"w-4 h-4 mr-2"}),t("common.upload")]})]})]}),Le&&Se&&ye&&r.jsxs("div",{className:"flex items-center gap-3 mb-4 p-3 bg-amber-500/10 border border-amber-500/30 rounded-lg",children:[r.jsx(Nn,{className:"w-5 h-5 text-amber-500 flex-shrink-0"}),r.jsxs("div",{className:"flex-1",children:[r.jsx("p",{className:"text-sm text-amber-500 font-medium",children:t("fileManager.lowDiskSpaceWarning")}),r.jsx("p",{className:"text-xs text-amber-500/80",children:t("fileManager.lowDiskSpaceDetails",{free:cs(Se.disk_free_bytes),total:cs(Se.disk_total_bytes),threshold:ye.library_disk_warning_gb})})]})]}),Se&&r.jsxs("div",{className:"flex flex-wrap items-center gap-3 sm:gap-6 mb-6 p-3 bg-bambu-dark-secondary rounded-lg border border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[r.jsx(_T,{className:"w-4 h-4 text-bambu-green"}),r.jsxs("span",{className:"text-bambu-gray",children:[t("fileManager.files"),":"]}),r.jsx("span",{className:"text-white font-medium",children:Se.total_files})]}),r.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[r.jsx(Fl,{className:"w-4 h-4 text-blue-400"}),r.jsxs("span",{className:"text-bambu-gray",children:[t("fileManager.folders"),":"]}),r.jsx("span",{className:"text-white font-medium",children:Se.total_folders})]}),r.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[r.jsx(ob,{className:"w-4 h-4 text-amber-400"}),r.jsxs("span",{className:"text-bambu-gray",children:[t("fileManager.size"),":"]}),r.jsx("span",{className:"text-white font-medium",children:cs(Se.total_size_bytes)})]}),r.jsxs("div",{className:"flex items-center gap-2 text-sm sm:ml-auto",children:[r.jsxs("span",{className:"text-bambu-gray",children:[t("fileManager.free"),":"]}),r.jsx("span",{className:`font-medium ${Le?"text-amber-500":"text-white"}`,children:cs(Se.disk_free_bytes)})]})]}),r.jsxs("div",{className:"flex-1 flex flex-col lg:flex-row gap-4 lg:gap-6 min-h-0",children:[r.jsx("div",{className:"lg:hidden",children:r.jsxs("select",{value:m??"",onChange:je=>p(je.target.value?parseInt(je.target.value,10):null),className:"w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg px-3 py-2.5 text-white focus:outline-none focus:border-bambu-green",children:[r.jsxs("option",{value:"",children:["📁 ",t("fileManager.allFiles")]}),be&&(()=>{const je=(Ve,et=0)=>{const Ie=[];for(const mt of Ve)Ie.push({id:mt.id,name:mt.name,fileCount:mt.file_count,depth:et}),mt.children.length>0&&Ie.push(...je(mt.children,et+1));return Ie};return je(be).map(Ve=>r.jsxs("option",{value:Ve.id,children:["│ ".repeat(Ve.depth),"📂 ",Ve.name," ",Ve.fileCount>0?`(${Ve.fileCount})`:""]},Ve.id))})()]})}),r.jsxs("div",{ref:Z,className:"hidden lg:flex flex-shrink-0 bg-bambu-dark-secondary rounded-lg border border-bambu-dark-tertiary overflow-hidden flex-col relative",style:{width:`${se}px`},children:[r.jsx("div",{className:`absolute right-0 top-0 bottom-0 w-1.5 cursor-col-resize z-10 group/resize flex items-center justify-center transition-colors ${G?"bg-bambu-green":"hover:bg-bambu-green/50"}`,onMouseDown:je=>{je.preventDefault(),K(!0)},onDoubleClick:()=>{z(256),localStorage.setItem("library-sidebar-width","256")},title:t("fileManager.dragToResizeTooltip"),children:r.jsxs("div",{className:`flex flex-col gap-1 opacity-0 group-hover/resize:opacity-100 transition-opacity ${G?"opacity-100":""}`,children:[r.jsx("div",{className:"w-0.5 h-0.5 rounded-full bg-white/70"}),r.jsx("div",{className:"w-0.5 h-0.5 rounded-full bg-white/70"}),r.jsx("div",{className:"w-0.5 h-0.5 rounded-full bg-white/70"})]})}),r.jsxs("div",{className:"p-3 border-b border-bambu-dark-tertiary flex items-center justify-between",children:[r.jsx("h2",{className:"text-sm font-medium text-white",children:t("fileManager.folders")}),r.jsxs("div",{className:"flex items-center gap-1",children:[r.jsx("button",{onClick:()=>{const je=!Y;O(je),localStorage.setItem("library-collapse-folders",String(je))},className:`text-xs px-1.5 py-0.5 rounded transition-colors ${Y?"bg-bambu-green/20 text-bambu-green":"text-bambu-gray hover:text-white hover:bg-bambu-dark"}`,title:t(Y?"fileManager.expandFoldersByDefault":"fileManager.collapseFoldersByDefault"),children:t("fileManager.collapse")}),r.jsx("button",{onClick:()=>{const je=!j;B(je),localStorage.setItem("library-wrap-folders",String(je))},className:`text-xs px-1.5 py-0.5 rounded transition-colors ${j?"bg-bambu-green/20 text-bambu-green":"text-bambu-gray hover:text-white hover:bg-bambu-dark"}`,title:t(j?"fileManager.disableTextWrapping":"fileManager.enableTextWrapping"),children:t("fileManager.wrap")})]})]}),r.jsxs("div",{className:"flex-1 overflow-y-auto p-2",children:[r.jsxs("div",{className:`flex items-center gap-2 px-2 py-1.5 rounded cursor-pointer transition-colors ${m===null?"bg-bambu-green/20 text-bambu-green":"hover:bg-bambu-dark text-white"}`,onClick:()=>p(null),children:[r.jsx(Nh,{className:"w-4 h-4"}),r.jsx("span",{className:"text-sm",children:t("fileManager.allFiles")})]}),be?.map(je=>r.jsx(Lce,{folder:je,selectedFolderId:m,onSelect:p,onDelete:Ve=>I({type:"folder",id:Ve}),onLink:E,onRename:Ve=>ae({type:"folder",id:Ve.id,name:Ve.name}),wrapNames:j,defaultExpanded:!Y,hasPermission:a,t},`${je.id}-${Y?"c":"e"}`))]})]}),r.jsxs("div",{className:"flex-1 flex flex-col min-w-0 min-h-0",children:[Fe?.is_external&&r.jsxs("div",{className:"flex items-center gap-3 mb-4 p-3 bg-purple-500/10 border border-purple-500/30 rounded-lg",children:[r.jsx(eC,{className:"w-5 h-5 text-purple-400 flex-shrink-0"}),r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("span",{className:"text-sm font-medium text-purple-300",children:t("fileManager.externalFolder")}),Fe.external_readonly&&r.jsxs("span",{className:"text-xs px-1.5 py-0.5 rounded bg-amber-500/20 text-amber-400 flex items-center gap-1",children:[r.jsx(lc,{className:"w-3 h-3"}),t("fileManager.readOnly")]})]}),r.jsx("p",{className:"text-xs text-bambu-gray truncate font-mono",title:Fe.external_path||"",children:Fe.external_path})]}),r.jsxs(Me,{variant:"secondary",size:"sm",onClick:()=>m&&Qe.mutate(m),disabled:Qe.isPending,title:t("fileManager.scanFolder"),children:[Qe.isPending?r.jsx(pt,{className:"w-4 h-4 animate-spin"}):r.jsx(er,{className:"w-4 h-4"}),r.jsx("span",{className:"ml-1.5",children:t("fileManager.scanFolder")})]})]}),Oe&&Oe.length>0&&r.jsxs("div",{className:"flex flex-wrap items-center gap-2 sm:gap-3 mb-4 p-2 sm:p-3 bg-bambu-dark-secondary rounded-lg border border-bambu-dark-tertiary sticky top-0 z-10 lg:static",children:[r.jsxs("div",{className:"relative w-full sm:w-auto sm:flex-1 sm:max-w-xs",children:[r.jsx(Sr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),r.jsx("input",{type:"text",placeholder:t("fileManager.searchFiles"),value:oe,onChange:je=>ee(je.target.value),className:"w-full pl-9 pr-3 py-1.5 bg-bambu-dark border border-bambu-dark-tertiary rounded text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green"})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(NS,{className:"w-4 h-4 text-bambu-gray hidden sm:block"}),r.jsxs("select",{value:fe,onChange:je=>de(je.target.value),className:"bg-bambu-dark border border-bambu-dark-tertiary rounded px-2 py-1.5 text-sm text-white focus:outline-none focus:border-bambu-green",children:[r.jsx("option",{value:"all",children:t("fileManager.allTypes")}),rt.map(je=>r.jsx("option",{value:je,children:je.toUpperCase()},je))]})]}),o&&r.jsxs("div",{className:"relative",children:[r.jsx("input",{type:"text",placeholder:t("fileManager.filterByUser",{defaultValue:"Filter by user"}),value:le,onChange:je=>q(je.target.value),list:"usernames-list",className:`w-32 sm:w-40 px-2 py-1.5 bg-bambu-dark border border-bambu-dark-tertiary rounded text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green ${le?"pr-7":""}`,style:le?{WebkitAppearance:"none",MozAppearance:"textfield"}:void 0}),le&&r.jsx("button",{onClick:()=>q(""),className:"absolute right-2 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white z-10",children:r.jsx(Ht,{className:"w-3 h-3"})}),r.jsx("datalist",{id:"usernames-list",children:$e?.map(je=>r.jsx("option",{value:je.username},je.id))})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsxs("select",{value:R,onChange:je=>{const Ve=je.target.value;ne(Ve),localStorage.setItem("library-sort-field",Ve)},className:"bg-bambu-dark border border-bambu-dark-tertiary rounded px-2 py-1.5 text-sm text-white focus:outline-none focus:border-bambu-green",children:[r.jsx("option",{value:"name",children:t("common.name")}),r.jsx("option",{value:"date",children:t("common.date")}),r.jsx("option",{value:"size",children:t("fileManager.size")}),r.jsx("option",{value:"type",children:t("common.type")}),r.jsx("option",{value:"prints",children:t("fileManager.prints")})]}),r.jsx("button",{onClick:()=>ve(je=>{const Ve=je==="asc"?"desc":"asc";return localStorage.setItem("library-sort-direction",Ve),Ve}),className:"p-1.5 rounded bg-bambu-dark border border-bambu-dark-tertiary hover:border-bambu-green transition-colors",title:t(xe==="asc"?"fileManager.ascending":"fileManager.descending"),children:xe==="asc"?r.jsx(gfe,{className:"w-4 h-4 text-white"}):r.jsx(cfe,{className:"w-4 h-4 text-white"})})]}),(oe||fe!=="all"||le)&&r.jsx("span",{className:"text-sm text-bambu-gray hidden sm:inline",children:t("fileManager.resultsCount",{showing:ot.length,total:Oe.length})})]}),ot.length>0&&r.jsxs("div",{className:"flex flex-wrap items-center gap-2 mb-4 p-2 bg-bambu-dark-secondary rounded-lg border border-bambu-dark-tertiary sticky top-[52px] z-10 lg:static",children:[f.length===ot.length&&f.length>0?r.jsxs(Me,{variant:"secondary",size:"sm",onClick:un,children:[r.jsx(so,{className:"w-4 h-4 sm:mr-1"}),r.jsx("span",{className:"hidden sm:inline",children:t("fileManager.deselectAll")})]}):r.jsxs(Me,{variant:"secondary",size:"sm",onClick:Yt,children:[r.jsx(bs,{className:"w-4 h-4 sm:mr-1"}),r.jsx("span",{className:"hidden sm:inline",children:t("fileManager.selectAll")})]}),f.length>0&&r.jsxs(r.Fragment,{children:[r.jsx("span",{className:"text-sm text-bambu-gray ml-2",children:t("fileManager.selected",{count:f.length})}),r.jsx("div",{className:"hidden sm:block flex-1"}),r.jsxs("div",{className:"w-full sm:w-auto flex flex-wrap items-center gap-2 mt-2 sm:mt-0",children:[Wt.length===1&&r.jsxs(Me,{variant:"primary",size:"sm",onClick:()=>re(Wt[0]),disabled:!a("printers:control"),title:a("printers:control")?void 0:t("fileManager.noPermissionPrint"),children:[r.jsx(fs,{className:"w-4 h-4 sm:mr-1"}),r.jsx("span",{className:"hidden sm:inline",children:t("common.print")})]}),Wt.length===1&&r.jsxs(Me,{variant:"secondary",size:"sm",onClick:()=>ce(Wt[0]),disabled:!a("queue:create"),title:a("queue:create")?void 0:t("fileManager.noPermissionAddToQueue"),children:[r.jsx(Zn,{className:"w-4 h-4 sm:mr-1"}),r.jsx("span",{className:"hidden sm:inline",children:t("fileManager.schedulePrint")})]}),r.jsxs(Me,{variant:"secondary",size:"sm",onClick:()=>C(!0),disabled:!i("library:update_own","library:update_all"),title:i("library:update_own","library:update_all")?void 0:t("fileManager.noPermissionMoveFiles"),children:[r.jsx(Cxe,{className:"w-4 h-4 sm:mr-1"}),r.jsx("span",{className:"hidden sm:inline",children:t("common.move")})]}),r.jsxs(Me,{variant:"danger",size:"sm",onClick:()=>{f.length===1?I({type:"file",id:f[0]}):I({type:"bulk",id:0,count:f.length})},disabled:!i("library:delete_own","library:delete_all"),title:i("library:delete_own","library:delete_all")?void 0:t("fileManager.noPermissionDeleteFiles"),children:[r.jsx(Jt,{className:"w-4 h-4 sm:mr-1"}),r.jsx("span",{className:"hidden sm:inline",children:t("common.delete")})]}),r.jsxs(Me,{variant:"secondary",size:"sm",onClick:un,children:[r.jsx(Ht,{className:"w-4 h-4 sm:mr-1"}),r.jsx("span",{className:"hidden sm:inline",children:t("common.clear")})]})]})]})]}),Dt?r.jsx("div",{className:"flex-1 flex items-center justify-center",children:r.jsxs("div",{className:"flex flex-col items-center gap-3",children:[r.jsx(pt,{className:"w-8 h-8 animate-spin text-bambu-green"}),r.jsx("p",{className:"text-sm text-bambu-gray",children:t("fileManager.loadingFiles")})]})}):Oe?.length===0?r.jsxs("div",{className:"flex-1 flex flex-col items-center justify-center",children:[r.jsx("div",{className:"p-4 bg-bambu-dark rounded-2xl mb-4",children:r.jsx(Nh,{className:"w-12 h-12 text-bambu-gray/50"})}),r.jsx("h3",{className:"text-lg font-medium text-white mb-2",children:t(m!==null?"fileManager.folderIsEmpty":"fileManager.noFilesYet")}),r.jsx("p",{className:"text-bambu-gray text-center max-w-md mb-6",children:t(m!==null?"fileManager.folderEmptyDescription":"fileManager.noFilesDescription")}),r.jsxs(Me,{onClick:()=>T(!0),disabled:!a("library:upload"),title:a("library:upload")?void 0:t("fileManager.noPermissionUpload"),children:[r.jsx(ir,{className:"w-4 h-4 mr-2"}),t("fileManager.uploadFiles")]})]}):ot.length===0?r.jsxs("div",{className:"flex-1 flex flex-col items-center justify-center",children:[r.jsx("div",{className:"p-4 bg-bambu-dark rounded-2xl mb-4",children:r.jsx(Sr,{className:"w-12 h-12 text-bambu-gray/50"})}),r.jsx("h3",{className:"text-lg font-medium text-white mb-2",children:t("fileManager.noMatchingFiles")}),r.jsx("p",{className:"text-bambu-gray text-center max-w-md mb-6",children:t("fileManager.noMatchingFilesDescription")}),r.jsx(Me,{variant:"secondary",onClick:()=>{ee(""),de("all")},children:t("fileManager.clearFilters")})]}):W==="grid"?r.jsx("div",{className:"flex-1 lg:overflow-y-auto",children:r.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 2xl:grid-cols-6 gap-4",children:ot.map(je=>r.jsx(cit,{file:je,isSelected:f.includes(je.id),isMobile:Ce,t,onSelect:Zt,onDelete:Ve=>I({type:"file",id:Ve}),onDownload:dt,onAddToQueue:Ve=>{const et=Oe?.find(Ie=>Ie.id===Ve);et&&ce(et)},onPrint:L,onSlice:ue,useSlicerApi:ye?.use_slicer_api??!1,onPreview3d:Ve=>{vw(Ve.filename)?c(`/gcode-viewer?library_file=${Ve.id}`):$(Ve)},onRename:Ve=>ae({type:"file",id:Ve.id,name:Ve.filename}),onGenerateThumbnail:Ve=>at.mutate(Ve.id),thumbnailVersion:me[je.id],hasPermission:a,canModify:s,authEnabled:o},je.id))})}):r.jsx("div",{className:"flex-1 lg:overflow-y-auto",children:r.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg border border-bambu-dark-tertiary overflow-hidden",children:[r.jsxs("div",{className:`hidden sm:grid ${o?"grid-cols-[auto_1fr_120px_100px_100px_100px_80px]":"grid-cols-[auto_1fr_100px_100px_100px_80px]"} gap-4 px-4 py-2 bg-bambu-dark-secondary border-b border-bambu-dark-tertiary text-xs text-bambu-gray font-medium`,children:[r.jsx("div",{className:"w-6"}),r.jsx("div",{children:t("common.name")}),o&&r.jsx("div",{children:t("fileManager.uploadedBy",{defaultValue:"Uploaded By"})}),r.jsx("div",{children:t("common.type")}),r.jsx("div",{children:t("fileManager.size")}),r.jsx("div",{children:t("fileManager.prints")}),r.jsx("div",{})]}),ot.map(je=>r.jsxs("div",{className:`grid ${o?"grid-cols-[auto_1fr_120px_100px_100px_100px_80px]":"grid-cols-[auto_1fr_100px_100px_100px_80px]"} gap-4 px-4 py-3 items-center border-b border-bambu-dark-tertiary last:border-b-0 cursor-pointer hover:bg-bambu-dark/50 transition-colors ${f.includes(je.id)?"bg-bambu-green/10":""}`,onClick:()=>Zt(je.id),children:[r.jsx("div",{className:`w-5 h-5 rounded border-2 flex items-center justify-center ${f.includes(je.id)?"bg-bambu-green border-bambu-green":"border-bambu-gray/50"}`,children:f.includes(je.id)&&r.jsx("div",{className:"w-2 h-2 bg-white rounded-sm"})}),r.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[r.jsxs("div",{className:"relative group/thumb",children:[r.jsx("div",{className:"w-10 h-10 rounded bg-bambu-dark flex-shrink-0 overflow-hidden",children:je.thumbnail_path?r.jsx("img",{src:`${ie.getLibraryFileThumbnailUrl(je.id)}${me[je.id]?(ie.getLibraryFileThumbnailUrl(je.id).includes("?")?"&":"?")+`v=${me[je.id]}`:""}`,alt:"",className:"w-full h-full object-cover"}):r.jsx("div",{className:"w-full h-full flex items-center justify-center",children:r.jsx(Nh,{className:"w-5 h-5 text-bambu-gray/50"})})}),je.thumbnail_path&&r.jsx("div",{className:"absolute left-0 top-full mt-2 z-50 hidden group-hover/thumb:block",children:r.jsx("div",{className:"w-48 h-48 rounded-lg bg-bambu-dark-secondary border border-bambu-dark-tertiary shadow-xl overflow-hidden",children:r.jsx("img",{src:`${ie.getLibraryFileThumbnailUrl(je.id)}${me[je.id]?(ie.getLibraryFileThumbnailUrl(je.id).includes("?")?"&":"?")+`v=${me[je.id]}`:""}`,alt:je.filename,className:"w-full h-full object-contain"})})})]}),r.jsx("div",{className:"min-w-0",children:r.jsx("div",{className:"text-sm text-white truncate",children:je.print_name||je.filename})})]}),o&&r.jsx("div",{className:"text-sm text-bambu-gray flex items-center gap-1",children:je.created_by_username?r.jsxs(r.Fragment,{children:[r.jsx(Vm,{className:"w-3 h-3"}),r.jsx("span",{className:"truncate",children:je.created_by_username})]}):"-"}),r.jsx("div",{children:r.jsx("span",{className:`text-xs px-1.5 py-0.5 rounded font-medium ${je.file_type==="3mf"?"bg-bambu-green/20 text-bambu-green":je.file_type==="gcode"?"bg-blue-500/20 text-blue-400":je.file_type==="stl"?"bg-purple-500/20 text-purple-400":"bg-bambu-gray/20 text-bambu-gray"}`,children:je.file_type.toUpperCase()})}),r.jsx("div",{className:"text-sm text-bambu-gray",children:cs(je.file_size)}),r.jsx("div",{className:"text-sm text-bambu-gray",children:je.print_count>0?`${je.print_count}x`:"-"}),r.jsxs("div",{className:"flex items-center gap-1",onClick:Ve=>Ve.stopPropagation(),children:[vw(je.filename)&&r.jsxs(r.Fragment,{children:[r.jsx("button",{onClick:()=>a("printers:control")&&L(je),className:`p-1.5 rounded transition-colors ${a("printers:control")?"hover:bg-bambu-dark text-bambu-gray hover:text-bambu-green":"text-bambu-gray/50 cursor-not-allowed"}`,title:a("printers:control")?t("common.print"):t("fileManager.noPermissionPrint"),disabled:!a("printers:control"),children:r.jsx(pr,{className:"w-4 h-4"})}),r.jsx("button",{onClick:()=>{a("queue:create")&&ce(je)},className:`p-1.5 rounded transition-colors ${a("queue:create")?"hover:bg-bambu-dark text-bambu-gray hover:text-white":"text-bambu-gray/50 cursor-not-allowed"}`,title:a("queue:create")?t("fileManager.schedulePrint"):t("fileManager.noPermissionAddToQueue"),disabled:!a("queue:create"),children:r.jsx(Zn,{className:"w-4 h-4"})})]}),(ye?.use_slicer_api??!1)&&Ice(je.filename)&&r.jsx("button",{onClick:()=>a("library:upload")&&ue(je),className:`p-1.5 rounded transition-colors ${a("library:upload")?"hover:bg-bambu-dark text-bambu-gray hover:text-bambu-green":"text-bambu-gray/50 cursor-not-allowed"}`,title:a("library:upload")?t("slice.action"):t("fileManager.noPermissionSlice"),disabled:!a("library:upload"),children:r.jsx(cu,{className:"w-4 h-4"})}),(je.file_type==="3mf"||je.file_type==="gcode"||je.file_type==="stl")&&r.jsx("button",{onClick:()=>{a("library:read")&&(vw(je.filename)?c(`/gcode-viewer?library_file=${je.id}`):$(je))},className:`p-1.5 rounded transition-colors ${a("library:read")?"hover:bg-bambu-dark text-bambu-gray hover:text-bambu-green":"text-bambu-gray/50 cursor-not-allowed"}`,title:a("library:read")?"3D Preview":"You do not have permission to preview files",disabled:!a("library:read"),children:r.jsx(Ni,{className:"w-4 h-4"})}),r.jsx("button",{onClick:()=>a("library:read")&&dt(je.id),className:`p-1.5 rounded transition-colors ${a("library:read")?"hover:bg-bambu-dark text-bambu-gray hover:text-white":"text-bambu-gray/50 cursor-not-allowed"}`,title:a("library:read")?t("common.download"):t("fileManager.noPermissionDownload"),disabled:!a("library:read"),children:r.jsx(Yr,{className:"w-4 h-4"})}),r.jsx("button",{onClick:()=>s("library","update",je.created_by_id)&&ae({type:"file",id:je.id,name:je.filename}),className:`p-1.5 rounded transition-colors ${s("library","update",je.created_by_id)?"hover:bg-bambu-dark text-bambu-gray hover:text-white":"text-bambu-gray/50 cursor-not-allowed"}`,title:s("library","update",je.created_by_id)?t("common.rename"):t("fileManager.noPermissionRenameFile"),disabled:!s("library","update",je.created_by_id),children:r.jsx(oi,{className:"w-4 h-4"})}),je.file_type==="stl"&&r.jsx("button",{onClick:()=>s("library","update",je.created_by_id)&&at.mutate(je.id),className:`p-1.5 rounded transition-colors ${s("library","update",je.created_by_id)?"hover:bg-bambu-dark text-bambu-gray hover:text-bambu-green":"text-bambu-gray/50 cursor-not-allowed"}`,title:s("library","update",je.created_by_id)?t("fileManager.generateThumbnail"):t("fileManager.noPermissionGenerateThumbnail"),disabled:at.isPending||!s("library","update",je.created_by_id),children:r.jsx(du,{className:"w-4 h-4"})}),r.jsx("button",{onClick:()=>s("library","delete",je.created_by_id)&&I({type:"file",id:je.id}),className:`p-1.5 rounded transition-colors ${s("library","delete",je.created_by_id)?"hover:bg-bambu-dark text-bambu-gray hover:text-red-400":"text-bambu-gray/50 cursor-not-allowed"}`,title:s("library","delete",je.created_by_id)?t("common.delete"):t("fileManager.noPermissionDeleteFile"),disabled:!s("library","delete",je.created_by_id),children:r.jsx(Jt,{className:"w-4 h-4"})})]})]},je.id))]})})]})]}),w&&r.jsx(ait,{parentId:m,onClose:()=>b(!1),onSave:je=>nt.mutate(je),isLoading:nt.isPending,t}),x&&r.jsx(iit,{onClose:()=>S(!1),onSave:je=>Ne.mutate(je),isLoading:Ne.isPending,t}),N&&be&&r.jsx(oit,{folders:be,selectedFiles:f,currentFolderId:m,onClose:()=>C(!1),onMove:je=>Ae.mutate({fileIds:f,folderId:je}),isLoading:Ae.isPending,t}),P&&r.jsx(Uie,{folderId:m,onClose:()=>T(!1),onUploadComplete:bn}),A&&r.jsx(rit,{onClose:()=>F(!1)}),_&&r.jsx(lit,{folder:_,onClose:()=>E(null),onLink:je=>Xe.mutate({id:_.id,data:je}),isLoading:Xe.isPending,t}),H&&r.jsx(vn,{title:H.type==="folder"?t("fileManager.deleteFolder"):H.type==="bulk"?t("fileManager.deleteFilesCount",{count:H.count}):t("fileManager.deleteFile"),message:H.type==="folder"?t("fileManager.deleteFolderConfirm"):H.type==="bulk"?t("fileManager.deleteFilesConfirm",{count:H.count}):t("fileManager.deleteFileConfirm"),confirmText:t("common.delete"),variant:"danger",isLoading:vt,loadingText:t("fileManager.deleting"),onConfirm:st,onCancel:()=>I(null)}),U&&r.jsx(Sc,{mode:"reprint",libraryFileId:U.id,archiveName:U.print_name||U.filename,onClose:()=>L(null),onSuccess:()=>{L(null),e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["archives"]})}}),Q&&r.jsx(Sc,{mode:"reprint",libraryFileId:Q.id,archiveName:Q.print_name||Q.filename,onClose:()=>re(null),onSuccess:()=>{re(null),g([]),e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["archives"]})}}),J&&r.jsx(Sc,{mode:"add-to-queue",libraryFileId:J.id,archiveName:J.print_name||J.filename,onClose:()=>ce(null),onSuccess:()=>{ce(null),g([]),e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["queue"]}),e.invalidateQueries({queryKey:["archives"]})}}),pe&&r.jsx(FA,{source:{kind:"libraryFile",id:pe.id,filename:pe.filename},onClose:()=>ue(null)}),Pe&&r.jsx(tit,{libraryFileId:Pe.id,title:Pe.print_name||Pe.filename,fileType:Pe.file_type,onClose:()=>$(null)}),X&&r.jsx(sit,{type:X.type,currentName:X.name,onClose:()=>ae(null),onSave:je=>{X.type==="file"?Ke.mutate({id:X.id,filename:je}):gt.mutate({id:X.id,name:je})},isLoading:Ke.isPending||gt.isPending,t})]})}function uit(t){const e=Xn(t);if(!e)return"";const n=Math.ceil((e.getTime()-Date.now())/(1e3*60*60*24));return n<=0?"any moment":n===1?"1 day":`${n} days`}function hQ(t){const e=Xn(t);return e?e.toLocaleString():t}function mit(){const{t}=kt(),e=Di(),n=en(),{showToast:a}=rn(),{hasPermission:i,authEnabled:s}=cr(),[o,l]=y.useState(null),[c,d]=y.useState(new Set),u=!s||i("library:purge"),m=Ge({queryKey:["library-trash"],queryFn:()=>ie.listLibraryTrash(200,0)}),p=Ge({queryKey:["library-trash-settings"],queryFn:()=>ie.getLibraryTrashSettings(),enabled:u}),[f,g]=y.useState(null);y.useEffect(()=>{p.data&&f===null&&g(p.data.retention_days)},[p.data,f]);const w=it({mutationFn:U=>{const L=p.data;return ie.updateLibraryTrashSettings({retention_days:U,auto_purge_enabled:L?.auto_purge_enabled??!1,auto_purge_days:L?.auto_purge_days??90,auto_purge_include_never_printed:L?.auto_purge_include_never_printed??!0})},onSuccess:U=>{a(t("libraryTrash.toast.retentionSaved",{days:U.retention_days}),"success"),n.invalidateQueries({queryKey:["library-trash-settings"]}),n.invalidateQueries({queryKey:["library-trash"]})},onError:U=>a(U.message||t("libraryTrash.toast.retentionFailed"),"error")}),b=it({mutationFn:U=>ie.restoreLibraryTrash(U),onSuccess:()=>{a(t("libraryTrash.toast.restored"),"success"),n.invalidateQueries({queryKey:["library-trash"]}),n.invalidateQueries({queryKey:["library-trash-count"]}),n.invalidateQueries({queryKey:["library-files"]}),n.invalidateQueries({queryKey:["library-folders"]})},onError:U=>a(U.message||t("libraryTrash.toast.restoreFailed"),"error")}),x=it({mutationFn:U=>ie.hardDeleteLibraryTrash(U),onSuccess:()=>{a(t("libraryTrash.toast.purged"),"success"),n.invalidateQueries({queryKey:["library-trash"]}),n.invalidateQueries({queryKey:["library-trash-count"]})},onError:U=>a(U.message||t("libraryTrash.toast.purgeFailed"),"error")}),S=it({mutationFn:()=>ie.emptyLibraryTrash(),onSuccess:U=>{a(t("libraryTrash.toast.emptied",{count:U.deleted}),"success"),n.invalidateQueries({queryKey:["library-trash"]}),n.invalidateQueries({queryKey:["library-trash-count"]})},onError:U=>a(U.message||t("libraryTrash.toast.emptyFailed"),"error")}),N=it({mutationFn:U=>Promise.all(U.map(L=>ie.restoreLibraryTrash(L))),onSuccess:(U,L)=>{a(t("libraryTrash.toast.bulkRestored",{count:L.length}),"success"),d(new Set),n.invalidateQueries({queryKey:["library-trash"]}),n.invalidateQueries({queryKey:["library-trash-count"]}),n.invalidateQueries({queryKey:["library-files"]}),n.invalidateQueries({queryKey:["library-folders"]})},onError:U=>a(U.message||t("libraryTrash.toast.restoreFailed"),"error")}),C=it({mutationFn:U=>Promise.all(U.map(L=>ie.hardDeleteLibraryTrash(L))),onSuccess:(U,L)=>{a(t("libraryTrash.toast.bulkPurged",{count:L.length}),"success"),d(new Set),n.invalidateQueries({queryKey:["library-trash"]}),n.invalidateQueries({queryKey:["library-trash-count"]})},onError:U=>a(U.message||t("libraryTrash.toast.purgeFailed"),"error")}),P=y.useMemo(()=>m.data?.items??[],[m.data?.items]),T=m.data?.retention_days??30,A=y.useMemo(()=>P.reduce((U,L)=>U+L.file_size,0),[P]),F=P.length>0&&P.every(U=>c.has(U.id)),_=c.size>0&&!F,E=U=>{d(L=>{const Q=new Set(L);return Q.has(U)?Q.delete(U):Q.add(U),Q})},H=()=>{d(U=>U.size===P.length?new Set:new Set(P.map(L=>L.id)))},I=()=>{o&&(o.type==="delete"?x.mutate(o.id):o.type==="bulkDelete"?C.mutate(Array.from(c)):S.mutate(),l(null))};return r.jsxs("div",{className:"p-6 max-w-screen-2xl mx-auto",children:[r.jsx("div",{className:"flex items-center gap-3 mb-4",children:r.jsxs(Is,{to:"/files",className:"inline-flex items-center gap-1 text-sm text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-200",children:[r.jsx(vT,{className:"w-4 h-4"})," ",t("libraryTrash.backToFiles")]})}),r.jsxs("div",{className:"flex items-start justify-between mb-6 gap-4 flex-wrap",children:[r.jsxs("div",{children:[r.jsx("h1",{className:"text-2xl font-bold text-gray-900 dark:text-gray-100",children:t("libraryTrash.title")}),r.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-400 mt-1",children:u?t("libraryTrash.subtitleAdmin",{days:T}):t("libraryTrash.subtitleUser",{days:T})})]}),P.length>0&&r.jsxs(Me,{variant:"secondary",onClick:()=>l({type:"empty"}),className:"text-red-600 dark:text-red-400",children:[r.jsx(Jt,{className:"w-4 h-4 mr-1"}),t("libraryTrash.emptyTrash")]})]}),u&&p.data&&r.jsxs("div",{className:"mb-4 border border-gray-200 dark:border-gray-700 rounded-lg p-3 flex items-center gap-3 bg-gray-50 dark:bg-gray-800/40",children:[r.jsx("label",{htmlFor:"retention-days",className:"text-sm font-medium text-gray-700 dark:text-gray-300",children:t("libraryTrash.retentionLabel")}),r.jsx("input",{id:"retention-days",type:"number",min:1,max:365,value:f??p.data.retention_days,onChange:U=>g(Math.max(1,Math.min(365,parseInt(U.target.value||"0",10)||0))),className:"w-20 rounded border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-sm px-2 py-1 text-gray-900 dark:text-gray-100"}),r.jsx("span",{className:"text-sm text-gray-600 dark:text-gray-400",children:t("libraryTrash.days")}),r.jsxs(Me,{variant:"secondary",onClick:()=>f!=null&&w.mutate(f),disabled:w.isPending||f==null||f===p.data.retention_days,className:"ml-auto",children:[r.jsx(us,{className:"w-4 h-4 mr-1"}),t("common.save")]})]}),m.isLoading?r.jsxs("div",{className:"flex items-center gap-2 text-gray-500 dark:text-gray-400",children:[r.jsx(pt,{className:"w-4 h-4 animate-spin"})," ",t("libraryTrash.loading")]}):P.length===0?r.jsx("div",{className:"border border-dashed border-gray-300 dark:border-gray-700 rounded-lg p-12 text-center",children:r.jsx("p",{className:"text-gray-500 dark:text-gray-400",children:t("libraryTrash.empty")})}):r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"flex items-center justify-between mb-2",children:[r.jsx("div",{className:"text-xs text-gray-500 dark:text-gray-400",children:t("libraryTrash.summary",{count:P.length,size:cs(A)})}),c.size>0&&r.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[r.jsx("span",{className:"text-gray-600 dark:text-gray-400",children:t("libraryTrash.selectionCount",{count:c.size})}),r.jsxs(Me,{variant:"secondary",onClick:()=>N.mutate(Array.from(c)),disabled:N.isPending,children:[r.jsx(gs,{className:"w-4 h-4 mr-1"}),t("libraryTrash.bulkRestore")]}),r.jsxs(Me,{variant:"secondary",onClick:()=>l({type:"bulkDelete",count:c.size}),disabled:C.isPending,className:"text-red-600 dark:text-red-400",children:[r.jsx(Jt,{className:"w-4 h-4 mr-1"}),t("libraryTrash.bulkPurge")]})]})]}),r.jsx("div",{className:"border border-gray-200 dark:border-gray-700 rounded-lg overflow-x-auto",children:r.jsxs("table",{className:"w-full text-sm",children:[r.jsx("thead",{className:"bg-gray-50 dark:bg-gray-800 text-left text-gray-600 dark:text-gray-300",children:r.jsxs("tr",{children:[r.jsx("th",{className:"px-3 py-2 w-10",children:r.jsx("input",{type:"checkbox",checked:F,ref:U=>{U&&(U.indeterminate=_)},onChange:H,"aria-label":t("libraryTrash.selectAll"),className:"rounded border-gray-300 cursor-pointer"})}),r.jsx("th",{className:"px-3 py-2 font-medium",children:t("libraryTrash.col.filename")}),r.jsx("th",{className:"px-3 py-2 font-medium",children:t("libraryTrash.col.folder")}),r.jsx("th",{className:"px-3 py-2 font-medium text-right",children:t("libraryTrash.col.size")}),r.jsx("th",{className:"px-3 py-2 font-medium whitespace-nowrap",children:t("libraryTrash.col.deleted")}),r.jsx("th",{className:"px-3 py-2 font-medium whitespace-nowrap",children:t("libraryTrash.col.autoPurge")}),u&&r.jsx("th",{className:"px-3 py-2 font-medium",children:t("libraryTrash.col.owner")}),r.jsx("th",{className:"px-3 py-2 font-medium text-right",children:t("libraryTrash.col.actions")})]})}),r.jsx("tbody",{className:"divide-y divide-gray-100 dark:divide-gray-800",children:P.map(U=>r.jsxs("tr",{className:"hover:bg-gray-50 dark:hover:bg-gray-800/50",children:[r.jsx("td",{className:"px-3 py-2",children:r.jsx("input",{type:"checkbox",checked:c.has(U.id),onChange:()=>E(U.id),"aria-label":t("libraryTrash.selectOne",{filename:U.filename}),className:"rounded border-gray-300 cursor-pointer"})}),r.jsx("td",{className:"px-3 py-2 text-gray-900 dark:text-gray-100 truncate max-w-md",title:U.filename,children:U.filename}),r.jsx("td",{className:"px-3 py-2 text-gray-600 dark:text-gray-400",children:U.folder_name??"—"}),r.jsx("td",{className:"px-3 py-2 text-right text-gray-600 dark:text-gray-400 tabular-nums whitespace-nowrap",children:cs(U.file_size)}),r.jsx("td",{className:"px-3 py-2 text-gray-600 dark:text-gray-400 whitespace-nowrap",children:hQ(U.deleted_at)}),r.jsx("td",{className:"px-3 py-2 text-gray-600 dark:text-gray-400 whitespace-nowrap",children:r.jsx("span",{title:hQ(U.auto_purge_at),children:t("libraryTrash.autoPurgeIn",{when:uit(U.auto_purge_at)})})}),u&&r.jsx("td",{className:"px-3 py-2 text-gray-600 dark:text-gray-400",children:U.created_by_username??"—"}),r.jsxs("td",{className:"px-3 py-2 text-right whitespace-nowrap",children:[r.jsxs("button",{onClick:()=>b.mutate(U.id),disabled:b.isPending,className:"inline-flex items-center gap-1 px-2 py-1 text-xs text-blue-600 hover:text-blue-800 dark:text-blue-400 dark:hover:text-blue-300",children:[r.jsx(gs,{className:"w-3.5 h-3.5"}),t("libraryTrash.restore")]}),r.jsxs("button",{onClick:()=>l({type:"delete",id:U.id,filename:U.filename}),disabled:x.isPending,className:"inline-flex items-center gap-1 px-2 py-1 text-xs text-red-600 hover:text-red-800 dark:text-red-400 dark:hover:text-red-300 ml-2",children:[r.jsx(Jt,{className:"w-3.5 h-3.5"}),t("libraryTrash.purgeNow")]})]})]},U.id))})]})})]}),o&&r.jsx(vn,{onCancel:()=>l(null),onConfirm:I,title:o.type==="delete"?t("libraryTrash.confirm.purgeTitle"):o.type==="bulkDelete"?t("libraryTrash.confirm.bulkPurgeTitle"):t("libraryTrash.confirm.emptyTitle"),message:o.type==="delete"?t("libraryTrash.confirm.purgeBody",{filename:o.filename}):o.type==="bulkDelete"?t("libraryTrash.confirm.bulkPurgeBody",{count:o.count}):t("libraryTrash.confirm.emptyBody",{count:P.length}),confirmText:t("libraryTrash.confirm.cta"),variant:"danger"}),m.isError&&r.jsxs("div",{className:"mt-4 text-sm text-red-600 dark:text-red-400",children:[m.error?.message??t("libraryTrash.loadError"),r.jsx(Me,{variant:"secondary",onClick:()=>e("/files"),className:"ml-3",children:t("libraryTrash.backToFiles")})]})]})}function pit(t,e){const n=`token=${encodeURIComponent(e)}`;let a=0;return t.querySelectorAll('img[src*="/api/v1/"], video[src*="/api/v1/"]').forEach(i=>{const s=i.getAttribute("src")||"";if(s.includes(n))return;const o=s.replace(/([?&])token=[^&]*(&|$)/,(c,d,u)=>u==="&"?d:""),l=o.includes("?")?"&":"?";i.src=`${o}${l}${n}`,a+=1}),a}function Oce(){const{authEnabled:t,user:e}=cr(),n=en(),a=y.useRef(!1),{data:i}=Ge({queryKey:["camera-stream-token",e?.id??null],queryFn:()=>ie.getCameraStreamToken(),enabled:t?!!e:!0,staleTime:3e3*1e3,refetchInterval:3e3*1e3});y.useEffect(()=>{const s=i?.token??null;return m6(s),s&&pit(document,s),()=>m6(null)},[i?.token]),y.useEffect(()=>{if(!t)return;const s=o=>{const l=o.target;if(!(l instanceof HTMLImageElement||l instanceof HTMLVideoElement))return;const c=l.src||"",d=qZ();!d||!c.includes(`token=${encodeURIComponent(d)}`)||a.current||(a.current=!0,n.invalidateQueries({queryKey:["camera-stream-token"]}),setTimeout(()=>{a.current=!1},5e3))};return document.addEventListener("error",s,!0),()=>document.removeEventListener("error",s,!0)},[t,n])}const uN=5,hit=2e3,fit=3e4,git=5e3;function bit(){const{t}=kt(),e=en(),{showToast:n}=rn(),{hasPermission:a,authEnabled:i,user:s}=cr(),{printerId:o}=_S(),l=parseInt(o||"0",10),[c]=ab(),d=parseInt(c.get("fps")||"15",10),u=Math.min(Math.max(isNaN(d)?15:d,1),30);Oce();const{data:m}=Ge({queryKey:["camera-stream-token",s?.id??null],queryFn:()=>ie.getCameraStreamToken(),enabled:i?!!s:!0,staleTime:3e3*1e3}),p=m?.token??qZ(),[f,g]=y.useState("stream"),[w,b]=y.useState(!1),[x,S]=y.useState(!1),[N,C]=y.useState(!0),[P,T]=y.useState(Date.now()),[A,F]=y.useState(!1),[_,E]=y.useState(!1),[H,I]=y.useState(0),[U,L]=y.useState(!1),[Q,re]=y.useState(0),[J,ce]=y.useState(1),[pe,ue]=y.useState({x:0,y:0}),[X,ae]=y.useState(!1),[me,ge]=y.useState({x:0,y:0}),[Pe,$]=y.useState(null),[W,D]=y.useState(null),j=y.useRef(null),B=y.useRef(null),Y=y.useRef(null),O=y.useRef(null),se=y.useRef(null),{data:z}=Ge({queryKey:["printer",l],queryFn:()=>ie.getPrinter(l),enabled:l>0}),{data:G}=Ge({queryKey:["printerStatus",l],queryFn:()=>ie.getPrinterStatus(l),refetchInterval:3e4,enabled:l>0}),K=it({mutationFn:Ue=>ie.setChamberLight(l,Ue),onMutate:async Ue=>{await e.cancelQueries({queryKey:["printerStatus",l]});const ke=e.getQueryData(["printerStatus",l]);return e.setQueryData(["printerStatus",l],De=>({...De,chamber_light:Ue})),{previousStatus:ke}},onSuccess:(Ue,ke)=>{n(`Chamber light ${ke?"on":"off"}`)},onError:(Ue,ke,De)=>{De?.previousStatus&&e.setQueryData(["printerStatus",l],De.previousStatus),n(Ue.message||t("printers.toast.failedToControlChamberLight"),"error")}}),Z=(G?.state==="RUNNING"||G?.state==="PAUSE")&&(G?.printable_objects_count??0)>=2;y.useEffect(()=>(z&&(document.title=`${z.name} - Camera`),()=>{document.title="Bambuddy"}),[z]);const oe=y.useRef(!1);y.useEffect(()=>{const Ue=`/api/v1/printers/${l}/camera/stop`;oe.current=!1;const ke=()=>{if(l>0&&!oe.current){oe.current=!0;const Xe={},Ke=Gm();Ke&&(Xe.Authorization=`Bearer ${Ke}`),fetch(Ue,{method:"POST",keepalive:!0,headers:Xe}).catch(()=>{})}},De=()=>{ke()};window.addEventListener("beforeunload",De);const Ae=j.current;return()=>{window.removeEventListener("beforeunload",De),Ae&&(Ae.src=""),ke()}},[l]),y.useEffect(()=>{if(N&&!A){const ke=setTimeout(()=>{C(!1)},f==="stream"?3e3:2e4);return()=>clearTimeout(ke)}},[f,N,P,A]),y.useEffect(()=>{const Ue=()=>{const ke=!!document.fullscreenElement;E(ke),ce(1),ue({x:0,y:0}),f==="stream"&&!A&&(j.current&&(j.current.src=""),setTimeout(()=>{C(!0),T(Date.now())},200))};return document.addEventListener("fullscreenchange",Ue),()=>document.removeEventListener("fullscreenchange",Ue)},[f,A]),y.useEffect(()=>{let Ue;const ke=()=>{clearTimeout(Ue),Ue=setTimeout(()=>{localStorage.setItem("cameraWindowState",JSON.stringify({width:window.outerWidth,height:window.outerHeight,left:window.screenX,top:window.screenY}))},500)};return window.addEventListener("resize",ke),()=>{clearTimeout(Ue),window.removeEventListener("resize",ke)}},[]),y.useEffect(()=>()=>{Y.current&&clearTimeout(Y.current),O.current&&clearInterval(O.current),se.current&&clearInterval(se.current)},[]);const ee=y.useCallback(()=>{if(H>=uN){L(!1),S(!0);return}const Ue=Math.min(hit*Math.pow(2,H),fit);L(!0),re(Math.ceil(Ue/1e3)),O.current=setInterval(()=>{re(ke=>ke<=1?(O.current&&clearInterval(O.current),0):ke-1)},1e3),Y.current=setTimeout(()=>{I(ke=>ke+1),L(!1),C(!0),S(!1),j.current&&(j.current.src=""),T(Date.now())},Ue)},[H]);y.useEffect(()=>{if(f!=="stream"||N||U||A){se.current&&(clearInterval(se.current),se.current=null);return}return se.current=setInterval(async()=>{try{const Ue=await ie.getCameraStatus(l);(Ue.stalled||!Ue.active&&!x)&&(console.log(`Stream issue detected: stalled=${Ue.stalled}, active=${Ue.active}, reconnecting...`),se.current&&(clearInterval(se.current),se.current=null),C(!1),ee())}catch{}},git),()=>{se.current&&(clearInterval(se.current),se.current=null)}},[f,N,x,U,A,l,ee]);const fe=()=>{C(!1),f==="stream"&&H{if(C(!1),S(!1),I(0),L(!1),Y.current&&clearTimeout(Y.current),O.current&&clearInterval(O.current),j.current&&!localStorage.getItem("cameraWindowState")){const Ue=j.current,ke=Ue.naturalWidth,De=Ue.naturalHeight;if(ke>0&&De>0){const Ke=window.outerWidth-window.innerWidth,gt=window.outerHeight-window.innerHeight,ct=ke+16+Ke,at=De+45+16+gt;try{window.resizeTo(ct,at)}catch{}}}},le=()=>{if(l>0){const Ue={},ke=Gm();ke&&(Ue.Authorization=`Bearer ${ke}`),fetch(`/api/v1/printers/${l}/camera/stop`,{method:"POST",headers:Ue}).catch(()=>{})}},q=Ue=>{f===Ue||A||(F(!0),C(!0),S(!1),I(0),L(!1),ce(1),ue({x:0,y:0}),Y.current&&clearTimeout(Y.current),O.current&&clearInterval(O.current),j.current&&(j.current.src=""),f==="stream"&&le(),setTimeout(()=>{g(Ue),T(Date.now()),F(!1)},100))},R=()=>{A||(F(!0),C(!0),S(!1),I(0),L(!1),Y.current&&clearTimeout(Y.current),O.current&&clearInterval(O.current),j.current&&(j.current.src=""),f==="stream"&&le(),setTimeout(()=>{T(Date.now()),F(!1)},100))},ne=()=>{B.current&&(document.fullscreenElement?document.exitFullscreen():B.current.requestFullscreen())},xe=()=>{ce(Ue=>Math.min(Ue+.5,4))},ve=()=>{ce(Ue=>{const ke=Math.max(Ue-.5,1);return ke===1&&ue({x:0,y:0}),ke})},Ce=Ue=>{Ue.preventDefault(),Ue.deltaY<0?xe():ve()},ye=Ue=>{J>1&&(Ue.preventDefault(),ae(!0),ge({x:Ue.clientX-pe.x,y:Ue.clientY-pe.y}))},be=y.useCallback(()=>{if(!B.current)return{x:300,y:200};const Ue=B.current.getBoundingClientRect(),ke=Ue.width*(J-1)/2,De=Ue.height*(J-1)/2;return{x:Math.max(50,ke),y:Math.max(50,De)}},[J]),Ee=Ue=>{if(X&&J>1){const ke=Ue.clientX-me.x,De=Ue.clientY-me.y,Ae=be();ue({x:Math.max(-Ae.x,Math.min(Ae.x,ke)),y:Math.max(-Ae.y,Math.min(Ae.y,De))})}},ze=()=>{ae(!1)},Oe=Ue=>{if(Ue.length<2)return 0;const ke=Ue[0].clientX-Ue[1].clientX,De=Ue[0].clientY-Ue[1].clientY;return Math.sqrt(ke*ke+De*De)},Be=Ue=>Ue.length<2?{x:Ue[0].clientX,y:Ue[0].clientY}:{x:(Ue[0].clientX+Ue[1].clientX)/2,y:(Ue[0].clientY+Ue[1].clientY)/2},Se=Ue=>{Ue.touches.length===2?(Ue.preventDefault(),$(Oe(Ue.touches)),D(Be(Ue.touches))):Ue.touches.length===1&&J>1&&(Ue.preventDefault(),ae(!0),ge({x:Ue.touches[0].clientX-pe.x,y:Ue.touches[0].clientY-pe.y}))},$e=Ue=>{if(Ue.touches.length===2&&Pe!==null){Ue.preventDefault();const ke=Oe(Ue.touches),De=ke/Pe;ce(Xe=>{const Ke=Math.max(1,Math.min(4,Xe*De));return Ke===1&&ue({x:0,y:0}),Ke}),$(ke);const Ae=Be(Ue.touches);if(W){const Xe=be();ue(Ke=>({x:Math.max(-Xe.x,Math.min(Xe.x,Ke.x+(Ae.x-W.x))),y:Math.max(-Xe.y,Math.min(Xe.y,Ke.y+(Ae.y-W.y)))}))}D(Ae)}else if(Ue.touches.length===1&&X&&J>1){Ue.preventDefault();const ke=Ue.touches[0].clientX-me.x,De=Ue.touches[0].clientY-me.y,Ae=be();ue({x:Math.max(-Ae.x,Math.min(Ae.x,ke)),y:Math.max(-Ae.y,Math.min(Ae.y,De))})}},rt=Ue=>{Ue.touches.length<2&&($(null),D(null)),Ue.touches.length===0&&ae(!1)},ot=()=>{ce(1),ue({x:0,y:0})},Le=i&&!p,nt=Ue=>p?`${Ue}&token=${encodeURIComponent(p)}`:La(Ue),Ne=A||Le?"":nt(f==="stream"?`/api/v1/printers/${l}/camera/stream?fps=${u}&t=${P}`:`/api/v1/printers/${l}/camera/snapshot?t=${P}`),Qe=N||A||U;return l?r.jsxs("div",{ref:B,className:"min-h-screen bg-black flex flex-col",children:[r.jsxs("div",{className:"flex items-center justify-between px-4 py-2 bg-bambu-dark-secondary border-b border-bambu-dark-tertiary",children:[r.jsxs("h1",{className:"text-sm font-medium text-white flex items-center gap-2",children:[r.jsx(fy,{className:"w-4 h-4"}),z?.name||`Printer ${l}`]}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsxs("div",{className:"flex bg-bambu-dark rounded p-0.5",children:[r.jsx("button",{onClick:()=>q("stream"),disabled:Qe,className:`px-3 py-1 text-xs rounded transition-colors ${f==="stream"?"bg-bambu-green text-white":"text-bambu-gray hover:text-white disabled:opacity-50"}`,children:t("camera.live")}),r.jsx("button",{onClick:()=>q("snapshot"),disabled:Qe,className:`px-3 py-1 text-xs rounded transition-colors ${f==="snapshot"?"bg-bambu-green text-white":"text-bambu-gray hover:text-white disabled:opacity-50"}`,children:t("camera.snapshot")})]}),r.jsx("button",{onClick:()=>K.mutate(!G?.chamber_light),disabled:!G?.connected||K.isPending||!a("printers:control"),className:`p-1.5 rounded disabled:opacity-50 ${G?.chamber_light?"bg-yellow-500/20 hover:bg-yellow-500/30":"hover:bg-bambu-dark-tertiary"}`,title:a("printers:control")?t("camera.chamberLight"):t("printers.permission.noControl"),children:r.jsx(t4,{on:G?.chamber_light??!1,className:"w-4 h-4"})}),r.jsx("button",{onClick:()=>b(!0),disabled:!Z||!a("printers:control"),className:`p-1.5 rounded disabled:opacity-50 ${Z&&a("printers:control")?"hover:bg-bambu-dark-tertiary":""}`,title:a("printers:control")?t(Z?"printers.skipObjects.tooltip":"printers.skipObjects.onlyWhilePrinting"):t("printers.permission.noControl"),children:r.jsx(OT,{className:"w-4 h-4 text-bambu-gray"})}),r.jsx("button",{onClick:R,disabled:Qe,className:"p-1.5 hover:bg-bambu-dark-tertiary rounded disabled:opacity-50",title:t(f==="stream"?"camera.restartStream":"camera.refreshSnapshot"),children:r.jsx(er,{className:`w-4 h-4 text-bambu-gray ${Qe?"animate-spin":""}`})}),r.jsx("button",{onClick:ne,className:"p-1.5 hover:bg-bambu-dark-tertiary rounded",title:t(_?"camera.exitFullscreen":"camera.fullscreen"),children:_?r.jsx(EZ,{className:"w-4 h-4 text-bambu-gray"}):r.jsx(fxe,{className:"w-4 h-4 text-bambu-gray"})})]})]}),r.jsx("div",{className:"flex-1 flex items-center justify-center p-2 overflow-hidden",onWheel:Ce,onMouseMove:Ee,onMouseUp:ze,onMouseLeave:ze,onTouchStart:Se,onTouchMove:$e,onTouchEnd:rt,style:{touchAction:"none"},children:r.jsxs("div",{className:"relative w-full h-full flex items-center justify-center",children:[(N||A)&&!U&&r.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/50 z-10",children:r.jsxs("div",{className:"text-center",children:[r.jsx(er,{className:"w-8 h-8 text-bambu-gray animate-spin mx-auto mb-2"}),r.jsx("p",{className:"text-sm text-bambu-gray",children:t(f==="stream"?"camera.connectingToCamera":"camera.capturingSnapshot")})]})}),U&&r.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/80 z-10",children:r.jsxs("div",{className:"text-center p-4",children:[r.jsx(mu,{className:"w-10 h-10 text-orange-400 mx-auto mb-3"}),r.jsx("p",{className:"text-white mb-2",children:t("camera.connectionLost")}),r.jsx("p",{className:"text-sm text-bambu-gray mb-3",children:t("camera.reconnecting",{countdown:Q,attempt:Math.min(H+1,uN),max:uN})}),r.jsx("button",{onClick:R,className:"px-4 py-2 bg-bambu-green text-white text-sm rounded hover:bg-bambu-green/80 transition-colors",children:t("camera.reconnectNow")})]})}),x&&!U&&r.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black z-10",children:r.jsxs("div",{className:"text-center p-4",children:[r.jsx(Nn,{className:"w-12 h-12 text-orange-400 mx-auto mb-3"}),r.jsx("p",{className:"text-white mb-2",children:t("camera.cameraUnavailable")}),r.jsx("p",{className:"text-xs text-bambu-gray mb-4 max-w-md",children:t("camera.cameraUnavailableDesc")}),r.jsx("button",{onClick:R,className:"px-4 py-2 bg-bambu-green text-white rounded hover:bg-bambu-green/80 transition-colors",children:t("camera.retry")})]})}),r.jsx("img",{ref:j,src:Ne,alt:t("camera.cameraStream"),className:"max-w-full max-h-full object-contain select-none",style:{transform:`scale(${J}) translate(${pe.x/J}px, ${pe.y/J}px) rotate(${z?.camera_rotation||0}deg)`,...z?.camera_rotation===90||z?.camera_rotation===270?{maxWidth:"100vh",maxHeight:"100vw"}:{},cursor:J>1?X?"grabbing":"grab":"default"},onError:Ne?fe:void 0,onLoad:Ne?de:void 0,onMouseDown:ye,draggable:!1},P),r.jsxs("div",{className:"absolute bottom-4 left-4 flex items-center gap-1.5 bg-black/60 rounded-lg px-2 py-1.5",children:[r.jsx("button",{onClick:ve,disabled:J<=1,className:"p-1.5 hover:bg-white/10 rounded disabled:opacity-30",title:t("camera.zoomOut"),children:r.jsx(SO,{className:"w-4 h-4 text-white"})}),r.jsxs("button",{onClick:ot,className:"px-2 py-1 text-sm text-white hover:bg-white/10 rounded min-w-[48px]",title:t("camera.resetZoom"),children:[Math.round(J*100),"%"]}),r.jsx("button",{onClick:xe,disabled:J>=4,className:"p-1.5 hover:bg-white/10 rounded disabled:opacity-30",title:t("camera.zoomIn"),children:r.jsx(wO,{className:"w-4 h-4 text-white"})})]})]})}),r.jsx(n4,{printerId:l,isOpen:w,onClose:()=>b(!1)})]}):r.jsx("div",{className:"min-h-screen bg-black flex items-center justify-center",children:r.jsx("p",{className:"text-white",children:t("camera.invalidPrinterId")})})}function xit(t,e,n){if(!t)return"";if(!e)return t;const a=e.match(/plate_(\d+)\.gcode/);return a&&parseInt(a[1],10)>1?`${t} — ${n("printers.plateNumber","Plate {{number}}",{number:a[1]})}`:t}function yit(t){const e=t.get("show")?.split(",")||["progress","layers","eta","filename","status"],n=parseInt(t.get("fps")||"15",10),a=Math.min(Math.max(isNaN(n)?15:n,1),30),i=t.get("camera"),s=i!=="false"&&i!=="0";return{size:t.get("size")||"medium",fps:a,showCamera:s,showProgress:e.includes("progress"),showLayers:e.includes("layers"),showEta:e.includes("eta"),showFilename:e.includes("filename"),showStatus:e.includes("status"),showPrinter:e.includes("printer")}}function vit(t,e){if(t.stg_cur_name)return t.stg_cur_name;switch(t.state){case"RUNNING":return e("streamOverlay.status.printing");case"PAUSE":return e("streamOverlay.status.paused");case"FINISH":return e("streamOverlay.status.finished");case"FAILED":return e("streamOverlay.status.failed");case"IDLE":return e("streamOverlay.status.idle");default:return t.state||e("streamOverlay.status.unknown")}}function wit(t){switch(t){case"small":return{container:"p-3",text:"text-sm",textLarge:"text-lg",progressHeight:"h-2",icon:"w-3 h-3",gap:"gap-2",logoHeight:"h-12"};case"large":return{container:"p-6",text:"text-xl",textLarge:"text-3xl",progressHeight:"h-4",icon:"w-6 h-6",gap:"gap-4",logoHeight:"h-24"};default:return{container:"p-4",text:"text-base",textLarge:"text-xl",progressHeight:"h-3",icon:"w-4 h-4",gap:"gap-3",logoHeight:"h-16"}}}function Sit(){const{printerId:t}=_S(),[e]=ab(),{t:n}=kt(),a=en(),i=parseInt(t||"0",10),[s,o]=y.useState(Date.now()),l=y.useMemo(()=>yit(e),[e]),c=wit(l.size),{data:d}=Ge({queryKey:["printer",i],queryFn:()=>ie.getPrinter(i),enabled:i>0}),{data:u}=Ge({queryKey:["printerStatus",i],queryFn:()=>ie.getPrinterStatus(i),enabled:i>0,refetchInterval:2e3}),{data:m}=Ge({queryKey:["settings"],queryFn:ie.getSettings}),p=m?.time_format||"system";y.useEffect(()=>{if(!i)return;const S=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/api/v1/ws`,N=new WebSocket(S);return N.onmessage=C=>{try{const P=JSON.parse(C.data);P.type==="printer_status"&&P.printer_id===i&&a.setQueryData(["printerStatus",i],P.status)}catch{}},N.onerror=()=>{},()=>{N.close()}},[i,a]),y.useEffect(()=>(document.title=d?`${d.name} - ${n("streamOverlay.title")}`:n("streamOverlay.title"),()=>{document.title="Bambuddy"}),[d,n]);const f=()=>{setTimeout(()=>{o(Date.now())},3e3)};if(!i)return r.jsx("div",{className:"min-h-screen bg-black flex items-center justify-center",children:r.jsx("p",{className:"text-white",children:n("streamOverlay.invalidPrinterId")})});if(!u)return r.jsx("div",{className:"min-h-screen bg-black flex items-center justify-center",children:r.jsx("p",{className:"text-gray-400",children:n("common.loading")})});const g=u.state==="RUNNING"||u.state==="PAUSE",w=u.progress||0,b=La(`/api/v1/printers/${i}/camera/stream?fps=${l.fps}&t=${s}`);return r.jsxs("div",{className:"min-h-screen bg-black relative overflow-hidden",children:[l.showCamera&&r.jsx("img",{src:b,alt:n("streamOverlay.cameraStream"),className:"absolute inset-0 w-full h-full object-contain",style:d?.camera_rotation?{transform:`rotate(${d.camera_rotation}deg)`}:void 0,onError:f},s),r.jsx("a",{href:"https://github.com/maziggy/bambuddy",target:"_blank",rel:"noopener noreferrer",className:"absolute top-4 right-4 z-10",children:r.jsx("img",{src:"/img/bambuddy_logo_dark_transparent.png",alt:"Bambuddy",className:`${c.logoHeight} object-contain drop-shadow-lg hover:scale-105 transition-transform`})}),r.jsx("div",{className:"absolute bottom-0 left-0 right-0 z-10 bg-gradient-to-t from-black/80 via-black/60 to-transparent",children:r.jsxs("div",{className:`${c.container}`,children:[l.showPrinter&&d&&r.jsxs("div",{className:`flex items-center ${c.gap} mb-2`,children:[r.jsx(pr,{className:`${c.icon} text-white/70`}),r.jsx("span",{className:`${c.text} text-white font-medium`,children:d.name})]}),l.showFilename&&u.current_print&&r.jsx("div",{className:`${c.textLarge} text-white font-semibold mb-2 truncate drop-shadow-md`,children:xit(u.current_print.replace(/\.gcode\.3mf$|\.3mf$|\.gcode$/i,""),u.gcode_file,n)}),l.showStatus&&r.jsx("div",{className:`${c.text} text-white/70 mb-2`,children:vit(u,n)}),l.showProgress&&g&&r.jsxs("div",{className:"mb-3",children:[r.jsxs("div",{className:`flex items-center justify-between mb-1 ${c.text}`,children:[r.jsx("span",{className:"text-white/70",children:n("streamOverlay.progress")}),r.jsxs("span",{className:"text-white font-bold",children:[Math.round(w),"%"]})]}),r.jsx("div",{className:`w-full bg-white/20 rounded-full ${c.progressHeight}`,children:r.jsx("div",{className:`bg-bambu-green ${c.progressHeight} rounded-full transition-all duration-500`,style:{width:`${w}%`}})})]}),g&&(l.showLayers||l.showEta)&&r.jsxs("div",{className:`flex items-center ${c.gap} flex-wrap`,children:[l.showLayers&&u.layer_num!=null&&u.total_layers!=null&&u.total_layers>0&&r.jsxs("div",{className:`flex items-center ${c.gap} text-white/70`,children:[r.jsx(oa,{className:c.icon}),r.jsxs("span",{className:c.text,children:[r.jsx("span",{className:"text-white",children:u.layer_num}),r.jsx("span",{className:"mx-1",children:"/"}),r.jsx("span",{children:u.total_layers})]})]}),l.showEta&&u.remaining_time!=null&&u.remaining_time>0&&r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:`flex items-center ${c.gap} text-white/70`,children:[r.jsx(Xd,{className:c.icon}),r.jsx("span",{className:`${c.text} text-white`,children:ds(u.remaining_time*60)})]}),r.jsxs("div",{className:`flex items-center ${c.gap} text-white/70`,children:[r.jsx(Zn,{className:c.icon}),r.jsxs("span",{className:`${c.text} text-white`,children:[n("streamOverlay.eta")," ",CO(u.remaining_time,p,n)]})]})]})]}),!g&&r.jsx("div",{className:`${c.text} text-white/70 py-2`,children:u.connected?n("streamOverlay.printerIdle"):n("streamOverlay.printerOffline")})]})})]})}function _it(){const{t}=kt(),{id:e}=_S(),{mode:n}=cb(),{data:a,isLoading:i,error:s}=Ge({queryKey:["external-link",e],queryFn:()=>ie.getExternalLink(Number(e)),enabled:!!e});return i?r.jsx("div",{className:"flex items-center justify-center h-full",children:r.jsx(pt,{className:"w-8 h-8 text-bambu-green animate-spin"})}):s||!a?r.jsxs("div",{className:"flex flex-col items-center justify-center h-full gap-4 text-bambu-gray",children:[r.jsx(Nn,{className:"w-12 h-12"}),r.jsx("p",{children:t("common.linkNotFound")})]}):r.jsx("iframe",{src:a.url,className:"h-full w-full border-0",style:{colorScheme:n},title:a.name,sandbox:"allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox"})}function fQ(){const{id:t}=_S(),e=Di(),n=en(),{t:a}=kt(),{showToast:i}=rn(),s=!!t,[o,l]=y.useState(""),[c,d]=y.useState(""),[u,m]=y.useState([]),[p,f]=y.useState(""),[g,w]=y.useState(!1),{data:b,isLoading:x}=Ge({queryKey:["group",t],queryFn:()=>ie.getGroup(Number(t)),enabled:s}),{data:S,isLoading:N}=Ge({queryKey:["permissions"],queryFn:()=>ie.getPermissions()});s&&b&&!g&&(l(b.name),d(b.description||""),m(b.permissions),w(!0));const C=it({mutationFn:J=>ie.createGroup(J),onSuccess:()=>{n.invalidateQueries({queryKey:["groups"]}),n.invalidateQueries({queryKey:["group"]}),i(a("groups.toast.created")),e("/settings?tab=users")},onError:J=>{i(J.message,"error")}}),P=it({mutationFn:J=>ie.updateGroup(Number(t),J),onSuccess:J=>{n.invalidateQueries({queryKey:["groups"]}),J&&n.setQueryData(["group",t],J),i(a("groups.toast.updated")),e("/settings?tab=users")},onError:J=>{i(J.message,"error")}}),T=C.isPending||P.isPending,A=()=>{if(!o.trim()){i(a("groups.toast.enterGroupName"),"error");return}s?P.mutate({name:o!==b?.name?o:void 0,description:c,permissions:u}):C.mutate({name:o,description:c||void 0,permissions:u})},F=J=>{m(ce=>ce.includes(J)?ce.filter(pe=>pe!==J):[...ce,J])},_=(J,ce)=>{const pe=J.permissions.map(ue=>ue.value);m(ue=>{const X=ue.filter(ae=>!pe.includes(ae));return ce?[...X,...pe]:X})},E=J=>J.permissions.every(ce=>u.includes(ce.value)),H=J=>{const ce=J.permissions.filter(pe=>u.includes(pe.value)).length;return ce>0&&ce{S&&m(S.all_permissions)},U=()=>{m([])},L=p.toLowerCase(),Q=y.useMemo(()=>S?L?S.categories.map(J=>({...J,permissions:J.permissions.filter(ce=>ce.label.toLowerCase().includes(L))})).filter(J=>J.permissions.length>0):S.categories:[],[S,L]),re=S?.all_permissions.length??0;return x||N?r.jsx("div",{className:"flex items-center justify-center py-16",children:r.jsx(pt,{className:"w-8 h-8 text-bambu-green animate-spin"})}):r.jsxs("div",{className:"space-y-6 max-w-5xl mx-auto",children:[r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("button",{onClick:()=>e("/settings?tab=users"),className:"p-2 rounded-lg hover:bg-bambu-dark-tertiary text-bambu-gray hover:text-white transition-colors",children:r.jsx(vT,{className:"w-5 h-5"})}),r.jsx("h1",{className:"text-xl font-bold text-white",children:a(s?"groups.editor.title":"groups.editor.createTitle")})]}),s&&b?.is_system&&r.jsxs("div",{className:"flex items-center gap-3 px-4 py-3 rounded-lg bg-yellow-500/10 border border-yellow-500/20 text-yellow-400 text-sm",children:[r.jsx(Nn,{className:"w-4 h-4 shrink-0"}),a("groups.form.systemGroupWarning")]}),r.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:a("groups.form.groupName")}),r.jsx("input",{type:"text",value:o,onChange:J=>l(J.target.value),disabled:s&&b?.is_system,className:"w-full px-4 py-3 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors disabled:opacity-50",placeholder:a("groups.form.groupNamePlaceholder")})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:a("groups.form.description")}),r.jsx("input",{type:"text",value:c,onChange:J=>d(J.target.value),className:"w-full px-4 py-3 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors",placeholder:a("groups.form.descriptionPlaceholder")})]})]}),r.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-3",children:[r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsxs("span",{className:"text-sm text-bambu-gray",children:[a("groups.editor.permissionsSelected",{count:u.length})," / ",re]}),r.jsx(Me,{size:"sm",variant:"ghost",onClick:I,children:a("groups.editor.selectAll")}),r.jsx(Me,{size:"sm",variant:"ghost",onClick:U,children:a("groups.editor.clearAll")})]}),r.jsxs("div",{className:"relative",children:[r.jsx(Sr,{className:"w-4 h-4 absolute left-3 top-1/2 -translate-y-1/2 text-bambu-gray"}),r.jsx("input",{type:"text",value:p,onChange:J=>f(J.target.value),placeholder:a("groups.editor.search"),className:"pl-9 pr-4 py-2 text-sm bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors w-64"})]})]}),Q.length===0?r.jsx("div",{className:"text-center py-12 text-bambu-gray",children:a("groups.editor.noResults")}):r.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:Q.map(J=>{const ce=S.categories.find(me=>me.name===J.name),pe=ce.permissions.filter(me=>u.includes(me.value)).length,ue=ce.permissions.length,X=E(ce),ae=H(ce);return r.jsxs(Ct,{children:[r.jsxs("div",{className:"sticky top-0 z-10 flex items-center justify-between px-4 py-3 bg-bambu-dark-secondary border-b border-bambu-dark-tertiary rounded-t-xl",children:[r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsxs("button",{type:"button",onClick:()=>_(ce,!X),className:`w-5 h-5 rounded border flex items-center justify-center transition-colors shrink-0 ${X?"bg-bambu-green border-bambu-green":ae?"bg-bambu-green/50 border-bambu-green":"border-bambu-gray hover:border-white"}`,children:[X&&r.jsx(_r,{className:"w-3 h-3 text-white"}),ae&&!X&&r.jsx(tC,{className:"w-3 h-3 text-white"})]}),r.jsx(Sl,{className:"w-4 h-4 text-bambu-gray shrink-0"}),r.jsx("span",{className:"text-white font-medium text-sm",children:J.name})]}),r.jsxs("span",{className:"text-xs text-bambu-gray tabular-nums",children:[pe,"/",ue]})]}),r.jsx("div",{className:"p-3 space-y-1",children:J.permissions.map(me=>r.jsxs("label",{className:"flex items-center gap-3 px-2 py-1.5 rounded hover:bg-bambu-dark-secondary cursor-pointer",children:[r.jsx("input",{type:"checkbox",checked:u.includes(me.value),onChange:()=>F(me.value),className:"w-4 h-4 rounded border-bambu-gray text-bambu-green focus:ring-bambu-green focus:ring-offset-0 bg-bambu-dark-secondary"}),r.jsx("span",{className:"text-sm text-bambu-gray",children:me.label})]},me.value))})]},J.name)})}),r.jsx("div",{className:"h-16"}),r.jsxs("div",{className:"fixed bottom-0 left-0 right-0 z-20 px-6 py-3 bg-bambu-dark-secondary border-t border-bambu-dark-tertiary flex items-center justify-center gap-3",children:[r.jsx(Me,{variant:"secondary",onClick:()=>e("/settings?tab=users"),children:a("common.cancel")}),r.jsx(Me,{onClick:A,disabled:T||!o.trim(),children:T?r.jsxs(r.Fragment,{children:[r.jsx(pt,{className:"w-4 h-4 animate-spin"}),a("common.saving")]}):r.jsxs(r.Fragment,{children:[r.jsx(us,{className:"w-4 h-4"}),a("common.save")]})})]})]})}const kit=1.65,gQ=["#1DB954","#3B82F6","#F59E0B","#EF4444","#8B5CF6"];function ww(t,e,n){return`${t}||${e??""}||${n??""}`}function Um(t,e){const n=new Date(t);return n.setDate(n.getDate()+Math.round(e)),n}function wS(t){return t.toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})}function Sw(t){return t.toLocaleDateString(void 0,{month:"short",day:"numeric"})}function Nit(t){if(t.length<2)return null;const e=[...t].sort((c,d)=>new Date(c.created_at).getTime()-new Date(d.created_at).getTime()),n=Date.now(),a=Math.LN2/30,i=[];for(let c=1;cc+d.weight,0);if(s===0)return null;const o=i.reduce((c,d)=>c+d.rate*d.weight,0)/s,l=i.reduce((c,d)=>c+d.weight*(d.rate-o)**2,0)/s;return{rate:o,stdDev:Math.sqrt(l)}}function Cit(t){const e=t.reduce((s,o)=>s+o.weight_used,0);if(e===0)return null;const n=Date.now(),a=t.reduce((s,o)=>{const l=new Date(o.created_at).getTime();return lie.getAllUsageHistory(5e3),staleTime:6e4,enabled:o}),{data:A=[]}=Ge({queryKey:["shopping-list"],queryFn:ie.getShoppingList,staleTime:3e4,enabled:o}),F=C?.forecast_global_lead_time_days??0,_=y.useMemo(()=>{const ce=new Map;for(const pe of P)ce.set(ww(pe.material,pe.subtype,pe.brand),pe);return ce},[P]),E=y.useMemo(()=>{const ce=new Map;for(const pe of T){const ue=ce.get(pe.spool_id)??[];ue.push(pe),ce.set(pe.spool_id,ue)}return ce},[T]),H=y.useMemo(()=>{const ce=new Map;for(const pe of t){if(pe.archived_at)continue;const ue=ww(pe.material,pe.subtype,pe.brand),X=ce.get(ue)??{key:ue,material:pe.material,subtype:pe.subtype,brand:pe.brand,spools:[]};X.spools.push(pe),ce.set(ue,X)}return[...ce.values()]},[t]),I=y.useMemo(()=>{const ce=new Date;return ce.setHours(0,0,0,0),H.map(pe=>{const ue=_.get(pe.key)??null,X=ue?.lead_time_days??0,ae=Math.max(F,X),me=ue?.safety_margin_value??14,ge=ue?.safety_margin_unit??"days",Pe=pe.spools.reduce((R,ne)=>R+Math.max(0,ne.label_weight-ne.weight_used),0),$=pe.spools.reduce((R,ne)=>R+ne.label_weight,0),W=pe.spools.reduce((R,ne)=>R+ne.weight_used,0),D=[];for(const R of pe.spools)D.push(...E.get(R.id)??[]);let j=null,B=null,Y="none";const O=Nit(D);if(O!==null)j=O.rate,B=O.stdDev,Y="history";else{const R=Cit(pe.spools);R!==null&&(j=R,Y="delta")}const se=B??(j!==null?j*.2:0),z=kit*se*Math.sqrt(ae),G=ge==="g"?me:j!==null?j*me:me*5,K=z+G,Z=j!==null?j*ae+K:0,oe=j&&j>0?Math.floor(Pe/j):null,ee=oe!==null?Um(ce,oe):null,fe=j&&j>0?Math.floor((Pe-Z)/j):null,de=fe!==null?Um(ce,Math.max(0,fe)):null,le=oe!==null&&ae>0&&oe<=ae,q=!le&&fe!==null&&fe<=0;return{group:pe,settings:ue,totalRemainingG:Pe,totalLabelG:$,totalSpools:pe.spools.length,totalUsedG:W,dailyRateG:j,dailyRateStdDev:B,rateTier:Y,effectiveLeadTimeDays:ae,safetyStockG:K,reorderPointG:Z,daysRemaining:oe,daysUntilROP:fe,projectedEmptyDate:ee,reorderTriggerDate:de,reorderAlert:q,stockBreakAlert:le}})},[H,_,E,F]),U=y.useMemo(()=>{const ce=[...I];return ce.sort((pe,ue)=>{let X=0,ae=0;switch(u){case"material":X=[pe.group.material,pe.group.subtype??"",pe.group.brand??""].join(" ").toLowerCase(),ae=[ue.group.material,ue.group.subtype??"",ue.group.brand??""].join(" ").toLowerCase();break;case"used":X=pe.totalUsedG,ae=ue.totalUsedG;break;case"days_left":X=pe.daysRemaining??999999,ae=ue.daysRemaining??999999;break;case"stock":X=pe.totalRemainingG,ae=ue.totalRemainingG;break}const me=Xae?1:0;return p==="asc"?me:-me}),ce},[I,u,p]),L=y.useMemo(()=>I.filter(ce=>!ce.settings?.alerts_snoozed&&(ce.stockBreakAlert||ce.reorderAlert)),[I]),Q=y.useMemo(()=>[...I].filter(ce=>ce.dailyRateG!==null).sort((ce,pe)=>pe.totalUsedG-ce.totalUsedG).slice(0,5),[I]);if(!o)return r.jsxs("div",{className:"flex flex-col items-center justify-center py-16 text-bambu-gray gap-3",children:[r.jsx(lc,{className:"w-8 h-8 opacity-40"}),r.jsx("p",{className:"text-sm",children:a("forecast.noReadAccess")})]});function re(ce){u===ce?f(pe=>pe==="asc"?"desc":"asc"):(m(ce),f(ce==="days_left"?"asc":"desc"))}const J=A.length>0?A.length:null;return r.jsxs("div",{className:"space-y-5",children:[r.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[L.length>0&&r.jsxs("button",{onClick:()=>d(ce=>!ce),className:`flex items-center gap-2 px-3 py-1.5 rounded-lg border text-sm font-medium transition-colors ${L.some(ce=>ce.stockBreakAlert)?"bg-red-500/15 border-red-500/30 text-red-300 hover:bg-red-500/25":"bg-yellow-500/15 border-yellow-500/30 text-yellow-300 hover:bg-yellow-500/25"}`,children:[r.jsx(Nn,{className:"w-4 h-4"}),a("forecast.alertCount",{count:L.length}),c?r.jsx(tl,{className:"w-3.5 h-3.5"}):r.jsx(Rn,{className:"w-3.5 h-3.5"})]}),l&&r.jsx(Eit,{value:F,onSave:ce=>{ie.updateSettings({forecast_global_lead_time_days:ce}).then(()=>{e.invalidateQueries({queryKey:["settings"]}),n(a("forecast.globalLeadTimeSaved"),"success")})}}),r.jsxs("button",{onClick:()=>x(ce=>!ce),className:"relative flex items-center gap-2 px-3 py-1.5 rounded-lg border border-bambu-dark-tertiary text-bambu-gray hover:bg-bambu-dark-tertiary text-sm transition-colors ml-auto",children:[r.jsx(lb,{className:"w-4 h-4"}),r.jsx("span",{className:"hidden sm:inline",children:a("forecast.shoppingList")}),J&&r.jsx("span",{className:"absolute -top-1.5 -right-1.5 w-4 h-4 rounded-full bg-bambu-green text-white text-[10px] font-bold flex items-center justify-center",children:J})]})]}),c&&L.length>0&&r.jsx("div",{className:"space-y-2",children:L.map(ce=>r.jsx(Ait,{forecast:ce,onCart:()=>w(ce)},ce.group.key))}),b&&r.jsx(Lit,{items:A,forecasts:I,globalLeadTime:F,canWrite:l,onClose:()=>x(!1),onRemove:ce=>{ie.removeFromShoppingList(ce).then(()=>e.invalidateQueries({queryKey:["shopping-list"]})).catch(()=>n(a("forecast.failedSaveSettings"),"error"))},onClear:()=>{ie.clearShoppingList().then(()=>e.invalidateQueries({queryKey:["shopping-list"]})).catch(()=>n(a("forecast.failedSaveSettings"),"error"))}}),Q.length>0&&r.jsx(Mit,{forecasts:Q,days:S,onDaysChange:N}),I.length===0?r.jsxs("div",{className:"flex flex-col items-center justify-center py-16 text-bambu-gray",children:[r.jsx(RS,{className:"w-10 h-10 mb-3 opacity-40"}),r.jsx("p",{className:"text-sm",children:a("forecast.noSpools")})]}):r.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg overflow-hidden border border-bambu-dark-tertiary",children:[r.jsx("div",{className:"overflow-x-auto",children:r.jsxs("table",{className:"w-full",children:[r.jsx("thead",{children:r.jsxs("tr",{className:"border-b border-bambu-dark-tertiary bg-bambu-dark-tertiary/30",children:[r.jsx("th",{className:"w-8 px-4 py-3"}),r.jsx(mN,{col:"material",active:u,dir:p,onSort:re,children:a("forecast.sku")}),r.jsx(mN,{col:"stock",active:u,dir:p,onSort:re,children:a("forecast.stock")}),r.jsx(mN,{col:"used",active:u,dir:p,onSort:re,children:a("forecast.dailyRate")}),r.jsx(mN,{col:"days_left",active:u,dir:p,onSort:re,children:a("forecast.daysLeft")}),r.jsx("th",{className:"px-4 py-3 text-left text-xs font-medium text-bambu-gray uppercase tracking-wide",children:a("forecast.emptyBy")}),r.jsx("th",{className:"px-4 py-3 text-left text-xs font-medium text-bambu-gray uppercase tracking-wide",children:a("forecast.reorderBy")}),r.jsx("th",{className:"w-24 px-4 py-3"})]})}),r.jsx("tbody",{className:"divide-y divide-bambu-dark-tertiary",children:U.map(ce=>r.jsx(Dit,{forecast:ce,globalLeadTime:F,canWrite:l,onSaved:()=>e.invalidateQueries({queryKey:["sku-settings"]}),onCart:()=>w(ce),showToast:n},ce.group.key))})]})}),r.jsxs("div",{className:"flex flex-wrap items-center gap-4 px-4 py-3 text-xs text-bambu-gray border-t border-bambu-dark-tertiary bg-bambu-dark-tertiary/20",children:[r.jsxs("span",{className:"flex items-center gap-1.5",children:[r.jsx("span",{className:"w-2 h-2 rounded-full bg-bambu-green inline-block"}),a("forecast.trendLegend")]}),r.jsxs("span",{className:"flex items-center gap-1.5",children:[r.jsx("span",{className:"w-2 h-2 rounded-full bg-blue-400 inline-block"}),a("forecast.estimatedLegend")]}),r.jsxs("span",{className:"flex items-center gap-1.5",children:[r.jsx("span",{className:"w-2 h-2 rounded-full bg-bambu-gray/40 inline-block"}),a("forecast.noDataLegend")]})]})]}),g&&r.jsx(Oit,{forecast:g,onClose:()=>w(null),onAdd:ce=>{ie.addToShoppingList(ce).then(()=>{e.invalidateQueries({queryKey:["shopping-list"]}),n(a("forecast.addedToCart"),"success"),w(null),x(!0)}).catch(()=>n(a("forecast.failedAddItem"),"error"))}})]})}function mN({col:t,active:e,dir:n,onSort:a,children:i}){const s=e===t;return r.jsx("th",{className:"px-4 py-3 text-left text-xs font-medium text-bambu-gray uppercase tracking-wide cursor-pointer select-none hover:text-white transition-colors",onClick:()=>a(t),children:r.jsxs("span",{className:"inline-flex items-center",children:[i,s?n==="asc"?r.jsx(Hm,{className:"w-3 h-3 ml-1 text-bambu-green"}):r.jsx(Bh,{className:"w-3 h-3 ml-1 text-bambu-green"}):r.jsx(wT,{className:"w-3 h-3 ml-1 opacity-40"})]})})}function Ait({forecast:t,onCart:e}){const{t:n}=kt(),a=[t.group.brand,t.group.material,t.group.subtype].filter(Boolean).join(" "),i=t.stockBreakAlert;return r.jsxs("div",{className:`flex items-center gap-3 px-4 py-3 rounded-lg border text-sm ${i?"bg-red-500/10 border-red-500/30 text-red-300":"bg-yellow-500/10 border-yellow-500/30 text-yellow-300"}`,children:[r.jsx(Nn,{className:"w-4 h-4 flex-shrink-0"}),r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsx("span",{className:"font-medium",children:a}),i?r.jsxs("span",{className:"ml-2 text-xs opacity-80",children:[n("forecast.stockBreakRisk")," — ",n("forecast.stockBreakDetail",{days:t.daysRemaining,lt:t.effectiveLeadTimeDays})]}):r.jsxs("span",{className:"ml-2 text-xs opacity-80",children:[n("forecast.reorderNow")," — ",n("forecast.reorderTriggerPassed",{date:t.reorderTriggerDate?wS(t.reorderTriggerDate):"—"})]})]}),r.jsxs("button",{onClick:e,className:"flex items-center gap-1.5 px-2.5 py-1 rounded border border-current text-xs opacity-70 hover:opacity-100 transition-opacity",children:[r.jsx(lb,{className:"w-3 h-3"})," ",n("forecast.order")]})]})}const jit=[{label:"1W",value:7},{label:"1M",value:30},{label:"6M",value:180}];function Mit({forecasts:t,days:e,onDaysChange:n}){const{t:a}=kt(),i=Array.from({length:e+1},(u,m)=>m),s=t.map((u,m)=>({key:u.group.key,label:[u.group.brand,u.group.material,u.group.subtype].filter(Boolean).join(" "),color:gQ[m%gQ.length],rop:u.reorderPointG,points:Pit(u,e)})),o=i.map(u=>{const m={day:u,label:Sw(Um(new Date,u))};for(const p of s){const f=p.points.find(g=>g.day===u);m[p.key]=f?.stock??0}return m}),l=(()=>{for(let u=e;u>=0;u--)if(s.some(m=>o[u]?.[m.key]>0))return u;return e})(),c=o.slice(0,l+1),d=s.filter(u=>u.rop>0);return r.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg overflow-hidden border border-bambu-dark-tertiary p-4",children:[r.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[r.jsx(RS,{className:"w-4 h-4 text-bambu-green"}),r.jsx("h3",{className:"text-sm font-semibold text-white",children:a("forecast.chartTitle")}),r.jsx("span",{className:"text-xs text-bambu-gray ml-1 hidden sm:inline",children:a("forecast.dashedLinesROP")}),r.jsx("div",{className:"ml-auto flex items-center bg-bambu-dark-tertiary rounded-lg p-0.5",children:jit.map(u=>r.jsx("button",{onClick:()=>n(u.value),className:`px-2.5 py-1 text-xs font-medium rounded-md transition-colors ${e===u.value?"bg-bambu-dark-secondary text-white shadow":"text-bambu-gray hover:text-white"}`,children:u.label},u.value))})]}),r.jsx(eu,{width:"100%",height:220,children:r.jsxs(s5,{data:c,margin:{top:4,right:8,bottom:0,left:0},children:[r.jsx("defs",{children:s.map(u=>r.jsxs("linearGradient",{id:`grad-${u.key}`,x1:"0",y1:"0",x2:"0",y2:"1",children:[r.jsx("stop",{offset:"5%",stopColor:u.color,stopOpacity:.25}),r.jsx("stop",{offset:"95%",stopColor:u.color,stopOpacity:.02})]},u.key))}),r.jsx(Cm,{strokeDasharray:"3 3",stroke:"#374151",strokeOpacity:.5}),r.jsx(Pm,{dataKey:"label",tick:{fill:"#6B7280",fontSize:10},interval:Math.max(0,Math.ceil(l/8)-1),axisLine:!1,tickLine:!1}),r.jsx(Tm,{tick:{fill:"#6B7280",fontSize:10},axisLine:!1,tickLine:!1,tickFormatter:u=>u>=1e3?`${(u/1e3).toFixed(1)}kg`:`${u}g`,width:48}),r.jsx(nu,{contentStyle:{background:"#1a1a2e",border:"1px solid #374151",borderRadius:8,fontSize:12},labelStyle:{color:"#9CA3AF"},itemStyle:{color:"#E5E7EB"},formatter:(u,m)=>{if(typeof u!="number")return"";const p=s.find(f=>f.key===String(m));return`${u}g — ${p?.label??m}`}}),r.jsx(j4,{formatter:u=>{const m=s.find(p=>p.key===u);return r.jsx("span",{style:{color:"#9CA3AF",fontSize:11},children:m?.label??u})}}),s.map(u=>r.jsx(DA,{type:"monotone",dataKey:u.key,stroke:u.color,strokeWidth:2,fill:`url(#grad-${u.key})`,dot:!1,activeDot:{r:3}},u.key)),d.map(u=>r.jsx(ru,{y:u.rop,stroke:u.color,strokeDasharray:"4 3",strokeOpacity:.6},`rop-${u.key}`))]})})]})}function Eit({value:t,onSave:e}){const{t:n}=kt(),[a,i]=y.useState(!1),[s,o]=y.useState(String(t));function l(){const c=parseInt(s,10);isNaN(c)||c<0||(e(c),i(!1))}return r.jsxs("div",{className:"flex items-center gap-2 px-3 py-1.5 bg-bambu-dark-tertiary/40 rounded-lg border border-bambu-dark-tertiary text-xs text-bambu-gray",children:[r.jsx(Ci,{className:"w-3.5 h-3.5 flex-shrink-0","aria-label":n("forecast.globalLeadTimeHint")}),r.jsxs("span",{className:"hidden sm:inline",children:[n("forecast.globalLeadTime"),":"]}),a?r.jsxs("form",{className:"flex items-center gap-1.5",onSubmit:c=>{c.preventDefault(),l()},children:[r.jsx("input",{type:"number",min:0,max:365,value:s,onChange:c=>o(c.target.value),className:"w-14 px-1.5 py-0.5 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-sm text-white focus:outline-none focus:border-bambu-green",autoFocus:!0}),r.jsx("span",{className:"text-bambu-gray",children:"d"}),r.jsx("button",{type:"submit",className:"px-2 py-0.5 bg-bambu-green text-white text-xs rounded hover:bg-bambu-green/80",children:n("forecast.save")}),r.jsx("button",{type:"button",onClick:()=>i(!1),className:"text-xs text-bambu-gray hover:text-white",children:"✕"})]}):r.jsxs("div",{className:"flex items-center gap-1.5",children:[r.jsxs("span",{className:"font-semibold text-white",children:[t,"d"]}),r.jsx("button",{onClick:()=>{o(String(t)),i(!0)},className:"p-0.5 text-bambu-gray hover:text-white rounded transition-colors",children:r.jsx(gc,{className:"w-3 h-3"})})]})]})}function Dit({forecast:t,globalLeadTime:e,canWrite:n,onSaved:a,onCart:i,showToast:s}){const{t:o}=kt(),[l,c]=y.useState(!1),[d,u]=y.useState(!1),[m,p]=y.useState(!1),[f,g]=y.useState(String(t.settings?.lead_time_days??0)),[w,b]=y.useState(String(t.settings?.safety_margin_value??14)),[x,S]=y.useState(t.settings?.safety_margin_unit??"days");y.useEffect(()=>{d||g(String(t.settings?.lead_time_days??0))},[t.settings?.lead_time_days,d]),y.useEffect(()=>{m||(b(String(t.settings?.safety_margin_value??14)),S(t.settings?.safety_margin_unit??"days"))},[t.settings?.safety_margin_value,t.settings?.safety_margin_unit,m]);const N=it({mutationFn:ie.upsertSkuSettings,onSuccess:()=>{a(),s(o("forecast.settingsSaved"),"success")},onError:()=>s(o("forecast.failedSaveSettings"),"error")}),C=t.settings?.alerts_snoozed??!1,P=[t.group.brand,t.group.material,t.group.subtype].filter(Boolean).join(" "),T=t.group.spools[0]?.rgba?`#${t.group.spools[0].rgba.substring(0,6)}`:"#4B5563",A=t.totalLabelG>0?Math.round(t.totalRemainingG/t.totalLabelG*100):0,F=C||t.daysRemaining===null?"text-bambu-gray":t.stockBreakAlert?"text-red-400":t.reorderAlert||t.daysRemaining<30?"text-yellow-400":"text-green-400";function _(U,L,Q,re=C){N.mutate({material:t.group.material,subtype:t.group.subtype,brand:t.group.brand,lead_time_days:U,safety_margin_value:L,safety_margin_unit:Q,alerts_snoozed:re})}function E(U){U.stopPropagation(),_(t.settings?.lead_time_days??0,t.settings?.safety_margin_value??14,t.settings?.safety_margin_unit??"days",!C)}const H=t.rateTier==="history"?r.jsxs("span",{className:"inline-flex items-center gap-1 text-xs px-1.5 py-0.5 rounded bg-bambu-green/15 text-bambu-green",children:[r.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-bambu-green"}),o("forecast.trend")]}):t.rateTier==="delta"?r.jsxs("span",{className:"inline-flex items-center gap-1 text-xs px-1.5 py-0.5 rounded bg-blue-400/15 text-blue-400",children:[r.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-blue-400"}),o("forecast.estimated")]}):r.jsxs("span",{className:"inline-flex items-center gap-1 text-xs px-1.5 py-0.5 rounded bg-bambu-dark-tertiary text-bambu-gray/60",children:[r.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-bambu-gray/40"}),o("forecast.noData")]}),I=C?"":t.stockBreakAlert?"bg-red-500/5":t.reorderAlert?"bg-yellow-500/5":"";return r.jsxs(r.Fragment,{children:[r.jsxs("tr",{className:`cursor-pointer hover:bg-bambu-dark-tertiary/40 transition-colors ${I} ${C?"opacity-50":""}`,onClick:()=>c(U=>!U),children:[r.jsx("td",{className:"px-4 py-3",children:r.jsx("span",{className:"block w-3 h-3 rounded-full border border-black/20",style:{backgroundColor:T}})}),r.jsxs("td",{className:"px-4 py-3",children:[r.jsx("div",{className:"text-sm font-medium text-white",children:P}),r.jsx("div",{className:"text-xs text-bambu-gray",children:o("forecast.spoolCount",{count:t.totalSpools})})]}),r.jsxs("td",{className:"px-4 py-3 min-w-[120px]",children:[r.jsx("div",{className:"h-1.5 bg-bambu-dark-tertiary rounded-full overflow-hidden mb-1 w-24",children:r.jsx("div",{className:`h-full rounded-full ${A>50?"bg-bambu-green":A>20?"bg-yellow-500":"bg-red-500"}`,style:{width:`${Math.min(A,100)}%`}})}),r.jsxs("span",{className:"text-xs text-bambu-gray",children:[Math.round(t.totalRemainingG),"g"]})]}),r.jsxs("td",{className:"px-4 py-3",children:[r.jsx("div",{className:"text-sm text-white",children:t.dailyRateG!==null?`${t.dailyRateG.toFixed(1)}g/d`:"—"}),r.jsx("div",{className:"mt-0.5",children:H})]}),r.jsx("td",{className:"px-4 py-3",children:r.jsx("span",{className:`text-sm font-semibold ${F}`,children:t.daysRemaining!==null?`${t.daysRemaining}d`:r.jsx("span",{className:"text-bambu-gray font-normal",children:"—"})})}),r.jsx("td",{className:"px-4 py-3",children:r.jsx("span",{className:"text-sm text-bambu-gray",children:t.projectedEmptyDate?wS(t.projectedEmptyDate):"—"})}),r.jsx("td",{className:"px-4 py-3",children:r.jsx("span",{className:`text-sm font-medium ${!C&&t.reorderAlert?"text-yellow-400":"text-bambu-gray"}`,children:t.reorderTriggerDate?wS(t.reorderTriggerDate):"—"})}),r.jsx("td",{className:"px-4 py-3",onClick:U=>U.stopPropagation(),children:r.jsxs("div",{className:"flex items-center justify-end gap-1",children:[n&&r.jsx("button",{onClick:i,className:"p-1.5 text-bambu-gray hover:text-bambu-green rounded transition-colors",title:o("forecast.addToCart"),children:r.jsx(lb,{className:"w-4 h-4"})}),!C&&(t.stockBreakAlert?r.jsx(Nn,{className:"w-4 h-4 text-red-400","aria-label":o("forecast.stockBreakRisk")}):t.reorderAlert?r.jsx(Nn,{className:"w-4 h-4 text-yellow-400","aria-label":o("forecast.reorderNow")}):t.daysRemaining!==null?r.jsx(_r,{className:"w-4 h-4 text-bambu-green/50"}):null),n&&r.jsx("button",{onClick:E,className:`p-1 rounded transition-colors ${C?"text-bambu-gray/70 hover:text-white":"text-bambu-dark-tertiary hover:text-bambu-gray"}`,title:o(C?"forecast.alertsEnabled":"forecast.alertsSnoozed"),children:r.jsx(NZ,{className:"w-3.5 h-3.5"})}),r.jsx("button",{onClick:U=>{U.stopPropagation(),c(L=>!L)},className:"p-1.5 text-bambu-gray hover:text-white rounded transition-colors",children:l?r.jsx(tl,{className:"w-4 h-4"}):r.jsx(Rn,{className:"w-4 h-4"})})]})})]}),l&&r.jsx("tr",{className:"bg-bambu-dark-tertiary/10",children:r.jsx("td",{colSpan:8,className:"px-6 py-4",children:r.jsxs("div",{className:"space-y-4",children:[r.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[r.jsx(hF,{label:o("forecast.effectiveLeadTime"),value:`${t.effectiveLeadTimeDays}d`,hint:o("forecast.effectiveLeadTimeHint",{global:e,sku:t.settings?.lead_time_days??0})}),r.jsx(hF,{label:o("forecast.safetyMarginLabel"),value:`${Math.round(t.safetyStockG)}g`,hint:o("forecast.safetyMarginHint")}),r.jsx(hF,{label:o("forecast.reorderPoint"),value:`${Math.round(t.reorderPointG)}g`,hint:o("forecast.reorderPointHint")})]}),n&&r.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[r.jsx(Fit,{label:o("forecast.skuLeadTimeOverride"),hint:o("forecast.skuLeadTimeHint"),unit:o("forecast.leadTime"),editing:d,value:t.settings?.lead_time_days??0,inputValue:f,onInputChange:g,onEdit:()=>{g(String(t.settings?.lead_time_days??0)),u(!0)},onSave:()=>{const U=parseInt(f,10);!isNaN(U)&&U>=0&&(_(U,t.settings?.safety_margin_value??14,x),u(!1))},onCancel:()=>u(!1),isPending:N.isPending,saveLabel:o("forecast.save"),cancelLabel:o("forecast.cancel")}),r.jsx(Rit,{value:t.settings?.safety_margin_value??14,unit:x,editing:m,inputValue:w,dailyRateG:t.dailyRateG,onInputChange:b,onUnitChange:U=>S(U),onEdit:()=>{b(String(t.settings?.safety_margin_value??14)),S(t.settings?.safety_margin_unit??"days"),p(!0)},onSave:()=>{const U=parseInt(w,10);!isNaN(U)&&U>=0&&(_(t.settings?.lead_time_days??0,U,x),p(!1))},onCancel:()=>p(!1),isPending:N.isPending,saveLabel:o("forecast.save"),cancelLabel:o("forecast.cancel"),safetyMarginLabel:o("forecast.safetyMarginLabel")})]}),t.group.spools.length>1&&r.jsxs("div",{className:"border-t border-bambu-dark-tertiary pt-3",children:[r.jsx("p",{className:"text-xs text-bambu-gray mb-2",children:o("forecast.individualSpools")}),r.jsx("div",{className:"bg-bambu-dark-secondary rounded-lg overflow-hidden border border-bambu-dark-tertiary",children:r.jsxs("table",{className:"w-full",children:[r.jsx("thead",{children:r.jsxs("tr",{className:"border-b border-bambu-dark-tertiary bg-bambu-dark-tertiary/30",children:[r.jsx("th",{className:"px-4 py-2 text-left text-xs font-medium text-bambu-gray uppercase tracking-wide",children:"#"}),r.jsx("th",{className:"px-4 py-2 text-left text-xs font-medium text-bambu-gray uppercase tracking-wide",children:o("inventory.remaining")}),r.jsx("th",{className:"px-4 py-2 text-left text-xs font-medium text-bambu-gray uppercase tracking-wide",children:o("inventory.used")}),r.jsx("th",{className:"px-4 py-2 text-left text-xs font-medium text-bambu-gray uppercase tracking-wide",children:o("forecast.labelWeight")})]})}),r.jsx("tbody",{className:"divide-y divide-bambu-dark-tertiary",children:t.group.spools.map(U=>{const L=Math.max(0,U.label_weight-U.weight_used),Q=U.label_weight>0?L/U.label_weight*100:0;return r.jsxs("tr",{className:"hover:bg-bambu-dark-tertiary/30 transition-colors",children:[r.jsx("td",{className:"px-4 py-2",children:r.jsxs("span",{className:"text-xs font-mono text-bambu-gray/70",children:["#",U.id]})}),r.jsx("td",{className:"px-4 py-2",children:r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("div",{className:"w-24 h-1.5 bg-bambu-dark-tertiary rounded-full overflow-hidden flex-shrink-0",children:r.jsx("div",{className:`h-full rounded-full ${Q>50?"bg-bambu-green":Q>20?"bg-yellow-500":"bg-red-500"}`,style:{width:`${Math.min(Q,100)}%`}})}),r.jsxs("span",{className:"text-sm text-white",children:[Math.round(L),"g"]})]})}),r.jsx("td",{className:"px-4 py-2",children:r.jsxs("span",{className:"text-sm text-bambu-gray",children:[Math.round(U.weight_used),"g"]})}),r.jsx("td",{className:"px-4 py-2",children:r.jsxs("span",{className:"text-sm text-bambu-gray",children:[U.label_weight,"g"]})})]},U.id)})})]})})]})]})})})]})}function hF({label:t,value:e,hint:n}){return r.jsxs("div",{className:"bg-bambu-dark-tertiary/40 rounded-lg p-3",title:n,children:[r.jsx("div",{className:"text-xs text-bambu-gray mb-1",children:t}),r.jsx("div",{className:"text-lg font-semibold text-white",children:e})]})}function Fit({label:t,hint:e,unit:n,editing:a,value:i,inputValue:s,onInputChange:o,onEdit:l,onSave:c,onCancel:d,isPending:u,saveLabel:m="Save",cancelLabel:p="Cancel"}){return r.jsxs("div",{className:"bg-bambu-dark-tertiary/40 rounded-lg p-3 space-y-1",children:[r.jsxs("div",{className:"flex items-center gap-1.5",children:[r.jsx("span",{className:"text-xs font-medium text-white",children:t}),r.jsx("span",{title:e,children:r.jsx(Ci,{className:"w-3 h-3 text-bambu-gray/50"})})]}),a?r.jsxs("form",{className:"flex items-center gap-2",onSubmit:f=>{f.preventDefault(),c()},children:[r.jsx("input",{type:"number",min:0,max:365,value:s,onChange:f=>o(f.target.value),className:"w-20 px-2 py-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-sm text-white focus:outline-none focus:border-bambu-green",autoFocus:!0,disabled:u}),r.jsx("span",{className:"text-xs text-bambu-gray",children:n}),r.jsx("button",{type:"submit",disabled:u,className:"px-2 py-1 bg-bambu-green text-white text-xs rounded hover:bg-bambu-green/80 disabled:opacity-50",children:m}),r.jsx("button",{type:"button",onClick:d,disabled:u,className:"px-2 py-1 text-xs text-bambu-gray hover:text-white",children:p})]}):r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("span",{className:"text-lg font-semibold text-white",children:i}),r.jsx("span",{className:"text-xs text-bambu-gray",children:n}),r.jsx("button",{onClick:l,className:"p-1 text-bambu-gray hover:text-white rounded transition-colors",children:r.jsx(gc,{className:"w-3 h-3"})})]})]})}function Rit({value:t,unit:e,editing:n,inputValue:a,dailyRateG:i,onInputChange:s,onUnitChange:o,onEdit:l,onSave:c,onCancel:d,isPending:u,saveLabel:m="Save",cancelLabel:p="Cancel",safetyMarginLabel:f="Safety Margin"}){const{t:g}=kt(),w=e==="g"?t:i!==null?Math.round(i*t):null,b=e==="days"?g("forecast.safetyMarginHintDays",{approx:w!==null?g("forecast.safetyMarginHintDaysApprox",{g:w}):""}):g("forecast.safetyMarginHintG",{approx:i!==null?g("forecast.safetyMarginHintGApprox",{days:Math.round(t/i)}):""});return r.jsxs("div",{className:"bg-bambu-dark-tertiary/40 rounded-lg p-3 space-y-1",children:[r.jsxs("div",{className:"flex items-center gap-1.5",children:[r.jsx("span",{className:"text-xs font-medium text-white",children:f}),r.jsx("span",{title:b,children:r.jsx(Ci,{className:"w-3 h-3 text-bambu-gray/50"})})]}),n?r.jsxs("form",{className:"flex items-center gap-2 flex-wrap",onSubmit:x=>{x.preventDefault(),c()},children:[r.jsx("input",{type:"number",min:0,max:e==="g"?1e4:365,value:a,onChange:x=>s(x.target.value),className:"w-20 px-2 py-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-sm text-white focus:outline-none focus:border-bambu-green",autoFocus:!0,disabled:u}),r.jsxs("div",{className:"flex bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded overflow-hidden text-xs",children:[r.jsx("button",{type:"button",onClick:()=>o("days"),className:`px-2 py-1 transition-colors ${e==="days"?"bg-bambu-green text-white":"text-bambu-gray hover:text-white"}`,children:"days"}),r.jsx("button",{type:"button",onClick:()=>o("g"),className:`px-2 py-1 transition-colors ${e==="g"?"bg-bambu-green text-white":"text-bambu-gray hover:text-white"}`,children:"g"})]}),r.jsx("button",{type:"submit",disabled:u,className:"px-2 py-1 bg-bambu-green text-white text-xs rounded hover:bg-bambu-green/80 disabled:opacity-50",children:m}),r.jsx("button",{type:"button",onClick:d,disabled:u,className:"px-2 py-1 text-xs text-bambu-gray hover:text-white",children:p})]}):r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("span",{className:"text-lg font-semibold text-white",children:t}),r.jsx("span",{className:"text-xs text-bambu-gray",children:e}),w!==null&&e==="days"&&r.jsxs("span",{className:"text-xs text-bambu-gray/60",children:["≈ ",w,"g"]}),e==="g"&&i!==null&&r.jsxs("span",{className:"text-xs text-bambu-gray/60",children:["≈ ",Math.round(t/i),"d"]}),r.jsx("button",{onClick:l,className:"p-1 text-bambu-gray hover:text-white rounded transition-colors",children:r.jsx(gc,{className:"w-3 h-3"})})]})]})}function Lit({items:t,forecasts:e,globalLeadTime:n,canWrite:a,onClose:i,onRemove:s,onClear:o}){const{t:l}=kt(),c=en(),[d,u]=y.useState("list"),m=it({mutationFn:async({id:b,status:x,item:S,avgSpoolG:N})=>{if(await ie.updateShoppingListStatus(b,x),x==="received"&&S){const C=N??1e3,P={material:S.material,subtype:S.subtype,brand:S.brand,label_weight:C,core_weight:0,core_weight_catalog_id:null,color_name:null,rgba:null,extra_colors:null,effect_type:null,nozzle_temp_min:null,nozzle_temp_max:null,note:S.note??null,tag_uid:null,tray_uuid:null,data_origin:"manual",tag_type:null,cost_per_kg:null,last_scale_weight:null,last_weighed_at:null,weight_used:0,slicer_filament:null,slicer_filament_name:null,added_full:null,last_used:null,encode_time:null,category:"Stock",low_stock_threshold_pct:null};await ie.bulkCreateSpools(P,S.quantity_spools),await ie.removeFromShoppingList(b)}},onSuccess:()=>{c.invalidateQueries({queryKey:["shopping-list"]}),c.invalidateQueries({queryKey:["spools"]})}}),p=y.useMemo(()=>{const b=new Map;for(const x of e)b.set(x.group.key,x);return b},[e]),f=y.useMemo(()=>t.map(b=>({item:b,forecast:p.get(ww(b.material,b.subtype,b.brand))??null})),[t,p]),g=y.useMemo(()=>f.filter(({forecast:b})=>!b||b.dailyRateG===null?!1:b.stockBreakAlert||b.daysRemaining!==null&&b.daysRemaining<=b.effectiveLeadTimeDays),[f]);function w(){const b=[l("forecast.qty"),l("forecast.material"),"Brand","Subtype",`${l("forecast.weight")} (g)`,`${l("forecast.leadTime")} (d)`,l("forecast.expectedRestock"),l("forecast.status"),l("forecast.note")],x=t.map(T=>{const A=p.get(ww(T.material,T.subtype,T.brand))??null,F=A&&A.totalSpools>0?A.totalLabelG/A.totalSpools:1e3,_=Math.round(T.quantity_spools*F),E=A?.effectiveLeadTimeDays??n??0,H=E>0?wS(Um(new Date,E)):"";return[T.quantity_spools,T.material,T.brand??"",T.subtype??"",_,E||"",H,T.status,T.note??""].map(I=>`"${String(I).replace(/"/g,'""')}"`).join(",")}),S=[b.join(","),...x].join(` -`),N=new Blob([S],{type:"text/csv"}),C=URL.createObjectURL(N),P=document.createElement("a");P.href=C,P.download=`shopping-list-${new Date().toISOString().slice(0,10)}.csv`,P.click(),setTimeout(()=>URL.revokeObjectURL(C),100)}return r.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg overflow-hidden border border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"flex items-center justify-between px-4 py-3 border-b border-bambu-dark-tertiary bg-bambu-dark-tertiary/30",children:[r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx(lb,{className:"w-4 h-4 text-bambu-green"}),r.jsx("h3",{className:"text-sm font-semibold text-white",children:l("forecast.shoppingList")}),r.jsx("span",{className:"text-xs text-bambu-gray",children:l("forecast.shoppingListItems",{count:t.length})}),t.length>0&&r.jsxs("div",{className:"flex bg-bambu-dark-tertiary rounded-md p-0.5 ml-1",children:[r.jsxs("button",{onClick:()=>u("list"),className:`flex items-center gap-1.5 px-2 py-0.5 text-xs font-medium rounded transition-colors ${d==="list"?"bg-bambu-dark-secondary text-white shadow":"text-bambu-gray hover:text-white"}`,children:[r.jsx(Br,{className:"w-3 h-3"}),l("forecast.listView")]}),r.jsxs("button",{onClick:()=>u("logistics"),className:`flex items-center gap-1.5 px-2 py-0.5 text-xs font-medium rounded transition-colors ${d==="logistics"?"bg-bambu-dark-secondary text-white shadow":"text-bambu-gray hover:text-white"}`,children:[r.jsx(Hfe,{className:"w-3 h-3"}),l("forecast.logisticsView"),g.length>0&&r.jsx("span",{className:"w-3.5 h-3.5 rounded-full bg-red-500 text-white text-[9px] font-bold flex items-center justify-center",children:g.length})]})]})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[t.length>0&&r.jsxs(r.Fragment,{children:[r.jsxs("button",{onClick:w,className:"flex items-center gap-1.5 text-xs text-bambu-gray hover:text-white transition-colors px-2 py-1 rounded border border-bambu-dark-tertiary hover:bg-bambu-dark-tertiary",children:[r.jsx(Yr,{className:"w-3 h-3"}),l("forecast.downloadCsv")]}),a&&r.jsx("button",{onClick:o,className:"text-xs text-red-400 hover:text-red-300 transition-colors px-2 py-1 rounded border border-red-500/20 hover:bg-red-500/10",children:l("forecast.clearAll")})]}),r.jsx("button",{onClick:i,className:"p-1 text-bambu-gray hover:text-white transition-colors",children:r.jsx(Ht,{className:"w-4 h-4"})})]})]}),t.length===0?r.jsxs("div",{className:"flex flex-col items-center py-8 text-bambu-gray",children:[r.jsx(Br,{className:"w-8 h-8 mb-2 opacity-30"}),r.jsx("p",{className:"text-sm",children:l("forecast.shoppingListEmpty")})]}):d==="list"?r.jsx("div",{className:"overflow-x-auto",children:r.jsxs("table",{className:"w-full",children:[r.jsx("thead",{children:r.jsxs("tr",{className:"border-b border-bambu-dark-tertiary bg-bambu-dark-tertiary/20",children:[r.jsx("th",{className:"px-4 py-2 text-left text-xs font-medium text-bambu-gray uppercase tracking-wide",children:l("forecast.qty")}),r.jsx("th",{className:"px-4 py-2 text-left text-xs font-medium text-bambu-gray uppercase tracking-wide",children:l("forecast.material")}),r.jsx("th",{className:"px-4 py-2 text-left text-xs font-medium text-bambu-gray uppercase tracking-wide",children:l("forecast.weight")}),r.jsx("th",{className:"px-4 py-2 text-left text-xs font-medium text-bambu-gray uppercase tracking-wide",children:l("forecast.leadTime")}),r.jsx("th",{className:"px-4 py-2 text-left text-xs font-medium text-bambu-gray uppercase tracking-wide",children:l("forecast.expectedRestock")}),r.jsx("th",{className:"px-4 py-2 text-left text-xs font-medium text-bambu-gray uppercase tracking-wide",children:l("forecast.status")}),r.jsx("th",{className:"px-4 py-2 text-left text-xs font-medium text-bambu-gray uppercase tracking-wide",children:l("forecast.note")}),r.jsx("th",{className:"px-4 py-2 text-right text-xs font-medium text-bambu-gray uppercase tracking-wide",children:l("forecast.actions")})]})}),r.jsx("tbody",{className:"divide-y divide-bambu-dark-tertiary",children:t.map(b=>{const x=[b.brand,b.material,b.subtype].filter(Boolean).join(" "),S=g.some(H=>H.item.id===b.id),N=p.get(ww(b.material,b.subtype,b.brand))??null,C=N&&N.totalSpools>0?N.totalLabelG/N.totalSpools:1e3,P=Math.round(b.quantity_spools*C),T=N?.effectiveLeadTimeDays??n??0,A=T>0?Um(new Date,T):null,F=b.status==="purchased"||b.status==="received",_=b.status==="received",E=m.isPending;return r.jsxs("tr",{className:`hover:bg-bambu-dark-tertiary/30 transition-colors ${S&&!F?"bg-red-500/5":""}`,children:[r.jsx("td",{className:"px-4 py-2.5",children:r.jsxs("span",{className:"text-sm font-semibold text-bambu-green",children:[b.quantity_spools,"×"]})}),r.jsx("td",{className:"px-4 py-2.5",children:r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("span",{className:"text-sm text-white",children:x}),S&&!F&&r.jsx(Nn,{className:"w-3.5 h-3.5 text-red-400 flex-shrink-0","aria-label":l("forecast.stockBreakBefore")})]})}),r.jsx("td",{className:"px-4 py-2.5",children:r.jsx("span",{className:"text-sm text-white",children:P>=1e3?`${(P/1e3).toFixed(1)}kg`:`${P}g`})}),r.jsx("td",{className:"px-4 py-2.5",children:r.jsx("span",{className:"text-sm text-bambu-gray",children:T>0?`${T}d`:"—"})}),r.jsx("td",{className:"px-4 py-2.5",children:r.jsx("span",{className:"text-sm text-bambu-gray",children:A?wS(A):"—"})}),r.jsx("td",{className:"px-4 py-2.5",children:r.jsx("span",{className:`inline-flex items-center px-2 py-0.5 rounded text-xs font-medium ${_?"bg-bambu-green/20 text-bambu-green":F?"bg-blue-400/20 text-blue-400":"bg-bambu-dark-tertiary text-bambu-gray"}`,children:l(_?"forecast.received":F?"forecast.purchased":"forecast.pending")})}),r.jsx("td",{className:"px-4 py-2.5",children:r.jsx("span",{className:"text-xs text-bambu-gray",children:b.note||"—"})}),r.jsx("td",{className:"px-4 py-2.5",children:r.jsx("div",{className:"flex items-center justify-end gap-1",children:a&&r.jsxs(r.Fragment,{children:[r.jsx("button",{onClick:()=>m.mutate({id:b.id,status:F?"pending":"purchased"}),disabled:E||_,title:l(F?"forecast.resetToPending":"forecast.markPurchased"),className:`p-1 rounded transition-colors disabled:opacity-30 ${F?"text-blue-400 hover:text-bambu-gray":"text-bambu-gray hover:text-blue-400"}`,children:F?r.jsx(gs,{className:"w-3.5 h-3.5"}):r.jsx(Tge,{className:"w-3.5 h-3.5"})}),r.jsx("button",{onClick:()=>m.mutate({id:b.id,status:"received",item:b,avgSpoolG:C}),disabled:E||!F||_,title:l("forecast.markReceived"),className:"p-1 rounded transition-colors text-bambu-gray hover:text-bambu-green disabled:opacity-30",children:r.jsx(Mxe,{className:"w-3.5 h-3.5"})}),r.jsx("button",{onClick:()=>s(b.id),className:"p-1 text-bambu-gray hover:text-red-400 transition-colors",title:l("forecast.remove"),children:r.jsx(Jt,{className:"w-3.5 h-3.5"})})]})})})]},b.id)})})]})}):r.jsx("div",{className:"divide-y divide-bambu-dark-tertiary",children:f.filter(({item:b})=>b.status!=="received").map(({item:b,forecast:x})=>r.jsx(Iit,{item:b,forecast:x,globalLeadTime:n,canWrite:a,onRemove:()=>s(b.id)},b.id))})]})}function Iit({item:t,forecast:e,globalLeadTime:n,canWrite:a,onRemove:i}){const{t:s}=kt(),o=[t.brand,t.material,t.subtype].filter(Boolean).join(" "),l=y.useMemo(()=>{if(!e||e.dailyRateG===null||e.dailyRateG<=0)return null;const u=e.dailyRateG,m=e.effectiveLeadTimeDays,p=e.totalSpools>0?e.totalLabelG/e.totalSpools:1e3,f=t.quantity_spools*p,g=Math.max(0,e.totalRemainingG-u*m),w=g+f,b=Math.ceil(w/u),x=Math.min(m+b+5,365),S=[];for(let N=0;N<=x;N++){const C=Sw(Um(new Date,N));if(N===m)S.push({day:N,label:C,stock:Math.round(g),rop:Math.round(e.reorderPointG),safetyStock:Math.round(e.safetyStockG)}),S.push({day:N,label:C,stock:Math.round(w),rop:Math.round(e.reorderPointG),safetyStock:Math.round(e.safetyStockG),arrival:!0});else{const P=N{if(!e||e.dailyRateG===null||e.dailyRateG<=0)return null;const u=Math.floor(e.totalRemainingG/e.dailyRateG);return uu>=1e3?`${(u/1e3).toFixed(1)}kg`:`${u}g`,width:44}),r.jsx(nu,{contentStyle:{background:"#1a1a2e",border:"1px solid #374151",borderRadius:8,fontSize:11},labelStyle:{color:"#9CA3AF"},formatter:(u,m)=>typeof u!="number"?"":m==="stock"?`${u}g — ${s("forecast.stock")}`:m==="rop"?`${u}g — ${s("forecast.reorderPoint")}`:m==="safetyStock"?`${u}g — ${s("forecast.safetyMarginLabel")}`:`${u}`}),r.jsx(DA,{type:"linear",dataKey:"stock",stroke:"#1DB954",strokeWidth:2,fill:`url(#cart-post-${t.id})`,dot:!1,activeDot:{r:3}}),e.reorderPointG>0&&r.jsx(ru,{y:e.reorderPointG,stroke:"#F59E0B",strokeDasharray:"5 3",strokeOpacity:.8,label:{value:"ROP",position:"insideTopRight",fill:"#F59E0B",fontSize:9}}),e.safetyStockG>0&&r.jsx(ru,{y:e.safetyStockG,stroke:"#6B7280",strokeDasharray:"3 3",strokeOpacity:.6,label:{value:"SS",position:"insideTopRight",fill:"#6B7280",fontSize:9}}),r.jsx(ru,{x:Sw(Um(new Date,l.lt)),stroke:"#3B82F6",strokeWidth:1.5,strokeDasharray:"4 3",strokeOpacity:.9,label:{value:`+${l.arrivalG>=1e3?`${(l.arrivalG/1e3).toFixed(1)}kg`:`${Math.round(l.arrivalG)}g`} arrives (d${l.lt})`,position:"insideTopLeft",fill:"#3B82F6",fontSize:9}}),c!==null&&r.jsx(ru,{x:Sw(Um(new Date,c)),stroke:"#EF4444",strokeWidth:1.5,strokeOpacity:.9,label:{value:"OUT",position:"insideTopLeft",fill:"#EF4444",fontSize:9}})]})}),r.jsxs("div",{className:"flex flex-wrap items-center gap-3 mt-2 text-[10px] text-bambu-gray",children:[r.jsxs("span",{className:"flex items-center gap-1",children:[r.jsx("span",{className:"inline-block w-4 border-t-2 border-yellow-400 border-dashed"})," ",s("forecast.ropLabel")]}),r.jsxs("span",{className:"flex items-center gap-1",children:[r.jsx("span",{className:"inline-block w-4 border-t border-bambu-gray border-dashed"})," ",s("forecast.safetyStockLegend")]}),r.jsxs("span",{className:"flex items-center gap-1",children:[r.jsx("span",{className:"inline-block w-4 border-t-2 border-blue-400 border-dashed"})," ",s("forecast.stockArrivalLegend")]}),d&&r.jsxs("span",{className:"flex items-center gap-1 text-red-400",children:[r.jsx("span",{className:"inline-block w-4 border-t-2 border-red-400"})," ",s("forecast.stockoutLegend")]})]})]}):null]})}function Oit({forecast:t,onClose:e,onAdd:n}){const{t:a}=kt(),i=[t.group.brand,t.group.material,t.group.subtype].filter(Boolean).join(" "),[s,o]=y.useState("qty"),[l,c]=y.useState("1"),[d,u]=y.useState("30"),[m,p]=y.useState(""),f=y.useMemo(()=>{if(!t.dailyRateG||t.dailyRateG<=0)return null;const b=t.dailyRateG*Number(d),x=t.group.spools.length>0?t.group.spools.reduce((S,N)=>S+N.label_weight,0)/t.group.spools.length:1e3;return Math.ceil(b/x)},[t,d]),g=s==="qty"?parseInt(l,10)||1:f??1;function w(b){b.preventDefault(),n({material:t.group.material,subtype:t.group.subtype,brand:t.group.brand,quantity_spools:g,note:m||null})}return r.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm p-4",children:r.jsxs("div",{className:"bg-bambu-dark-secondary rounded-2xl border border-bambu-dark-tertiary w-full max-w-sm shadow-2xl",children:[r.jsxs("div",{className:"flex items-center justify-between px-5 pt-5 pb-4 border-b border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(lb,{className:"w-5 h-5 text-bambu-green"}),r.jsx("h2",{className:"text-base font-semibold text-white",children:a("forecast.addToCartTitle")})]}),r.jsx("button",{onClick:e,className:"p-1 text-bambu-gray hover:text-white transition-colors",children:r.jsx(Ht,{className:"w-5 h-5"})})]}),r.jsxs("form",{onSubmit:w,className:"p-5 space-y-4",children:[r.jsx("div",{className:"text-sm text-bambu-gray",children:i}),r.jsxs("div",{className:"flex bg-bambu-dark-tertiary rounded-lg p-0.5",children:[r.jsx("button",{type:"button",onClick:()=>o("qty"),className:`flex-1 py-1.5 text-xs font-medium rounded-md transition-colors ${s==="qty"?"bg-bambu-dark-secondary text-white shadow":"text-bambu-gray hover:text-white"}`,children:a("forecast.byQuantity")}),r.jsx("button",{type:"button",onClick:()=>o("duration"),className:`flex-1 py-1.5 text-xs font-medium rounded-md transition-colors ${s==="duration"?"bg-bambu-dark-secondary text-white shadow":"text-bambu-gray hover:text-white"}`,children:a("forecast.byDuration")})]}),s==="qty"?r.jsxs("div",{className:"space-y-1.5",children:[r.jsx("label",{className:"text-xs text-bambu-gray",children:a("forecast.numberOfSpools")}),r.jsx("input",{type:"number",min:1,max:99,value:l,onChange:b=>c(b.target.value),className:"w-full px-3 py-2 bg-bambu-dark-tertiary border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:outline-none focus:border-bambu-green",autoFocus:!0})]}):r.jsxs("div",{className:"space-y-2",children:[r.jsxs("div",{className:"space-y-1.5",children:[r.jsx("label",{className:"text-xs text-bambu-gray",children:a("forecast.lastHowManyDays")}),r.jsx("input",{type:"number",min:1,max:365,value:d,onChange:b=>u(b.target.value),className:"w-full px-3 py-2 bg-bambu-dark-tertiary border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:outline-none focus:border-bambu-green",autoFocus:!0})]}),t.dailyRateG!==null?r.jsxs("div",{className:"flex items-center gap-2 px-3 py-2 bg-bambu-dark-tertiary/50 rounded-lg",children:[r.jsx("span",{className:"text-xs text-bambu-gray",children:"≈"}),r.jsx("span",{className:"text-sm font-semibold text-bambu-green",children:a("forecast.spoolCount",{count:f??0})}),r.jsxs("span",{className:"text-xs text-bambu-gray",children:["at ",t.dailyRateG.toFixed(1),"g/day"]})]}):r.jsx("div",{className:"text-xs text-yellow-400 px-1",children:a("forecast.noUsageQty")})]}),r.jsxs("div",{className:"space-y-1.5",children:[r.jsx("label",{className:"text-xs text-bambu-gray",children:a("forecast.noteOptional")}),r.jsx("input",{type:"text",maxLength:200,value:m,onChange:b=>p(b.target.value),placeholder:a("forecast.notePlaceholder"),className:"w-full px-3 py-2 bg-bambu-dark-tertiary border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/40 focus:outline-none focus:border-bambu-green"})]}),r.jsxs("div",{className:"flex items-center gap-3 pt-1",children:[r.jsx("button",{type:"submit",className:"flex-1 py-2 bg-bambu-green text-white text-sm font-medium rounded-lg hover:bg-bambu-green/80 transition-colors",children:a("forecast.addNSpools",{count:g})}),r.jsx("button",{type:"button",onClick:e,className:"px-4 py-2 text-sm text-bambu-gray hover:text-white border border-bambu-dark-tertiary rounded-lg transition-colors",children:a("forecast.cancel")})]})]})]})})}const YI={material:"",subtype:"",brand:"",color_name:"",rgba:"808080FF",extra_colors:"",effect_type:"",label_weight:1e3,core_weight:250,core_weight_catalog_id:null,weight_used:0,slicer_filament:"",note:"",cost_per_kg:null,category:"",low_stock_threshold_pct:null,storage_location:"",spoolman_filament_id:null},zit=new Set(["material","subtype","brand","rgba","color_name","label_weight"]);function zce(t,e=!1,n=!1){const a={};return e||n?(!t.material&&!t.spoolman_filament_id&&(a.material="Material is required"),{isValid:Object.keys(a).length===0,errors:a}):(t.slicer_filament||(a.slicer_filament="Slicer preset is required"),t.material||(a.material="Material is required"),t.brand||(a.brand="Brand is required"),t.subtype||(a.subtype="Subtype is required"),{isValid:Object.keys(a).length===0,errors:a})}const Uce=["PLA","PETG","ABS","TPU","ASA","PC","PA","PVA","HIPS","PA-CF","PETG-CF","PLA-CF"],Uit=["Bambu","PolyLite","PolyTerra","eSUN","Overture","Fiberon","SUNLU","Inland","Hatchbox","Generic"],_w=["Basic","Matte","Silk","Silk+","Tough","Tough+","HF","High Flow","Engineering","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"],Bce=[{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"}],Bit=[{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"}],bQ=[...Bce,...Bit],Hce="bambuddy-recent-colors",Hit=8,qit=[{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 Jh(t){let e=t.replace(/@.*$/,"").trim();e=e.replace(/\(Custom\)/i,"").trim(),e=e.replace(/^[#*]+\s*/,"").trim();const n=["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 a="",i=-1;for(const c of n){const d=e.toUpperCase().indexOf(c.toUpperCase());if(d!==-1){a=c,i=d;break}}let s="";i>0&&(s=e.substring(0,i).trim(),s=s.replace(/[-_\s]+$/,""));let o="";i!==-1&&a&&(o=e.substring(i+a.length).trim(),o=o.replace(/^[-_\s]+/,""));let l="";for(const c of _w)if(o.toLowerCase().includes(c.toLowerCase())){l=c;break}if(!l&&s)for(const c of _w){const d=new RegExp(`\\s+${c}$`,"i");if(d.test(s)){l=c,s=s.replace(d,"").trim();break}}return{brand:s,material:a,variant:l}}function qce(t,e){const n=new Set(Uit);for(const a of t){const{brand:i}=Jh(a.name);i&&i.length>1&&n.add(i)}if(e)for(const a of e)if(a.filament_vendor&&a.filament_vendor.length>1)n.add(a.filament_vendor);else{const{brand:i}=Jh(a.name);i&&i.length>1&&n.add(i)}return Array.from(n).sort((a,i)=>a.localeCompare(i))}function $it(t){const e=t.filter(a=>a.preset_type==="filament");return e.length===0?[]:e.map(a=>{const i=String(a.id),s=a.filament_type||i,o=Array.from(new Set([i,s]));return{code:i,name:a.name,displayName:a.name,isCustom:!1,allCodes:o}}).sort((a,i)=>a.displayName.localeCompare(i.displayName))}function $ce(t,e,n,a){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=n&&n.length>0?$it(n):[],c=[];if(a&&a.length>0)for(const u of a){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?qit:d.sort((u,m)=>u.displayName.localeCompare(m.displayName))}function Vce(t,e){if(!t)return;let n=e.find(a=>a.code===t);if(n||(n=e.find(a=>a.allCodes.includes(t))),!n){const a=t.toLowerCase();n=e.find(i=>i.code.toLowerCase()===a||i.allCodes.some(s=>s.toLowerCase()===a))}return n}function Gce(){try{const t=localStorage.getItem(Hce);if(t)return JSON.parse(t)}catch{}return[]}function Wce(t,e){const n=e.filter(i=>i.hex.toUpperCase()!==t.hex.toUpperCase()),a=[t,...n].slice(0,Hit);try{localStorage.setItem(Hce,JSON.stringify(a))}catch{}return a}function fF(t,e){if(!e.material)return!1;const a=(t.name||"").replace(/^High Flow[_\s]+/i,"").replace(/^Standard[_\s]+/i,"").replace(/^HF[_\s]+/i,"").replace(/^S[_\s]+/i,"").trim(),i=Jh(a);return!(!(i.material.toUpperCase()===e.material.toUpperCase())||e.brand&&!(i.brand.toLowerCase().includes(e.brand.toLowerCase())||e.brand.toLowerCase().includes(i.brand.toLowerCase()))||e.subtype&&!(i.variant.toLowerCase().includes(e.subtype.toLowerCase())||e.subtype.toLowerCase().includes(i.variant.toLowerCase())||a.toLowerCase().includes(e.subtype.toLowerCase())))}function Kce({formData:t,updateField:e,cloudAuthenticated:n,loadingCloudPresets:a,presetInputValue:i,setPresetInputValue:s,selectedPresetOption:o,filamentOptions:l,availableBrands:c,availableMaterials:d,quickAdd:u,quantity:m,onQuantityChange:p,errors:f}){const{t:g}=kt(),[w,b]=y.useState(!1),[x,S]=y.useState(!1),[N,C]=y.useState(!1),[P,T]=y.useState(!1),[A,F]=y.useState(""),[_,E]=y.useState(""),[H,I]=y.useState(""),[U,L]=y.useState(String(t.label_weight)),[Q,re]=y.useState(!1),J=y.useRef(null),ce=y.useRef(null),pe=y.useRef(null),ue=y.useRef(null);y.useEffect(()=>{const $=W=>{J.current&&!J.current.contains(W.target)&&b(!1),ue.current&&!ue.current.contains(W.target)&&T(!1),ce.current&&!ce.current.contains(W.target)&&S(!1),pe.current&&!pe.current.contains(W.target)&&C(!1)};return document.addEventListener("mousedown",$),()=>document.removeEventListener("mousedown",$)},[]);const X=y.useMemo(()=>{if(!i)return l;const $=i.toLowerCase();return l.filter(W=>W.displayName.toLowerCase().includes($)||W.code.toLowerCase().includes($))},[l,i]),ae=y.useMemo(()=>{if(!A)return c;const $=A.toLowerCase();return c.filter(D=>D.toLowerCase().includes($)).sort((D,j)=>{const B=D.toLowerCase()===$,Y=j.toLowerCase()===$;return B&&!Y?-1:!B&&Y?1:D.localeCompare(j)})},[c,A]),me=y.useMemo(()=>{if(!_)return _w;const $=_.toLowerCase();return _w.filter(W=>W.toLowerCase().includes($))},[_]),ge=y.useMemo(()=>{if(!H)return d;const $=H.toLowerCase();return d.filter(D=>D.toLowerCase().includes($)).sort((D,j)=>{const B=D.toLowerCase()===$,Y=j.toLowerCase()===$;return B&&!Y?-1:!B&&Y?1:D.localeCompare(j)})},[H,d]);y.useEffect(()=>{Q||L(String(t.label_weight))},[t.label_weight,Q]);const Pe=$=>{e("slicer_filament",$.code),s($.displayName),b(!1);const W=Jh($.name);W.material&&e("material",W.material),W.brand&&e("brand",W.brand),W.variant&&e("subtype",W.variant)};return r.jsxs("div",{className:"space-y-4",children:[!u&&r.jsx("div",{className:"flex items-center gap-2 text-xs text-bambu-gray",children:a?r.jsxs(r.Fragment,{children:[r.jsx(pt,{className:"w-3 h-3 animate-spin"})," ",g("inventory.loadingPresets")]}):n?r.jsxs(r.Fragment,{children:[r.jsx(Hh,{className:"w-3 h-3 text-bambu-green"})," ",g("inventory.cloudConnected")]}):r.jsxs(r.Fragment,{children:[r.jsx(UF,{className:"w-3 h-3"})," ",g("inventory.cloudNotConnected")]})}),!u&&r.jsxs("div",{children:[r.jsxs("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:[g("inventory.slicerPreset")," *"]}),r.jsxs("div",{className:"relative",ref:J,children:[r.jsx(Sr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50 pointer-events-none"}),r.jsx("input",{type:"text",className:"w-full pl-9 pr-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green",placeholder:g("inventory.searchPresets"),value:i,onChange:$=>{s($.target.value),b(!0)},onFocus:()=>{b(!0),s("")}}),w&&r.jsx("div",{className:"absolute z-50 w-full mt-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-lg max-h-64 overflow-y-auto",children:X.length===0?r.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:g("inventory.noPresetsFound")}):X.map($=>r.jsx("button",{type:"button",className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary truncate ${o?.code===$.code?"bg-bambu-green/10 text-bambu-green":"text-white"}`,onClick:()=>Pe($),children:$.displayName},`${$.code}::${$.name}`))})]}),o&&r.jsxs("div",{className:"mt-1 text-xs text-bambu-gray",children:[g("inventory.selectedPreset"),": ",r.jsx("span",{className:"font-mono text-bambu-green",children:o.code})]}),f?.slicer_filament&&r.jsx("p",{className:"mt-1 text-xs text-red-400",children:f.slicer_filament})]}),r.jsxs("div",{children:[r.jsxs("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:[g("inventory.material")," *"]}),r.jsxs("div",{className:"relative",ref:ue,children:[r.jsx("input",{type:"text",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green",placeholder:g("inventory.selectMaterial"),value:P?H:t.material,onChange:$=>{I($.target.value),T(!0)},onFocus:()=>{T(!0),I("")}}),r.jsx(Rn,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50 pointer-events-none"}),P&&r.jsxs("div",{className:"absolute z-50 w-full mt-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-lg max-h-48 overflow-y-auto",children:[ge.length===0?r.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:g("inventory.noResults")}):ge.map($=>r.jsx("button",{type:"button",className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary ${t.material===$?"bg-bambu-green/10 text-bambu-green":"text-white"}`,onClick:()=>{e("material",$),T(!1),I("")},children:$},$)),H&&!ge.includes(H)&&r.jsx("button",{type:"button",className:"w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary text-bambu-green border-t border-bambu-dark-tertiary",onClick:()=>{e("material",H),T(!1),I("")},children:g("inventory.useCustomMaterial",{material:H})})]})]}),f?.material&&r.jsx("p",{className:"mt-1 text-xs text-red-400",children:f.material})]}),r.jsxs("div",{children:[r.jsxs("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:[g("inventory.brand"),!u&&" *"]}),r.jsxs("div",{className:"relative",ref:ce,children:[r.jsx("input",{type:"text",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green",placeholder:g("inventory.searchBrand"),value:x?A:t.brand,onChange:$=>{F($.target.value),S(!0)},onFocus:()=>{S(!0),F("")}}),r.jsx(Rn,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50 pointer-events-none"}),x&&r.jsxs("div",{className:"absolute z-50 w-full mt-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-lg max-h-48 overflow-y-auto",children:[ae.length===0?r.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:g("inventory.noResults")}):ae.map($=>r.jsx("button",{type:"button",className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary ${t.brand===$?"bg-bambu-green/10 text-bambu-green":"text-white"}`,onClick:()=>{e("brand",$),S(!1),F("")},children:$},$)),A&&!ae.includes(A)&&r.jsx("button",{type:"button",className:"w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary text-bambu-green border-t border-bambu-dark-tertiary",onClick:()=>{e("brand",A),S(!1),F("")},children:g("inventory.useCustomBrand",{brand:A})})]})]}),f?.brand&&r.jsx("p",{className:"mt-1 text-xs text-red-400",children:f.brand})]}),r.jsxs("div",{children:[r.jsxs("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:[g("inventory.subtype"),!u&&" *"]}),r.jsxs("div",{className:"relative",ref:pe,children:[r.jsx("input",{type:"text",value:N?_:t.subtype,onChange:$=>{E($.target.value),C(!0)},onFocus:()=>{C(!0),E("")},placeholder:"Basic, Matte, Silk...",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green"}),r.jsx(Rn,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50 pointer-events-none"}),N&&r.jsxs("div",{className:"absolute z-50 w-full mt-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-lg max-h-48 overflow-y-auto",children:[me.length===0?r.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:g("inventory.noResults")}):me.map($=>r.jsx("button",{type:"button",className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary ${t.subtype===$?"bg-bambu-green/10 text-bambu-green":"text-white"}`,onClick:()=>{e("subtype",$),C(!1),E("")},children:$},$)),_&&!_w.some($=>$.toLowerCase()===_.toLowerCase().trim())&&r.jsx("button",{type:"button",className:"w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary text-bambu-green border-t border-bambu-dark-tertiary",onClick:()=>{e("subtype",_),C(!1),E("")},children:g("inventory.useCustomBrand",{brand:_})})]})]}),f?.subtype&&r.jsx("p",{className:"mt-1 text-xs text-red-400",children:f.subtype})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:g("inventory.labelWeight")}),r.jsxs("div",{className:"relative",children:[r.jsx("input",{type:"number",className:"w-full px-3 py-2 pr-7 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:outline-none focus:border-bambu-green",value:U,min:0,onFocus:()=>re(!0),onChange:$=>L($.target.value),onBlur:()=>{re(!1);const $=U.trim(),W=Number($);if(!$||!Number.isFinite(W)||W<0){L(String(t.label_weight));return}const D=Math.round(W);e("label_weight",D),L(String(D))}}),r.jsx("span",{className:"absolute right-2 top-1/2 -translate-y-1/2 text-xs text-bambu-gray",children:"g"})]})]}),u&&r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:g("inventory.quantity")}),r.jsx("input",{type:"number",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",value:m,min:1,max:100,onChange:$=>{const W=Math.max(1,Math.min(100,parseInt($.target.value)||1));p(W)}})]})]})}function Vit(t){const e=t.split(/[\s,]+/).map(i=>i.trim().replace(/^#/,"")).filter(Boolean),n=[],a=[];for(const i of e)(i.length===6||i.length===8)&&/^[0-9a-fA-F]+$/.test(i)?n.push(i.toLowerCase()):a.push(i);return{value:n.join(","),invalid:a}}function Yce({formData:t,updateField:e,recentColors:n,onColorUsed:a,catalogColors:i}){const{t:s}=kt(),[o,l]=y.useState(!1),[c,d]=y.useState(""),u=t.rgba.replace("#","").substring(0,6),m=F=>u.toUpperCase()===F.toUpperCase(),p=(F,_,E,H)=>{if(e("rgba",F.toUpperCase()+"FF"),e("color_name",_),E!==void 0){const I=E??"";S(I),C([]),P.current=I,e("extra_colors",I)}H!==void 0&&e("effect_type",H??""),a({name:_,hex:F})},f=y.useMemo(()=>{if(i.length===0)return[];const F=t.brand?.trim(),_=t.material?.toLowerCase().trim(),E=t.subtype?.toLowerCase().trim();if(!F&&!_)return[];const H=F?F.toLowerCase().split(/[\s\-_]+/).filter(L=>L.length>=2):[],I=L=>{if(H.length===0)return!0;const Q=L.toLowerCase();return H.some(re=>Q.includes(re))};if(F&&!_){const L=i.filter(Q=>I(Q.manufacturer));if(L.length>0)return L.map(Q=>({name:Q.color_name,hex:Q.hex_color.replace("#","").substring(0,6),manufacturer:Q.manufacturer,material:typeof Q.material=="string"?Q.material:void 0,extra_colors:Q.extra_colors??null,effect_type:Q.effect_type??null}))}const U=_&&E?`${_} ${E}`:"";if(U){const L=i.filter(re=>I(re.manufacturer)&&re.material?.toLowerCase()===U);if(L.length>0)return L.map(re=>({name:re.color_name,hex:re.hex_color.replace("#","").substring(0,6),manufacturer:re.manufacturer,material:typeof re.material=="string"?re.material:void 0,extra_colors:re.extra_colors??null,effect_type:re.effect_type??null}));const Q=U.replace(/\+$/,"");if(Q!==U){const re=i.filter(J=>I(J.manufacturer)&&J.material?.toLowerCase()===Q);if(re.length>0)return re.map(J=>({name:J.color_name,hex:J.hex_color.replace("#","").substring(0,6),manufacturer:J.manufacturer,material:typeof J.material=="string"?J.material:void 0}))}}if(_){const L=i.filter(Q=>I(Q.manufacturer)&&(!Q.material||Q.material.toLowerCase().startsWith(_)));if(L.length>0)return L.map(Q=>({name:Q.color_name,hex:Q.hex_color.replace("#","").substring(0,6),manufacturer:Q.manufacturer,material:typeof Q.material=="string"?Q.material:void 0,extra_colors:Q.extra_colors??null,effect_type:Q.effect_type??null}))}return[]},[i,t.brand,t.material,t.subtype]),g=y.useMemo(()=>{if(!c)return f;if(f.length===0)return[];const F=c.toLowerCase();return f.filter(E=>E.name.toLowerCase().includes(F)||(E.manufacturer?.toLowerCase().includes(F)??!1)||(E.material?.toLowerCase().includes(F)??!1))},[c,f]),w=f.length>0,b=y.useMemo(()=>c?bQ.filter(F=>F.name.toLowerCase().includes(c.toLowerCase())):o?bQ:Bce,[c,o]),[x,S]=y.useState(t.extra_colors),[N,C]=y.useState([]),P=y.useRef(t.extra_colors);y.useEffect(()=>{t.extra_colors!==P.current&&(S(t.extra_colors),C([]),P.current=t.extra_colors)},[t.extra_colors]);const T=y.useMemo(()=>rj({rgba:t.rgba,extraColors:t.extra_colors,effectType:t.effect_type,subtype:t.subtype,effectSize:"bar"}),[t.rgba,t.extra_colors,t.effect_type,t.subtype]),A=F=>{if(S(F),!F.trim()){C([]),P.current="",e("extra_colors","");return}const{value:_,invalid:E}=Vit(F);C(E),P.current=_,e("extra_colors",_)};return r.jsxs("div",{className:"space-y-3",children:[r.jsx("div",{className:"h-10 rounded-lg border border-bambu-dark-tertiary",style:T,"data-testid":"color-preview-banner"}),n.length>0&&r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-bambu-gray shrink-0",children:[r.jsx(Zn,{className:"w-3 h-3"}),r.jsx("span",{children:s("inventory.recentColors")})]}),r.jsx("div",{className:"flex flex-wrap gap-1.5",children:n.map(F=>r.jsx("button",{type:"button",onClick:()=>p(F.hex,F.name),className:`w-6 h-6 rounded border-2 transition-all hover:scale-110 ${m(F.hex)?"border-bambu-green ring-1 ring-bambu-green/30 scale-110":"border-bambu-dark-tertiary"}`,style:{backgroundColor:`#${F.hex}`},title:F.name},F.hex))})]}),r.jsxs("div",{className:"relative",children:[r.jsx(Sr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50 pointer-events-none"}),r.jsx("input",{type:"text",className:"w-full pl-9 pr-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green",placeholder:s("inventory.searchColors"),value:c,onChange:F=>d(F.target.value)})]}),w?r.jsxs("div",{className:"space-y-1.5",children:[r.jsx("span",{className:"text-xs text-bambu-gray",children:c?s("inventory.searchResults"):`${t.brand}${t.material?` ${t.material}`:""}`}),r.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[g.map(F=>r.jsx("button",{type:"button",onClick:()=>p(F.hex,F.name,F.extra_colors,F.effect_type),className:`w-6 h-6 rounded border-2 transition-all hover:scale-110 hover:z-20 relative group ${m(F.hex)?"border-bambu-green ring-1 ring-bambu-green/30 scale-110":"border-bambu-dark-tertiary"}`,style:{backgroundColor:`#${F.hex}`},title:F.manufacturer&&F.material?`${F.name} (${F.manufacturer} — ${F.material})`:F.manufacturer?`${F.name} (${F.manufacturer})`:F.name,children:r.jsx("span",{className:"absolute -bottom-7 left-1/2 -translate-x-1/2 px-2 py-0.5 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-xs whitespace-nowrap opacity-0 group-hover:opacity-100 transition-opacity pointer-events-none z-20 shadow-lg text-white",children:F.manufacturer&&F.material?`${F.name} (${F.manufacturer} — ${F.material})`:F.manufacturer?`${F.name} (${F.manufacturer})`:F.name})},`${F.hex}-${F.name}-${F.manufacturer??""}`)),g.length===0&&r.jsx("p",{className:"text-sm text-bambu-gray py-1",children:s("inventory.noColorsFound")})]})]}):r.jsxs("div",{className:"space-y-1.5",children:[r.jsxs("div",{className:"flex items-center justify-between text-xs text-bambu-gray",children:[r.jsx("span",{children:s(c?"inventory.searchResults":o?"inventory.allColors":"inventory.commonColors")}),!c&&r.jsx("button",{type:"button",onClick:()=>l(!o),className:"flex items-center gap-1 hover:text-white transition-colors",children:o?r.jsxs(r.Fragment,{children:[s("inventory.showLess")," ",r.jsx(tl,{className:"w-3 h-3"})]}):r.jsxs(r.Fragment,{children:[s("inventory.showAll")," ",r.jsx(Rn,{className:"w-3 h-3"})]})})]}),r.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[b.map(F=>r.jsx("button",{type:"button",onClick:()=>p(F.hex,F.name),className:`w-6 h-6 rounded border-2 transition-all hover:scale-110 hover:z-20 relative group ${m(F.hex)?"border-bambu-green ring-1 ring-bambu-green/30 scale-110":"border-bambu-dark-tertiary"}`,style:{backgroundColor:`#${F.hex}`},title:F.name,children:r.jsx("span",{className:"absolute -bottom-7 left-1/2 -translate-x-1/2 px-2 py-0.5 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-xs whitespace-nowrap opacity-0 group-hover:opacity-100 transition-opacity pointer-events-none z-20 shadow-lg text-white",children:F.name})},F.hex)),b.length===0&&r.jsx("p",{className:"text-sm text-bambu-gray py-1",children:s("inventory.noColorsFound")})]})]}),r.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:s("inventory.colorName")}),r.jsx("input",{type:"text",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green",placeholder:s("inventory.colorNamePlaceholder"),value:t.color_name,onChange:F=>e("color_name",F.target.value)})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:s("inventory.hexColor")}),r.jsxs("div",{className:"flex gap-2",children:[r.jsxs("div",{className:"relative flex-1",children:[r.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-bambu-gray",children:"#"}),r.jsx("input",{type:"text",className:"w-full pl-7 pr-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm font-mono uppercase focus:outline-none focus:border-bambu-green",placeholder:"RRGGBB",value:u.toUpperCase(),onChange:F=>{const _=F.target.value.replace("#","").replace(/[^0-9A-Fa-f]/g,"").toUpperCase();if(_.length>8)return;const E=_.length===8?_:_.length===7?_.substring(0,6)+"FF":_.padEnd(6,"0")+"FF";e("rgba",E)}})]}),r.jsx("input",{type:"color",className:"w-11 h-[38px] rounded-lg cursor-pointer border border-bambu-dark-tertiary shrink-0 bg-transparent",value:`#${u}`,onChange:F=>{const _=F.target.value.replace("#","").toUpperCase();e("rgba",_+"FF")},title:s("inventory.pickColor")})]})]})]}),r.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3 pt-2 border-t border-bambu-dark-tertiary/50",children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:s("inventory.extraColorsLabel")}),r.jsx("input",{type:"text",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm font-mono placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green",placeholder:s("inventory.extraColorsPlaceholder"),value:x,onChange:F=>A(F.target.value),"data-testid":"extra-colors-input"}),N.length>0&&r.jsx("p",{className:"text-xs text-red-400 mt-1",children:s("inventory.extraColorsInvalid",{tokens:N.join(", ")})}),!N.length&&r.jsx("p",{className:"text-xs text-bambu-gray/70 mt-1",children:s("inventory.extraColorsHint")})]}),r.jsxs("div",{children:[r.jsxs("label",{className:"block text-sm font-medium text-bambu-gray mb-1 flex items-center gap-1.5",children:[r.jsx(Dg,{className:"w-3.5 h-3.5"}),s("inventory.colorEffectLabel")]}),r.jsxs("div",{className:"flex gap-2 items-stretch",children:[r.jsx("select",{className:"flex-1 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",value:t.effect_type,onChange:F=>e("effect_type",F.target.value),"data-testid":"effect-type-select",children:WI.map(F=>r.jsx("option",{value:F.value,children:s(F.labelKey)},F.value||"none"))}),r.jsx(rU,{rgba:t.rgba,extraColors:t.extra_colors,effectType:t.effect_type,subtype:t.subtype,effectSize:"preview",className:"w-10 h-10",shape:"square"})]})]})]})]})}function Git({catalog:t,value:e,onChange:n,catalogId:a,onCatalogIdChange:i}){const{t:s}=kt(),[o,l]=y.useState(!1),[c,d]=y.useState(""),u=y.useRef(null),m=y.useRef(null);y.useEffect(()=>{const w=b=>{u.current&&!u.current.contains(b.target)&&l(!1)};return document.addEventListener("mousedown",w),()=>document.removeEventListener("mousedown",w)},[]),y.useEffect(()=>{if(t.length===0)return;const w=t.filter(b=>b.weight===e);if(a){const b=t.find(x=>x.id===a);if(b&&b.weight===e)return}w.length===1?i(w[0].id):w.length===0&&a!==null&&i(null)},[e,t,a,i]);const p=y.useMemo(()=>{if(!c)return t;const w=c.toLowerCase();return t.filter(b=>b.name.toLowerCase().includes(w)||b.weight.toString().includes(w))},[t,c]),f=y.useMemo(()=>t.filter(w=>w.weight===e),[t,e]),g=y.useMemo(()=>{if(o)return c;if(a){const w=t.find(b=>b.id===a);if(w)return w.name}return f.length>0?f[0].name:""},[o,c,a,t,f]);return r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:r.jsxs("span",{className:"flex items-center gap-2",children:[r.jsx(FZ,{className:"w-3.5 h-3.5 text-bambu-gray"}),s("inventory.coreWeight")]})}),r.jsxs("div",{className:"flex gap-2 items-center",children:[r.jsxs("div",{className:"flex-1 min-w-0 relative",ref:u,children:[r.jsx("input",{ref:m,type:"text",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green",placeholder:s("inventory.searchSpoolWeight"),value:g,onFocus:()=>{l(!0),d("")},onChange:w=>{d(w.target.value),l(!0)}}),o&&r.jsx("div",{className:"absolute z-50 w-full mt-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-lg max-h-64 overflow-y-auto",children:p.length===0?r.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:s("inventory.noResults")}):p.map(w=>r.jsxs("button",{type:"button",className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex justify-between items-center ${(a?w.id===a:w.weight===e)?"bg-bambu-green/10 text-bambu-green":"text-white"}`,onClick:()=>{i(w.id),n(w.weight),l(!1),d("")},children:[r.jsx("span",{className:"truncate",children:w.name}),r.jsxs("span",{className:"font-mono text-xs text-bambu-gray ml-2 shrink-0",children:[w.weight,"g"]})]},w.id))})]}),r.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[r.jsx("input",{type:"number",className:"w-16 px-2 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm text-center font-mono focus:outline-none focus:border-bambu-green",value:e,min:0,max:2e3,onChange:w=>{const b=parseInt(w.target.value);!isNaN(b)&&b>=0&&n(b)}}),r.jsx("span",{className:"text-bambu-gray text-sm",children:"g"})]})]})]})}function Xce({formData:t,updateField:e,spoolCatalog:n,currencySymbol:a,availableCategories:i,globalLowStockThreshold:s,spoolmanMode:o=!1}){const{t:l}=kt(),{showToast:c}=rn(),[d,u]=y.useState(""),[m,p]=y.useState(!1),[f,g]=y.useState(""),[w,b]=y.useState(!1),x=Math.max(0,t.label_weight-t.weight_used),S=t.core_weight+x;return y.useEffect(()=>{m||u(String(S))},[m,S]),y.useEffect(()=>{w||g(String(x))},[w,x]),r.jsxs("div",{className:"space-y-4",children:[o?r.jsx("p",{className:"text-xs text-bambu-gray px-1",children:l("inventory.spoolWeightManagedBySpoolman")}):r.jsx(Git,{catalog:n,value:t.core_weight,onChange:N=>e("core_weight",N),catalogId:t.core_weight_catalog_id,onCatalogIdChange:N=>e("core_weight_catalog_id",N)}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:l("inventory.currentWeight")}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsxs("div",{className:"relative flex-1",children:[r.jsx("input",{type:"number",value:f,min:0,max:t.label_weight,onFocus:()=>b(!0),onChange:N=>{g(N.target.value)},onBlur:()=>{b(!1);const N=f.trim(),C=Number(N);if(!N||!Number.isFinite(C)||C<0||C>t.label_weight){g(String(x));return}const P=Math.round(C);e("weight_used",Math.max(0,t.label_weight-P)),g(String(P))},className:"w-full px-3 py-2 pr-7 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:outline-none focus:border-bambu-green"}),r.jsx("span",{className:"absolute right-2 top-1/2 -translate-y-1/2 text-xs text-bambu-gray",children:"g"})]}),r.jsxs("span",{className:"text-xs text-bambu-gray shrink-0",children:["/ ",t.label_weight,"g"]})]})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:l("inventory.measuredWeight")}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsxs("div",{className:"relative flex-1",children:[r.jsx("input",{type:"number",value:d,min:0,onFocus:()=>p(!0),onChange:N=>{u(N.target.value)},onBlur:()=>{p(!1);const N=d.trim(),C=Number(N),P=t.core_weight,T=t.core_weight+t.label_weight;if(!N||!Number.isFinite(C)||CT){c(l("inventory.measuredWeightError",{min:P,max:T}),"error"),u(String(S));return}const A=Math.round(C),F=Math.max(0,Math.min(t.label_weight,A-t.core_weight));e("weight_used",Math.max(0,t.label_weight-F)),u(String(A))},className:"w-full px-3 py-2 pr-7 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:outline-none focus:border-bambu-green"}),r.jsx("span",{className:"absolute right-2 top-1/2 -translate-y-1/2 text-xs text-bambu-gray",children:"g"})]}),r.jsxs("span",{className:"text-xs text-bambu-gray shrink-0",children:["/ ",t.core_weight+t.label_weight,"g"]})]})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:l("inventory.costPerKg","Cost per kg")}),r.jsx("div",{className:"flex items-center gap-2",children:r.jsxs("div",{className:"relative flex-1",children:[r.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-bambu-gray text-sm pointer-events-none",children:a}),r.jsx("input",{type:"number",value:t.cost_per_kg??"",min:0,step:.01,placeholder:"0.00",onChange:N=>{const C=N.target.value===""?null:parseFloat(N.target.value);e("cost_per_kg",C)},style:{paddingLeft:`${Math.max(2,a.length*.6+1)}rem`},className:"w-full py-2 pr-3 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:outline-none focus:border-bambu-green"})]})})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",htmlFor:"spool-category",children:l("inventory.category")}),r.jsx("input",{id:"spool-category",type:"text",list:"spool-category-options",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green",placeholder:l("inventory.categoryPlaceholder"),value:t.category,maxLength:50,onChange:N=>e("category",N.target.value)}),i.length>0&&r.jsx("datalist",{id:"spool-category-options",children:i.map(N=>r.jsx("option",{value:N},N))})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",htmlFor:"spool-low-stock-threshold",children:l("inventory.lowStockThresholdOverride")}),r.jsx("div",{className:"flex items-center gap-2",children:r.jsxs("div",{className:"relative flex-1",children:[r.jsx("input",{id:"spool-low-stock-threshold",type:"number",className:"w-full px-3 py-2 pr-8 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green",placeholder:String(s),value:t.low_stock_threshold_pct??"",min:1,max:99,step:1,onChange:N=>{const C=N.target.value;if(C===""){e("low_stock_threshold_pct",null);return}const P=Number(C);Number.isFinite(P)&&e("low_stock_threshold_pct",Math.min(99,Math.max(1,Math.round(P))))}}),r.jsx("span",{className:"absolute right-3 top-1/2 -translate-y-1/2 text-xs text-bambu-gray pointer-events-none",children:"%"})]})}),r.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:l("inventory.lowStockThresholdOverrideHelp",{global:s})})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:l("inventory.note")}),r.jsx("textarea",{className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green resize-none min-h-[80px]",placeholder:l("inventory.notePlaceholder"),value:t.note,onChange:N=>e("note",N.target.value)})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:l("inventory.storageLocation")}),r.jsx("input",{type:"text",maxLength:255,className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green",placeholder:l("inventory.storageLocationPlaceholder"),value:t.storage_location,onChange:N=>e("storage_location",N.target.value)})]})]})}function Wit({filaments:t,isLoading:e,selectedId:n,onSelect:a}){const{t:i}=kt(),[s,o]=y.useState(!1),[l,c]=y.useState(""),d=y.useRef(null),u=y.useRef(null),m=y.useMemo(()=>t.find(b=>b.id===n)??null,[t,n]);y.useEffect(()=>{const b=x=>{d.current&&!d.current.contains(x.target)&&(o(!1),c(""))};return document.addEventListener("mousedown",b),()=>document.removeEventListener("mousedown",b)},[]);const p=y.useMemo(()=>{const b=l.toLowerCase().trim();return b?t.filter(x=>x.name.toLowerCase().includes(b)||(x.material?.toLowerCase().includes(b)??!1)||(x.vendor?.name.toLowerCase().includes(b)??!1)||(x.color_name?.toLowerCase().includes(b)??!1)):t},[t,l]);y.useEffect(()=>{s&&u.current?.focus()},[s]);const f=()=>{o(!0),c("")},g=b=>{a(b),o(!1),c("")},w=b=>b?`#${b.replace("#","")}`:"#808080";return r.jsxs("div",{ref:d,className:"relative",children:[r.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:i("inventory.pickFromSpoolmanCatalog")}),r.jsxs("button",{type:"button",onClick:f,className:"w-full flex items-center gap-2 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-left focus:outline-none focus:border-bambu-green hover:border-bambu-gray transition-colors",children:[e?r.jsx(pt,{className:"w-4 h-4 text-bambu-gray animate-spin shrink-0"}):m?r.jsxs(r.Fragment,{children:[r.jsx("span",{className:"w-4 h-4 rounded-full shrink-0 border border-white/20",style:{backgroundColor:w(m.color_hex)},"aria-label":i("inventory.spoolmanFilamentColorSwatch")}),r.jsxs("span",{className:"text-white text-sm truncate flex-1",children:[m.vendor?.name?`${m.vendor.name} — `:"",m.name]})]}):r.jsxs(r.Fragment,{children:[r.jsx(Br,{className:"w-4 h-4 text-bambu-gray shrink-0"}),r.jsx("span",{className:"text-bambu-gray text-sm flex-1",children:i("inventory.spoolmanFilamentCatalog")})]}),r.jsx(Rn,{className:"w-4 h-4 text-bambu-gray shrink-0 ml-auto"})]}),s&&r.jsxs("div",{className:"absolute z-50 w-full mt-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl",children:[r.jsx("div",{className:"p-2 border-b border-bambu-dark-tertiary",children:r.jsx("input",{ref:u,type:"text",value:l,onChange:b=>c(b.target.value),placeholder:i("inventory.pickFromSpoolmanCatalog"),className:"w-full px-2 py-1.5 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-sm placeholder-bambu-gray focus:outline-none focus:border-bambu-green"})}),r.jsx("ul",{className:"max-h-56 overflow-y-auto py-1",children:e?r.jsxs("li",{className:"flex items-center justify-center gap-2 py-4 text-bambu-gray text-sm",children:[r.jsx(pt,{className:"w-4 h-4 animate-spin"}),r.jsx("span",{children:i("common.loading","Loading…")})]}):p.length===0?r.jsx("li",{className:"py-4 text-center text-bambu-gray text-sm",children:i("inventory.noSpoolmanFilaments")}):p.map(b=>r.jsx("li",{children:r.jsxs("button",{type:"button",onClick:()=>g(b),className:`w-full flex items-center gap-2 px-3 py-2 text-left hover:bg-bambu-dark-tertiary transition-colors ${b.id===n?"bg-bambu-dark-tertiary":""}`,children:[r.jsx("span",{className:"w-4 h-4 rounded-full shrink-0 border border-white/20",style:{backgroundColor:w(b.color_hex)},"aria-label":i("inventory.spoolmanFilamentColorSwatch")}),r.jsxs("span",{className:"flex-1 min-w-0",children:[r.jsxs("span",{className:"block text-white text-sm truncate",children:[b.vendor?.name?`${b.vendor.name} — `:"",b.name]}),r.jsxs("span",{className:"block text-bambu-gray text-xs truncate",children:[[b.material,b.color_name].filter(Boolean).join(" · "),b.weight?` · ${b.weight}g`:""]})]})]})},b.id))})]})]})}function Qce({formData:t,printersWithCalibrations:e,selectedProfiles:n,setSelectedProfiles:a,expandedPrinters:i,setExpandedPrinters:s}){const{t:o}=kt(),l=p=>{s(f=>{const g=new Set(f);return g.has(p)?g.delete(p):g.add(p),g})},c=(p,f,g)=>{const w=`${p}:${f}:${g??"null"}`,b=`${p}:${g??"null"}`;a(x=>{const S=new Set(x);if(S.has(w))S.delete(w);else{for(const N of Array.from(S)){const C=N.split(":");`${C[0]}:${C[2]}`===b&&S.delete(N)}S.add(w)}return S})},d=()=>{const p=new Set;for(const{printer:f,calibrations:g}of e){if(!f.connected)continue;const w=g.filter(x=>fF(x,t)),b=new Map;for(const x of w){const S=`${x.extruder_id??"null"}`;b.has(S)||b.set(S,[]),b.get(S).push(x)}for(const[x,S]of b)if(S.length>0){const C=[...S].sort((P,T)=>T.k_value-P.k_value)[0];p.add(`${f.id}:${C.cali_idx}:${x}`)}}a(p)};if(!t.material)return r.jsx("div",{className:"p-6 bg-bambu-dark rounded-lg text-center",children:r.jsx("p",{className:"text-bambu-gray",children:o("inventory.selectMaterialFirst")})});if(e.length===0)return r.jsx("div",{className:"p-6 bg-bambu-dark rounded-lg text-center",children:r.jsx("p",{className:"text-bambu-gray",children:o("inventory.noPrintersConfigured")})});const u=e.reduce((p,{printer:f,calibrations:g})=>f.connected?p+g.filter(w=>fF(w,t)).length:p,0),m=(p,f)=>{const g=`${p.id}:${f.cali_idx}:${f.extruder_id??"null"}`,w=n.has(g);return r.jsxs("label",{className:`flex items-center gap-3 p-3 rounded-lg cursor-pointer transition-all border ${w?"bg-bambu-green/10 border-bambu-green/30":"bg-bambu-dark border-transparent hover:bg-bambu-dark/80"}`,children:[r.jsx("input",{type:"checkbox",checked:w,onChange:()=>c(String(p.id),f.cali_idx,f.extruder_id),className:"w-4 h-4 rounded border-bambu-dark-tertiary text-bambu-green focus:ring-bambu-green"}),r.jsx("div",{className:"flex-1 min-w-0",children:r.jsx("span",{className:`text-sm font-medium ${w?"text-bambu-green":"text-white"}`,children:f.name||f.filament_id})}),r.jsx("div",{className:"flex items-center gap-2 shrink-0",children:r.jsxs("span",{className:"text-xs font-mono px-2 py-0.5 rounded bg-bambu-dark text-bambu-gray",children:["K=",f.k_value.toFixed(3)]})})]},`${f.cali_idx}-${f.extruder_id}`)};return r.jsxs("div",{className:"space-y-4",children:[r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("p",{className:"text-xs text-bambu-gray",children:[o("inventory.matchingFilter"),": ",t.brand||o("inventory.anyBrand")," / ",t.material," / ",t.subtype||o("inventory.anyVariant")]}),u>0&&r.jsxs("button",{type:"button",onClick:d,className:"flex items-center gap-1.5 px-2 py-1 text-xs bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-bambu-gray hover:text-white hover:border-bambu-green transition-colors",children:[r.jsx(Dg,{className:"w-3.5 h-3.5"}),o("inventory.autoSelect")," (",u,")"]})]}),r.jsx("div",{className:"space-y-3",children:e.map(({printer:p,calibrations:f})=>{const g=i.has(String(p.id)),w=f.filter(C=>fF(C,t)),b=w.length,x=w.some(C=>C.extruder_id!==void 0&&C.extruder_id!==null&&C.extruder_id>0),S=w.filter(C=>C.extruder_id===1),N=w.filter(C=>C.extruder_id===0||C.extruder_id===void 0||C.extruder_id===null);return r.jsxs("div",{className:"border border-bambu-dark-tertiary rounded-lg overflow-hidden",children:[r.jsxs("button",{type:"button",onClick:()=>l(String(p.id)),className:"w-full px-4 py-3 flex items-center justify-between bg-bambu-dark-secondary hover:bg-bambu-dark-tertiary transition-colors",children:[r.jsxs("div",{className:"flex items-center gap-3",children:[g?r.jsx(Rn,{className:"w-4 h-4 text-bambu-gray"}):r.jsx(Va,{className:"w-4 h-4 text-bambu-gray"}),r.jsx("span",{className:"font-medium text-white",children:p.name}),b>0?r.jsxs("span",{className:"text-xs px-2 py-0.5 rounded-full bg-bambu-green/20 text-bambu-green",children:[b," ",o(b!==1?"inventory.matches":"inventory.match")]}):r.jsx("span",{className:"text-xs px-2 py-0.5 rounded-full bg-bambu-dark-tertiary text-bambu-gray",children:o("inventory.noMatches")})]}),r.jsx("span",{className:`text-xs px-2 py-1 rounded-full ${p.connected?"bg-green-500/20 text-green-500":"bg-bambu-gray/20 text-bambu-gray"}`,children:p.connected?o("inventory.connected"):o("inventory.offline")})]}),g&&r.jsx("div",{className:"px-4 py-3 space-y-3 bg-bambu-dark border-t border-bambu-dark-tertiary",children:p.connected?b===0?r.jsx("p",{className:"text-sm text-bambu-gray italic py-2",children:o("inventory.noKProfilesMatch")}):x?r.jsxs(r.Fragment,{children:[S.length>0&&r.jsxs("div",{className:"space-y-2",children:[r.jsx("p",{className:"text-xs font-medium text-bambu-gray uppercase tracking-wide",children:o("inventory.leftNozzle")}),r.jsx("div",{className:"space-y-2",children:S.map(C=>m(p,C))})]}),N.length>0&&r.jsxs("div",{className:"space-y-2",children:[r.jsx("p",{className:"text-xs font-medium text-bambu-gray uppercase tracking-wide",children:o("inventory.rightNozzle")}),r.jsx("div",{className:"space-y-2",children:N.map(C=>m(p,C))})]})]}):r.jsx("div",{className:"space-y-2",children:w.map(C=>m(p,C))}):r.jsx("p",{className:"text-sm text-bambu-gray italic py-2",children:o("inventory.printerOffline")})})]},p.id)})}),n.size>0&&r.jsx("div",{className:"p-3 bg-bambu-green/10 border border-bambu-green/30 rounded-lg",children:r.jsxs("p",{className:"text-sm text-white",children:[r.jsx("span",{className:"font-semibold",children:n.size})," ",o("inventory.profilesSelected")]})})]})}function Kit(t){const e=new Date(t);return e.toLocaleDateString("en-GB",{day:"2-digit",month:"2-digit",year:"2-digit"})+" "+e.toLocaleTimeString("en-GB",{hour:"2-digit",minute:"2-digit"})}const Yit={completed:"text-bambu-green",failed:"text-red-400",aborted:"text-yellow-400"};function Xit({spoolId:t}){const{t:e}=kt(),n=en(),{showToast:a}=rn(),{data:i,isLoading:s}=Ge({queryKey:["spool-usage",t],queryFn:()=>ie.getSpoolUsageHistory(t)}),o=it({mutationFn:()=>ie.clearSpoolUsageHistory(t),onSuccess:()=>{n.invalidateQueries({queryKey:["spool-usage",t]}),a(e("inventory.historyCleared"),"success")}});return s?r.jsx("div",{className:"flex justify-center py-4",children:r.jsx(pt,{className:"w-5 h-5 animate-spin text-bambu-green"})}):!i||i.length===0?r.jsxs("div",{className:"text-center py-4 text-bambu-gray text-sm",children:[r.jsx(Zn,{className:"w-5 h-5 mx-auto mb-2 opacity-50"}),e("inventory.noUsageHistory")]}):r.jsxs("div",{className:"space-y-2",children:[r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsx("h4",{className:"text-sm font-medium text-white",children:e("inventory.usageHistory")}),r.jsxs(Me,{variant:"ghost",size:"sm",onClick:()=>o.mutate(),disabled:o.isPending,className:"text-xs text-bambu-gray hover:text-red-400",children:[r.jsx(Jt,{className:"w-3 h-3 mr-1"}),e("inventory.clearHistory")]})]}),r.jsx("div",{className:"max-h-48 overflow-y-auto space-y-1",children:i.map(l=>r.jsxs("div",{className:"flex items-center justify-between p-2 rounded bg-bambu-dark/50 text-xs",children:[r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsx("span",{className:"text-bambu-gray",children:Kit(l.created_at)}),l.print_name&&r.jsx("span",{className:"text-white ml-2 truncate",title:l.print_name,children:l.print_name})]}),r.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0 ml-2",children:[r.jsxs("span",{className:"text-white font-medium",children:[l.weight_used.toFixed(1),"g"]}),r.jsxs("span",{className:"text-bambu-gray",children:["(",l.percent_used,"%)"]}),r.jsx("span",{className:Yit[l.status]||"text-bambu-gray",children:l.status})]})]},l.id))})]})}const xQ={tag_uid:null,tray_uuid:null,tag_type:null,data_origin:null};function Qit({isOpen:t,onClose:e,spool:n,mode:a,printersWithCalibrations:i=[],currencySymbol:s,onSpoolsCreated:o,spoolmanMode:l=!1,spoolsQueryKey:c=["inventory-spools"]}){const{t:d}=kt(),u=en(),{showToast:m}=rn(),p=a==="edit",f=a==="copy",[g,w]=y.useState(YI),[b,x]=y.useState({}),[S,N]=y.useState("filament"),[C,P]=y.useState(!1),[T,A]=y.useState(!1),[F,_]=y.useState(!1),[E,H]=y.useState(1),[I,U]=y.useState(!1),[L,Q]=y.useState(!1),[re,J]=y.useState([]),[ce,pe]=y.useState(""),[ue,X]=y.useState([]),[ae,me]=y.useState([]),[ge,Pe]=y.useState([]),[$,W]=y.useState([]),[D,j]=y.useState([]),[B,Y]=y.useState([]),[O,se]=y.useState(new Set),[z,G]=y.useState(new Set),K=i.length>0?i:B,Z=O.size,{data:oe=[],isLoading:ee,error:fe}=Ge({queryKey:["spoolman-inventory-filaments"],queryFn:()=>ie.getSpoolmanInventoryFilaments(),enabled:l&&t,staleTime:6e4,retry:!1});y.useEffect(()=>{j(Gce())},[]),y.useEffect(()=>{t&&((async()=>{Q(!0);try{const gt=await ie.getCloudStatus();if(U(gt.is_authenticated),gt.is_authenticated){const ct=await ie.getFilamentPresets();J(ct)}}catch(gt){console.error("Failed to fetch cloud presets:",gt),U(!1)}finally{Q(!1)}})(),l||ie.getSpoolCatalog().then(X).catch(console.error),ie.getColorCatalog().then(W).catch(console.error),ie.getLocalPresets().then(gt=>me(gt.filament)).catch(console.error),ie.getBuiltinFilaments().then(Pe).catch(console.error),i.length===0&&(async()=>{try{const gt=await ie.getPrinters(),ct=await Promise.all(gt.map(Ot=>ie.getPrinterStatus(Ot.id).catch(()=>null))),at=[];for(let Ot=0;Ot({cali_idx:dt.slot_id,filament_id:dt.filament_id,setting_id:dt.setting_id||"",name:dt.name,k_value:parseFloat(dt.k_value)||0,n_coef:parseFloat(dt.n_coef)||0,extruder_id:dt.extruder_id,nozzle_diameter:dt.nozzle_diameter}))}catch{}at.push({printer:{...Wt,connected:Yt},calibrations:un})}Y(at)}catch(gt){console.error("Failed to fetch printer calibrations:",gt)}})())},[t,i.length]);const de=y.useMemo(()=>$ce(re,new Set,ae,ge),[re,ae,ge]),le=y.useMemo(()=>{const Ke=qce(re,ae),gt=$.map(at=>at.manufacturer?.trim()).filter(at=>!!at),ct=new Set([...Ke,...gt]);return Array.from(ct).sort((at,Ot)=>at.localeCompare(Ot))},[re,ae,$]),q=y.useMemo(()=>{const Ke=$.map(ct=>ct.material?.trim()).filter(ct=>!!ct),gt=new Set([...Uce,...Ke]);return Array.from(gt).sort((ct,at)=>ct.localeCompare(at))},[$]),R=y.useMemo(()=>{const Ke=[];for(const gt of $){const ct=gt.manufacturer?.trim(),at=gt.material?.trim();ct&&at&&Ke.push({brand:ct,material:at})}for(const gt of re){const ct=Jh(gt.name);ct.brand&&ct.material&&Ke.push({brand:ct.brand,material:ct.material})}for(const gt of ae){const ct=Jh(gt.name),at=gt.filament_vendor?.trim()||ct.brand,Ot=ct.material;at&&Ot&&Ke.push({brand:at,material:Ot})}return Ke},[re,$,ae]),ne=y.useMemo(()=>{const Ke=new Map;for(const gt of R){const ct=gt.brand.toLowerCase(),at=gt.material.toLowerCase();Ke.has(ct)||Ke.set(ct,new Set),Ke.get(ct).add(at)}return Ke},[R]),xe=y.useMemo(()=>{const Ke=new Map;for(const gt of R){const ct=gt.brand.toLowerCase(),at=gt.material.toLowerCase();Ke.has(at)||Ke.set(at,new Set),Ke.get(at).add(ct)}return Ke},[R]),ve=y.useMemo(()=>{if(!g.material)return le;const Ke=g.material.toLowerCase(),gt=xe.get(Ke);return!gt||gt.size===0?le:le.filter(ct=>gt.has(ct.toLowerCase()))},[le,g.material,xe]),Ce=y.useMemo(()=>{if(!g.brand)return q;const Ke=g.brand.toLowerCase(),gt=ne.get(Ke);return!gt||gt.size===0?q:q.filter(ct=>gt.has(ct.toLowerCase()))},[q,g.brand,ne]),ye=y.useMemo(()=>Vce(g.slicer_filament,de),[g.slicer_filament,de]);y.useEffect(()=>{if(t){if(n){const Ke=n.rgba&&/^[0-9A-Fa-f]{8}$/.test(n.rgba)?n.rgba:"808080FF";if(w({material:n.material||"",subtype:n.subtype||"",brand:n.brand||"",color_name:n.color_name_is_synthesized?"":n.color_name||"",rgba:Ke,extra_colors:n.extra_colors||"",effect_type:n.effect_type||"",label_weight:n.label_weight||1e3,core_weight:n.core_weight||250,core_weight_catalog_id:n.core_weight_catalog_id??null,weight_used:f?0:n.weight_used||0,slicer_filament:n.slicer_filament||"",note:n.note||"",cost_per_kg:n.cost_per_kg??null,category:n.category||"",low_stock_threshold_pct:n.low_stock_threshold_pct??null,storage_location:n.storage_location||"",spoolman_filament_id:null}),pe(n.slicer_filament_name||n.slicer_filament||""),n.k_profiles&&n.k_profiles.length>0){const gt=new Set;for(const ct of n.k_profiles)ct.cali_idx!==null&&ct.cali_idx!==void 0&>.add(`${ct.printer_id}:${ct.cali_idx}:${ct.extruder??"null"}`);se(gt)}else se(new Set)}else w(YI),pe(""),se(new Set),_(!1),H(1);x({}),N("filament"),P(!1),A(!1)}},[t,n,a,f]),y.useEffect(()=>{t&&K.length>0&&G(new Set(K.map(Ke=>String(Ke.printer.id))))},[t,K]);const be=(Ke,gt)=>{const ct=zit.has(Ke);l&&ct&&g.spoolman_filament_id!==null&&m(d("inventory.spoolmanFilamentUnlinked"),"info"),w(at=>({...at,[Ke]:gt,...l&&ct&&at.spoolman_filament_id!==null?{spoolman_filament_id:null}:{}})),Ke==="weight_used"&&P(!0),Ke==="storage_location"&&A(!0),b[Ke]&&x(at=>({...at,[Ke]:void 0}))},Ee=Ke=>{const gt=Ke.material||"",ct=Ke.name||"",at=gt&&ct.startsWith(gt)?ct.slice(gt.length).trim():ct,Ot=(Ke.color_hex??"").replace("#","").toUpperCase(),Wt=/^[0-9A-F]{6}$/.test(Ot)?Ot:"808080";w(Zt=>({...Zt,spoolman_filament_id:Ke.id,material:gt,subtype:at,brand:Ke.vendor?.name||"",rgba:`${Wt}FF`,color_name:Ke.color_name||"",label_weight:Ke.weight??Zt.label_weight})),m(d("inventory.spoolmanFilamentSelected"),"success")},ze=Ke=>{j(gt=>Wce(Ke,gt))},Oe=it({mutationFn:Ke=>l?ie.createSpoolmanInventorySpool(Ke):ie.createSpool(Ke),onSuccess:async Ke=>{Ke?.id&&!await De(Ke.id)||(await u.invalidateQueries({queryKey:c}),o&&o([Ke]),m(d("inventory.spoolCreated"),"success"),e())},onError:Ke=>{Ke instanceof _i&&Ke.status===503?m(d("inventory.spoolmanUnreachable"),"error"):m(d("inventory.saveFailed"),"error")}}),Be=it({mutationFn:({data:Ke,qty:gt})=>l?ie.bulkCreateSpoolmanInventorySpools(Ke,gt):ie.bulkCreateSpools(Ke,gt),onSuccess:async Ke=>{const gt=l&&"created"in Ke?Ke:null,ct=gt?gt.created:Ke;if(O.size>0)for(const at of ct)await De(at.id);await u.invalidateQueries({queryKey:c}),o&&o(ct),gt&>.failed_count>0?m(d("inventory.spoolsPartiallyCreated",{created:ct.length,total:gt.requested_count}),"warning"):m(d("inventory.spoolsCreated",{count:ct.length}),"success"),e()},onError:Ke=>{Ke instanceof _i&&Ke.status===503?m(d("inventory.spoolmanUnreachable"),"error"):m(d("inventory.saveFailed"),"error")}}),Se=it({mutationFn:Ke=>l?ie.updateSpoolmanInventorySpool(n.id,Ke):ie.updateSpool(n.id,Ke),onSuccess:async()=>{n?.id&&!await De(n.id)||(await u.invalidateQueries({queryKey:c}),m(d("inventory.spoolUpdated"),"success"),e())},onError:Ke=>{Ke instanceof _i&&Ke.status===503?m(d("inventory.spoolmanUnreachable"),"error"):m(d("inventory.saveFailed"),"error")}}),$e=it({mutationFn:()=>l?ie.updateSpoolmanInventorySpool(n.id,xQ):ie.updateSpool(n.id,xQ),onSuccess:async()=>{await u.invalidateQueries({queryKey:c}),m(d("inventory.rfidCleared","RFID tag cleared"),"success"),e()},onError:Ke=>{Ke instanceof _i&&Ke.status===503?m(d("inventory.spoolmanUnreachable"),"error"):m(d("inventory.tagClearFailed"),"error")}}),{data:rt}=Ge({queryKey:["spool-assignments"],queryFn:()=>ie.getAssignments(),enabled:t&&p&&!l}),{data:ot}=Ge({queryKey:["spoolman-slot-assignments-all"],queryFn:()=>ie.getSpoolmanSlotAssignments(),enabled:t&&p&&l}),Le=(()=>{if(n)return l?ot?.find(Ke=>Ke.spoolman_spool_id===n.id):rt?.find(Ke=>Ke.spool_id===n.id)})(),{data:nt}=Ge({queryKey:["inventory-spools"],queryFn:()=>ie.getSpools(!0),enabled:t}),{data:Ne}=Ge({queryKey:["settings"],queryFn:ie.getSettings,enabled:t}),Qe=(()=>{const Ke=new Set;for(const gt of nt??[]){const ct=gt.category?.trim();ct&&Ke.add(ct)}return Array.from(Ke).sort((gt,ct)=>gt.localeCompare(ct))})(),Ue=Ne?.low_stock_threshold??20,ke=it({mutationFn:async()=>{if(!Le)throw new Error("No assignment");if(l){if(!n)throw new Error("No spool");await ie.unassignSpoolmanSlot(n.id);return}await ie.unassignSpool(Le.printer_id,Le.ams_id,Le.tray_id)},onSuccess:async()=>{l?(await u.invalidateQueries({queryKey:["spoolman-slot-assignments-all"]}),await u.invalidateQueries({queryKey:["spoolman-slot-assignments"]})):await u.invalidateQueries({queryKey:["spool-assignments"]}),m(d("inventory.unassignSuccess","Spool unassigned"),"success"),e()},onError:Ke=>{m(Ke.message,"error")}}),De=async Ke=>{const gt=l?ie.saveSpoolmanKProfiles:ie.saveSpoolKProfiles;if(O.size===0)try{return await gt(Ke,[]),!0}catch(Ot){return console.error("Failed to save K-profiles:",Ot),m(d("inventory.kProfileSaveFailed"),"warning"),!1}const ct=[];let at=0;for(const Ot of O){const[Wt,Zt,Yt]=Ot.split(":"),un=parseInt(Wt),bn=parseInt(Zt),dt=Yt==="null"?0:parseInt(Yt),st=K.find(vt=>vt.printer.id===un);if(st){const vt=st.calibrations.find(_t=>_t.cali_idx===bn);vt?ct.push({printer_id:un,extruder:dt,nozzle_diameter:vt.nozzle_diameter||"0.4",k_value:vt.k_value,name:vt.name||null,cali_idx:vt.cali_idx,setting_id:vt.setting_id||null}):at++}else at++}if(at>0)return console.error(`saveKProfiles: ${at} profile key(s) could not be resolved`,Array.from(O)),m(d("inventory.kProfileSaveFailed"),"warning"),!1;if(ct.length>0)try{return await gt(Ke,ct),!0}catch(Ot){return console.error("Failed to save K-profiles:",Ot),m(d("inventory.kProfileSaveFailed"),"warning"),!1}return!0};if(y.useEffect(()=>{if(!t)return;const Ke=gt=>{gt.key==="Escape"&&e()};return document.addEventListener("keydown",Ke),()=>document.removeEventListener("keydown",Ke)},[t,e]),!t)return null;const Ae=()=>{const Ke=zce(g,F,l);if(!Ke.isValid){x(Ke.errors),(Ke.errors.slicer_filament||Ke.errors.material||Ke.errors.brand||Ke.errors.subtype)&&N("filament");return}const gt=ye?.displayName||ce||null,ct={material:g.material||null,subtype:g.subtype||null,brand:g.brand||null,color_name:g.color_name||null,rgba:g.rgba||null,extra_colors:g.extra_colors||null,effect_type:g.effect_type||null,label_weight:g.label_weight,...l?{}:{core_weight:g.core_weight,core_weight_catalog_id:g.core_weight_catalog_id},slicer_filament:g.slicer_filament||null,slicer_filament_name:gt,nozzle_temp_min:null,nozzle_temp_max:null,note:g.note||null,cost_per_kg:g.cost_per_kg,category:g.category.trim()||null,low_stock_threshold_pct:g.low_stock_threshold_pct,...l?{spoolman_filament_id:g.spoolman_filament_id}:{}};(!p||C)&&(ct.weight_used=g.weight_used),(!p||T)&&(ct.storage_location=g.storage_location||null),p?Se.mutate(ct):E>1?Be.mutate({data:ct,qty:E}):Oe.mutate(ct)},Xe=Oe.isPending||Be.isPending||Se.isPending||$e.isPending||ke.isPending;return r.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[r.jsx("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-sm",onClick:e}),r.jsxs("div",{className:"relative w-full max-w-xl mx-4 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl max-h-[90vh] flex flex-col",children:[r.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary flex-shrink-0",children:[r.jsx("h2",{className:"text-lg font-semibold text-white",children:d(p?"inventory.editSpool":f?"inventory.copySpool":"inventory.addSpool")}),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"})})]}),a==="create"&&r.jsxs("div",{className:"flex items-center justify-between px-4 py-2 border-b border-bambu-dark-tertiary flex-shrink-0",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(Cc,{className:"w-4 h-4 text-amber-400"}),r.jsx("span",{className:"text-sm text-white",children:d("inventory.quickAdd")})]}),r.jsx("button",{type:"button",onClick:()=>{_(!F),F||N("filament")},className:`relative inline-flex h-5 w-9 items-center rounded-full transition-colors ${F?"bg-bambu-green":"bg-bambu-dark-tertiary"}`,children:r.jsx("span",{className:`inline-block h-3.5 w-3.5 rounded-full bg-white transition-transform ${F?"translate-x-4":"translate-x-0.5"}`})})]}),r.jsxs("div",{className:"flex border-b border-bambu-dark-tertiary flex-shrink-0",children:[r.jsxs("button",{onClick:()=>N("filament"),className:`flex-1 px-4 py-2.5 text-sm font-medium flex items-center justify-center gap-2 transition-colors ${S==="filament"?"text-bambu-green border-b-2 border-bambu-green":"text-bambu-gray hover:text-white"}`,children:[r.jsx(jS,{className:"w-4 h-4"}),d("inventory.filamentInfoTab")]}),!F&&r.jsxs("button",{onClick:()=>N("pa-profile"),className:`flex-1 px-4 py-2.5 text-sm font-medium flex items-center justify-center gap-2 transition-colors ${S==="pa-profile"?"text-bambu-green border-b-2 border-bambu-green":"text-bambu-gray hover:text-white"}`,children:[r.jsx(yfe,{className:"w-4 h-4"}),d("inventory.paProfileTab"),Z>0&&r.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded-full bg-bambu-green/20 text-bambu-green",children:Z})]})]}),r.jsx("div",{className:"p-4 overflow-y-auto flex-1",style:{scrollbarGutter:"stable"},children:S==="filament"?r.jsxs("div",{className:"space-y-6",children:[l&&!p&&r.jsx("div",{children:fe?r.jsx("p",{className:"text-sm text-red-400 px-1",children:d("inventory.spoolmanCatalogLoadFailed")}):r.jsx(Wit,{filaments:oe,isLoading:ee,selectedId:g.spoolman_filament_id,onSelect:Ee})}),r.jsxs("div",{children:[r.jsx("h3",{className:"text-sm font-semibold text-bambu-gray uppercase tracking-wide mb-3",children:d("inventory.filamentInfo")}),r.jsx(Kce,{formData:g,updateField:be,cloudAuthenticated:I,loadingCloudPresets:L,presetInputValue:ce,setPresetInputValue:pe,selectedPresetOption:ye,filamentOptions:de,availableBrands:ve,availableMaterials:Ce,quickAdd:F,quantity:E,onQuantityChange:H,errors:b})]}),r.jsxs("div",{children:[r.jsx("h3",{className:"text-sm font-semibold text-bambu-gray uppercase tracking-wide mb-3",children:d("inventory.color")}),r.jsx(Yce,{formData:g,updateField:be,recentColors:D,onColorUsed:ze,catalogColors:$})]}),r.jsxs("div",{children:[r.jsx("h3",{className:"text-sm font-semibold text-bambu-gray uppercase tracking-wide mb-3",children:d("inventory.additional")}),r.jsx(Xce,{formData:g,updateField:be,spoolCatalog:ue,currencySymbol:s,availableCategories:Qe,globalLowStockThreshold:Ue,spoolmanMode:l})]}),p&&n&&!l&&r.jsx("div",{children:r.jsx(Xit,{spoolId:n.id})})]}):r.jsx(Qce,{formData:g,updateField:be,printersWithCalibrations:K,selectedProfiles:O,setSelectedProfiles:se,expandedPrinters:z,setExpandedPrinters:G})}),r.jsxs("div",{className:"flex gap-2 p-4 border-t border-bambu-dark-tertiary flex-shrink-0",children:[p&&r.jsxs("div",{className:"flex gap-2 mr-auto",children:[r.jsxs(Me,{variant:"secondary",onClick:()=>$e.mutate(),disabled:Xe||!n?.tag_uid,children:[r.jsx($m,{className:"w-4 h-4"}),d("inventory.clearRfid","Clear RFID Tag")]}),r.jsxs(Me,{variant:"secondary",onClick:()=>ke.mutate(),disabled:Xe||!Le,children:[r.jsx(iu,{className:"w-4 h-4"}),d("inventory.unassignSpool","Unassign")]})]}),r.jsxs("div",{className:"flex gap-2 ml-auto",children:[r.jsx(Me,{variant:"secondary",onClick:e,children:d("common.cancel")}),r.jsx(Me,{onClick:Ae,disabled:Xe,children:Xe?r.jsxs(r.Fragment,{children:[r.jsx(pt,{className:"w-4 h-4 animate-spin"}),d("common.saving")]}):r.jsxs(r.Fragment,{children:[r.jsx(us,{className:"w-4 h-4"}),d(p?"common.save":f?"inventory.copySpool":"inventory.addSpool")]})})]})]})]})]})}function Zit({isOpen:t,onClose:e,columns:n,defaultColumns:a,onSave:i}){const{t:s}=kt(),[o,l]=y.useState(n),[c,d]=y.useState(null),u=y.useRef(null);if(y.useEffect(()=>{t&&l(n.map(C=>({...C})))},[t,n]),y.useEffect(()=>{if(!t)return;const C=P=>{P.key==="Escape"&&e()};return window.addEventListener("keydown",C),()=>window.removeEventListener("keydown",C)},[t,e]),!t)return null;const m=C=>{l(P=>P.map((T,A)=>A===C?{...T,visible:!T.visible}:T))},p=(C,P)=>{P<0||P>=o.length||l(T=>{const A=[...T],[F]=A.splice(C,1);return A.splice(P,0,F),A})},f=(C,P)=>{u.current=P,d(P),C.dataTransfer.effectAllowed="move"},g=(C,P)=>{C.preventDefault(),C.dataTransfer.dropEffect="move";const T=u.current;T!==null&&T!==P&&(p(T,P),u.current=P,d(P))},w=C=>{C.preventDefault()},b=()=>{u.current=null,d(null)},x=()=>{l(a.map(C=>({...C})))},S=()=>{i(o),e()},N=o.filter(C=>C.visible).length;return r.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",onClick:e,children:r.jsx(Ct,{className:"w-full max-w-md max-h-[80vh] flex flex-col",onClick:C=>C.stopPropagation(),children:r.jsxs(At,{className:"p-6 flex flex-col min-h-0",children:[r.jsx("h3",{className:"text-lg font-semibold text-white mb-2",children:s("inventory.configureColumns")}),r.jsxs("p",{className:"text-sm text-bambu-gray mb-4",children:[s("inventory.configureColumnsDesc"),r.jsxs("span",{className:"ml-2 text-bambu-gray/60",children:["(",N," ",s("inventory.of")," ",o.length," ",s("inventory.visible"),")"]})]}),r.jsx("div",{className:"space-y-1 overflow-y-auto flex-1 min-h-0 pr-1",children:o.map((C,P)=>r.jsxs("div",{className:`flex items-center gap-2 p-2 rounded-lg border transition-colors ${c===P?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary bg-bambu-dark-tertiary/50"} ${C.visible?"":"opacity-50"}`,draggable:!0,onDragStart:T=>f(T,P),onDragOver:T=>g(T,P),onDrop:w,onDragEnd:b,children:[r.jsx("div",{className:"cursor-grab text-bambu-gray/50 hover:text-bambu-gray",children:r.jsx(Ph,{className:"w-4 h-4"})}),r.jsx("span",{className:"flex-1 font-medium text-sm text-white",children:C.label}),r.jsxs("div",{className:"flex items-center gap-0.5",children:[r.jsx("button",{onClick:()=>p(P,P-1),disabled:P===0,className:"p-1 rounded text-bambu-gray hover:bg-bambu-dark-secondary disabled:opacity-30 disabled:cursor-not-allowed",title:s("inventory.moveUp"),children:r.jsx(tl,{className:"w-4 h-4"})}),r.jsx("button",{onClick:()=>p(P,P+1),disabled:P===o.length-1,className:"p-1 rounded text-bambu-gray hover:bg-bambu-dark-secondary disabled:opacity-30 disabled:cursor-not-allowed",title:s("inventory.moveDown"),children:r.jsx(Rn,{className:"w-4 h-4"})})]}),r.jsx("button",{onClick:()=>m(P),className:`p-1.5 rounded transition-colors ${C.visible?"text-bambu-green hover:bg-bambu-green/10":"text-bambu-gray/50 hover:bg-bambu-dark-secondary"}`,title:C.visible?s("inventory.hideColumn"):s("inventory.showColumn"),children:C.visible?r.jsx(Dl,{className:"w-4 h-4"}):r.jsx(sb,{className:"w-4 h-4"})})]},C.id))}),r.jsxs("div",{className:"flex items-center gap-3 mt-4 pt-4 border-t border-bambu-dark-tertiary",children:[r.jsxs(Me,{variant:"secondary",onClick:x,className:"mr-auto",children:[r.jsx(gs,{className:"w-4 h-4"}),s("inventory.reset")]}),r.jsx(Me,{variant:"secondary",onClick:e,children:s("inventory.cancel")}),r.jsx(Me,{onClick:S,children:s("inventory.applyChanges")})]})]})})})}const Jit=[{value:"ams_30x15",i18nKey:"ams",fallbackLabel:"AMS holder (30 × 15 mm)",fallbackHint:"Single label per page; fits the popular AMS filament label holder."},{value:"box_40x30",i18nKey:"box40x30",fallbackLabel:"Box label (40 × 30 mm)",fallbackHint:"Single label per page; common DK/Brother roll size, good for filament-bag and storage-bin labels."},{value:"box_62x29",i18nKey:"box",fallbackLabel:"Box label (62 × 29 mm)",fallbackHint:"Single label per page; sized for Brother PT/QL and Dymo small labels."},{value:"avery_l7160",i18nKey:"averyL7160",fallbackLabel:"Avery L7160 — A4 sheet (38.1 × 63.5 mm × 21)",fallbackHint:"EU sheet stock; 21 labels per A4 page."},{value:"avery_5160",i18nKey:"avery5160",fallbackLabel:"Avery 5160 — US Letter sheet (25.4 × 66.7 mm × 30)",fallbackHint:"US sheet stock; 30 labels per Letter page."}];function est(t){const e=window.URL.createObjectURL(t);if(!window.open(e,"_blank","noopener,noreferrer")){const a=document.createElement("a");a.href=e,a.download="bambuddy-labels.pdf",document.body.appendChild(a),a.click(),document.body.removeChild(a)}setTimeout(()=>window.URL.revokeObjectURL(e),6e4)}function tst(t){if(!t)return{backgroundColor:"#808080"};const e=t.replace(/^#/,"").slice(0,6);return e.length===6?{backgroundColor:`#${e}`}:{backgroundColor:"#808080"}}function nst(t){const e=t.color_name??`${t.material}${t.subtype?` ${t.subtype}`:""}`,n=t.brand?` · ${t.brand}`:"";return`${e}${n}`}function rst(t){return[t.color_name,t.material,t.subtype,t.brand,`#${t.id}`].filter(Boolean).join(" ").toLowerCase()}function ast({isOpen:t,onClose:e,availableSpools:n,initialSelectedIds:a,spoolmanMode:i}){const{t:s}=kt(),{showToast:o}=rn(),[l,c]=y.useState(null),[d,u]=y.useState(new Set),[m,p]=y.useState(""),[f,g]=y.useState("");y.useEffect(()=>{if(t){const E=new Set(n.map(H=>H.id));u(new Set(a.filter(H=>E.has(H)))),p(""),g(""),c(null)}},[t]);const w=y.useMemo(()=>[...n].sort((E,H)=>E.id-H.id),[n]),b=y.useMemo(()=>{const E=new Set;for(const H of w)H.material&&E.add(H.material.toUpperCase());return[...E].sort()},[w]),x=y.useMemo(()=>{const E=m.trim().toLowerCase();return w.filter(H=>!(f&&(H.material||"").toUpperCase()!==f||E&&!rst(H).includes(E)))},[w,m,f]),S=x.length>0&&x.every(E=>d.has(E.id));if(!t)return null;const N=d.size,C=N===0;function P(E){u(H=>{const I=new Set(H);return I.has(E)?I.delete(E):I.add(E),I})}function T(){u(E=>{const H=new Set(E);for(const I of x)H.add(I.id);return H})}function A(){u(E=>{const H=new Set(E);for(const I of x)H.delete(I.id);return H})}function F(){u(new Set)}async function _(E){if(C||l)return;const H=[...d].sort((I,U)=>I-U);c(E);try{const I=i?await ie.printSpoolmanSpoolLabels({spool_ids:H,template:E}):await ie.printSpoolLabels({spool_ids:H,template:E});est(I),e()}catch(I){const U=I instanceof Error?I.message:String(I);o(s("inventory.labels.error","Could not generate labels: {{msg}}",{msg:U}),"error")}finally{c(null)}}return r.jsxs("div",{className:"fixed inset-0 z-50 flex items-start sm:items-center justify-center p-4 overflow-y-auto",children:[r.jsx("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-sm",onClick:e}),r.jsxs("div",{className:"relative w-full max-w-3xl bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl max-h-[90vh] overflow-hidden flex flex-col my-auto",children:[r.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(pr,{className:"w-5 h-5 text-bambu-green"}),r.jsx("h2",{className:"text-lg font-semibold text-white",children:s("inventory.labels.title","Print spool labels")}),N>0&&r.jsxs("span",{className:"text-sm text-bambu-gray",children:["(",s("inventory.labels.selectedCount","{{count}} selected",{count:N}),")"]})]}),r.jsx("button",{onClick:e,className:"p-1 text-bambu-gray hover:text-white rounded transition-colors","aria-label":s("common.close","Close"),children:r.jsx(Ht,{className:"w-5 h-5"})})]}),r.jsxs("div",{className:"p-4 space-y-2 border-b border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"relative",children:[r.jsx(Sr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"}),r.jsx("input",{type:"search",value:m,onChange:E=>p(E.target.value),placeholder:s("inventory.labels.searchPlaceholder","Search name, brand, or #ID"),className:"w-full pl-9 pr-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray focus:outline-none focus:border-bambu-green"})]}),b.length>1&&r.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[r.jsx("span",{className:"text-xs text-bambu-gray mr-1",children:s("inventory.labels.filterByMaterial","Material:")}),r.jsx("button",{type:"button",onClick:()=>g(""),className:`px-2 py-0.5 text-xs rounded-full border transition ${f===""?"bg-bambu-green text-bambu-dark border-bambu-green":"bg-bambu-dark text-bambu-gray border-bambu-dark-tertiary hover:border-bambu-gray"}`,children:s("inventory.labels.allMaterials","All")}),b.map(E=>r.jsx("button",{type:"button",onClick:()=>g(E),className:`px-2 py-0.5 text-xs rounded-full border transition ${f===E?"bg-bambu-green text-bambu-dark border-bambu-green":"bg-bambu-dark text-bambu-gray border-bambu-dark-tertiary hover:border-bambu-gray"}`,children:E},E))]})]}),r.jsxs("div",{className:"px-4 pt-3 pb-2 flex items-center justify-between gap-3 flex-wrap",children:[r.jsx("span",{className:"text-sm text-bambu-gray",children:s("inventory.labels.pickSpools","Pick which spools to print labels for:")}),r.jsxs("div",{className:"flex items-center gap-3 text-xs",children:[r.jsx("button",{type:"button",onClick:S?A:T,disabled:x.length===0,className:"text-bambu-green hover:underline disabled:opacity-50 disabled:no-underline disabled:cursor-not-allowed",children:S?s("inventory.labels.deselectVisible","Deselect visible"):s("inventory.labels.selectVisible","Select all visible ({{count}})",{count:x.length})}),r.jsx("button",{type:"button",onClick:F,disabled:N===0,className:"text-bambu-gray hover:text-white hover:underline disabled:opacity-50 disabled:no-underline disabled:cursor-not-allowed",children:s("inventory.labels.clearAll","Clear all")})]})]}),r.jsx("div",{className:"flex-1 overflow-y-auto px-2 pb-2 min-h-0",children:x.length===0?r.jsx("div",{className:"text-center text-sm text-bambu-gray py-6",children:w.length===0?s("inventory.labels.noSpoolsToShow","No spools to show. Adjust your filter and try again."):s("inventory.labels.noMatches","No spools match the current search or filter.")}):r.jsx("ul",{className:"space-y-0.5",children:x.map(E=>{const H=d.has(E.id);return r.jsx("li",{children:r.jsxs("label",{className:"flex items-center gap-3 px-2 py-1.5 rounded hover:bg-bambu-dark-tertiary/50 cursor-pointer",children:[H?r.jsx(bs,{className:"w-4 h-4 text-bambu-green shrink-0"}):r.jsx(so,{className:"w-4 h-4 text-bambu-gray shrink-0"}),r.jsx("input",{type:"checkbox",checked:H,onChange:()=>P(E.id),className:"sr-only"}),r.jsx("span",{className:"w-4 h-4 rounded border border-black/20 shrink-0",style:tst(E.rgba)}),r.jsx("span",{className:"flex-1 min-w-0 truncate text-sm text-white",children:nst(E)}),r.jsxs("span",{className:"text-xs font-mono text-bambu-gray shrink-0",children:["#",E.id]})]})},E.id)})})}),r.jsx("div",{className:"px-3 pt-2 pb-2 grid grid-cols-1 sm:grid-cols-2 gap-2 border-t border-bambu-dark-tertiary",children:Jit.map(E=>{const H=l===E.value,I=s(`inventory.labels.templates.${E.i18nKey}.label`,E.fallbackLabel),U=s(`inventory.labels.templates.${E.i18nKey}.hint`,E.fallbackHint);return r.jsxs("button",{disabled:C||l!==null,onClick:()=>_(E.value),title:`${I} — ${U}`,className:"w-full text-left p-2.5 rounded-lg border border-bambu-dark-tertiary bg-bambu-dark hover:border-bambu-green hover:bg-bambu-green/10 disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:border-bambu-dark-tertiary disabled:hover:bg-bambu-dark transition flex items-center gap-3",children:[r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsx("div",{className:"font-medium text-white text-sm truncate",children:I}),r.jsx("div",{className:"text-xs text-bambu-gray mt-0.5 truncate",children:U})]}),H&&r.jsx(pt,{className:"w-4 h-4 animate-spin text-bambu-green shrink-0"})]},E.value)})}),r.jsx("div",{className:"flex justify-end gap-2 px-5 py-2 border-t border-bambu-dark-tertiary",children:r.jsx(Me,{variant:"secondary",onClick:e,disabled:l!==null,children:s("common.cancel","Cancel")})})]})]})}function yQ(t){return`${t.material}|${t.subtype||""}|${t.brand||""}|${t.color_name||""}|${t.rgba||""}|${t.extra_colors||""}|${t.effect_type||""}|${t.label_weight}`}const Zce="bambuddy-inventory-columns",HN=[{id:"id",label:"#",visible:!0},{id:"added_time",label:"Added",visible:!0},{id:"encode_time",label:"Encoded",visible:!1},{id:"last_used_time",label:"Last Used",visible:!1},{id:"rgba",label:"Color",visible:!0},{id:"material",label:"Material",visible:!0},{id:"subtype",label:"Subtype",visible:!0},{id:"color_name",label:"Color Name",visible:!1},{id:"brand",label:"Brand",visible:!0},{id:"slicer_filament",label:"Slicer Filament",visible:!1},{id:"location",label:"Location",visible:!0},{id:"storage_location",label:"Storage Location",visible:!1},{id:"label_weight",label:"Label",visible:!0},{id:"net",label:"Net",visible:!0},{id:"gross",label:"Gross",visible:!1},{id:"added_full",label:"Full",visible:!1},{id:"used",label:"Used",visible:!1},{id:"printed_total",label:"Printed Total",visible:!1},{id:"printed_since_weight",label:"Printed Since Weight",visible:!1},{id:"note",label:"Note",visible:!1},{id:"pa_k",label:"PA(K)",visible:!0},{id:"tag_id",label:"Tag ID",visible:!1},{id:"data_origin",label:"Data Origin",visible:!1},{id:"tag_type",label:"Linked Tag Type",visible:!1},{id:"stock",label:"Stock",visible:!1},{id:"remaining",label:"Remaining",visible:!0},{id:"spool_name",label:"Spool",visible:!1},{id:"cost_per_kg",label:"Cost/kg",visible:!1},{id:"weight_check",label:"Weight Check",visible:!1}];function ist(){try{const t=localStorage.getItem(Zce);if(t){const e=JSON.parse(t),n=new Set(HN.map(o=>o.id)),a=new Set(e.map(o=>o.id)),i=e.filter(o=>n.has(o.id)),s=HN.filter(o=>!a.has(o.id));return[...i,...s]}}catch{}return HN.map(t=>({...t}))}function sst(t){try{localStorage.setItem(Zce,JSON.stringify(t))}catch{}}function au(t,e=!1){return e&&t>=1e3?`${(t/1e3).toFixed(1)}kg`:`${Math.round(t)}g`}const ost={PLA:"bg-green-500/20 text-green-400",ABS:"bg-red-500/20 text-red-400",PETG:"bg-blue-500/20 text-blue-400",TPU:"bg-purple-500/20 text-purple-400",ASA:"bg-orange-500/20 text-orange-400",PA:"bg-yellow-500/20 text-yellow-400",PC:"bg-cyan-500/20 text-cyan-400",PET:"bg-sky-500/20 text-sky-400"};function gF(t,e="system"){if(!t)return"-";const n=Xn(t);return n?YF(n,e):"-"}const lst={id:()=>"#",added_time:()=>"Added",encode_time:()=>"Encoded",last_used_time:()=>"Last Used",rgba:t=>t("inventory.color"),material:t=>t("inventory.material"),subtype:t=>t("inventory.subtype"),color_name:t=>t("inventory.colorName"),brand:t=>t("inventory.brand"),slicer_filament:t=>t("inventory.slicerFilament"),location:()=>"Location",storage_location:t=>t("inventory.storageLocation"),label_weight:t=>t("inventory.labelWeight"),net:t=>t("inventory.net"),gross:()=>"Gross",added_full:()=>"Full",used:t=>t("inventory.weightUsed"),printed_total:()=>"Printed Total",printed_since_weight:()=>"Printed Since Weight",note:t=>t("inventory.note"),pa_k:()=>"PA(K)",tag_id:()=>"Tag ID",data_origin:()=>"Data Origin",tag_type:()=>"Linked Tag Type",stock:t=>t("inventory.stock"),remaining:t=>t("inventory.remaining"),spool_name:t=>t("inventory.spoolName"),cost_per_kg:t=>t("inventory.costPerKg"),weight_check:t=>t("inventory.weightCheck")},XI={id:({spool:t})=>r.jsx("span",{className:"text-sm font-medium text-white",children:t.id}),added_time:({spool:t,dateFormat:e})=>r.jsx("span",{className:"text-sm text-bambu-gray",children:gF(t.created_at,e)}),encode_time:({spool:t,dateFormat:e})=>r.jsx("span",{className:"text-sm text-bambu-gray",children:gF(t.encode_time,e)}),last_used_time:({spool:t,dateFormat:e})=>r.jsx("span",{className:"text-sm text-bambu-gray",children:t.last_used?gF(t.last_used,e):"Never"}),rgba:({spool:t})=>r.jsx("div",{className:"flex items-center justify-center",children:r.jsx(rU,{rgba:t.rgba,extraColors:t.extra_colors,effectType:t.effect_type,effectSize:"table",subtype:t.subtype})}),material:({spool:t})=>r.jsx("span",{className:"text-sm text-white",children:t.material}),subtype:({spool:t})=>r.jsx("span",{className:"text-sm text-bambu-gray",children:t.subtype||"-"}),color_name:({spool:t})=>r.jsx("span",{className:"text-sm text-bambu-gray",children:PT(t.color_name,t.rgba)||"-"}),brand:({spool:t})=>r.jsx("span",{className:"text-sm text-bambu-gray",children:t.brand||"-"}),slicer_filament:({spool:t})=>r.jsx("span",{className:"text-sm text-bambu-gray",title:t.slicer_filament||void 0,children:t.slicer_filament_name||t.slicer_filament||"-"}),location:({spool:t,assignmentMap:e})=>{const n=e[t.id];if(!n)return r.jsx("span",{className:"text-sm text-bambu-gray",children:"-"});const a=n.printer_name||`Printer ${n.printer_id}`,i=n.ams_id===254||n.ams_id===255,s=!i&&n.ams_id>=128,o=c_(n.ams_id,n.tray_id,s,i);return r.jsxs("span",{className:"inline-flex items-center px-1.5 py-0.5 rounded text-xs font-medium bg-purple-500/20 text-purple-400",children:[a," ",o,n.ams_label?` (${n.ams_label})`:""]})},storage_location:({spool:t})=>t.storage_location?r.jsx("span",{className:"inline-flex items-center px-1.5 py-0.5 rounded text-xs font-medium bg-blue-500/20 text-blue-400",children:t.storage_location}):r.jsx("span",{className:"text-sm text-bambu-gray",children:"-"}),label_weight:({spool:t})=>r.jsx("span",{className:"text-sm text-white",children:au(t.label_weight)}),net:({remaining:t})=>r.jsx("span",{className:"text-sm text-white",children:au(t)}),gross:({spool:t,remaining:e})=>r.jsx("span",{className:"text-sm text-bambu-gray",children:au(e+t.core_weight)}),added_full:({spool:t})=>r.jsx("span",{className:"text-sm text-bambu-gray",children:t.added_full==null?"-":t.added_full?"Yes":"No"}),used:({spool:t})=>r.jsx("span",{className:"text-sm text-bambu-gray",children:t.weight_used>0?au(t.weight_used):"-"}),printed_total:()=>r.jsx("span",{className:"text-sm text-bambu-gray/50",children:"-"}),printed_since_weight:()=>r.jsx("span",{className:"text-sm text-bambu-gray/50",children:"-"}),note:({spool:t})=>r.jsx("span",{className:"text-sm text-bambu-gray max-w-[150px] truncate block",title:t.note||void 0,children:t.note||"-"}),pa_k:({spool:t})=>(t.k_profiles?.length??0)===0?r.jsx("span",{className:"text-sm text-bambu-gray",children:"-"}):r.jsx("span",{className:"inline-flex items-center px-1.5 py-0.5 rounded text-xs font-medium bg-bambu-green/20 text-bambu-green",children:"K"}),tag_id:({spool:t})=>{const e=t.tag_uid||t.tray_uuid;return e?r.jsx("span",{className:"text-sm text-bambu-gray font-mono",title:e,children:e.length>12?`${e.slice(0,6)}...${e.slice(-4)}`:e}):r.jsx("span",{className:"text-sm text-bambu-gray/50",children:"-"})},data_origin:({spool:t})=>r.jsx("span",{className:"text-sm text-bambu-gray",children:t.data_origin||"-"}),tag_type:({spool:t})=>r.jsx("span",{className:"text-sm text-bambu-gray",children:t.tag_type||"-"}),stock:({spool:t,t:e})=>t.slicer_filament?r.jsx("span",{className:"text-sm text-bambu-gray",children:"-"}):r.jsx("span",{className:"inline-flex items-center px-1.5 py-0.5 rounded text-xs font-medium bg-amber-500/20 text-amber-400",children:e("inventory.stock")}),remaining:({remaining:t,pct:e})=>r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("div",{className:"flex-1 h-2 bg-bambu-dark-tertiary rounded-full overflow-hidden",children:r.jsx("div",{className:`h-full rounded-full ${e>50?"bg-bambu-green":e>20?"bg-yellow-500":"bg-red-500"}`,style:{width:`${Math.min(e,100)}%`}})}),r.jsxs("span",{className:"text-xs text-bambu-gray min-w-[40px] text-right",children:[Math.round(t),"g"]})]}),spool_name:({spool:t,catalogMap:e})=>{const n=t.core_weight_catalog_id!=null?e[t.core_weight_catalog_id]:void 0;return r.jsx("span",{className:"text-sm text-bambu-gray",children:n?.name||"-"})},cost_per_kg:({spool:t,currencySymbol:e})=>r.jsx("span",{className:"text-sm text-bambu-gray",children:t.cost_per_kg!=null?`${e}${t.cost_per_kg.toFixed(2)}`:"-"}),weight_check:({spool:t,onSyncWeight:e})=>{const n=t.last_scale_weight;if(n==null)return r.jsx("span",{className:"text-sm text-bambu-gray/50",title:"No scale measurement",children:"-"});const a=t.core_weight||0,i=Math.max(0,t.label_weight-t.weight_used)+a;let s,o;n0?`+${Math.round(s)}`:`${Math.round(s)}`,c=o?`Scale: ${Math.round(n)}g +`),N=new Blob([S],{type:"text/csv"}),C=URL.createObjectURL(N),P=document.createElement("a");P.href=C,P.download=`shopping-list-${new Date().toISOString().slice(0,10)}.csv`,P.click(),setTimeout(()=>URL.revokeObjectURL(C),100)}return r.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg overflow-hidden border border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"flex items-center justify-between px-4 py-3 border-b border-bambu-dark-tertiary bg-bambu-dark-tertiary/30",children:[r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx(lb,{className:"w-4 h-4 text-bambu-green"}),r.jsx("h3",{className:"text-sm font-semibold text-white",children:l("forecast.shoppingList")}),r.jsx("span",{className:"text-xs text-bambu-gray",children:l("forecast.shoppingListItems",{count:t.length})}),t.length>0&&r.jsxs("div",{className:"flex bg-bambu-dark-tertiary rounded-md p-0.5 ml-1",children:[r.jsxs("button",{onClick:()=>u("list"),className:`flex items-center gap-1.5 px-2 py-0.5 text-xs font-medium rounded transition-colors ${d==="list"?"bg-bambu-dark-secondary text-white shadow":"text-bambu-gray hover:text-white"}`,children:[r.jsx(Br,{className:"w-3 h-3"}),l("forecast.listView")]}),r.jsxs("button",{onClick:()=>u("logistics"),className:`flex items-center gap-1.5 px-2 py-0.5 text-xs font-medium rounded transition-colors ${d==="logistics"?"bg-bambu-dark-secondary text-white shadow":"text-bambu-gray hover:text-white"}`,children:[r.jsx(Hfe,{className:"w-3 h-3"}),l("forecast.logisticsView"),g.length>0&&r.jsx("span",{className:"w-3.5 h-3.5 rounded-full bg-red-500 text-white text-[9px] font-bold flex items-center justify-center",children:g.length})]})]})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[t.length>0&&r.jsxs(r.Fragment,{children:[r.jsxs("button",{onClick:w,className:"flex items-center gap-1.5 text-xs text-bambu-gray hover:text-white transition-colors px-2 py-1 rounded border border-bambu-dark-tertiary hover:bg-bambu-dark-tertiary",children:[r.jsx(Yr,{className:"w-3 h-3"}),l("forecast.downloadCsv")]}),a&&r.jsx("button",{onClick:o,className:"text-xs text-red-400 hover:text-red-300 transition-colors px-2 py-1 rounded border border-red-500/20 hover:bg-red-500/10",children:l("forecast.clearAll")})]}),r.jsx("button",{onClick:i,className:"p-1 text-bambu-gray hover:text-white transition-colors",children:r.jsx(Ht,{className:"w-4 h-4"})})]})]}),t.length===0?r.jsxs("div",{className:"flex flex-col items-center py-8 text-bambu-gray",children:[r.jsx(Br,{className:"w-8 h-8 mb-2 opacity-30"}),r.jsx("p",{className:"text-sm",children:l("forecast.shoppingListEmpty")})]}):d==="list"?r.jsx("div",{className:"overflow-x-auto",children:r.jsxs("table",{className:"w-full",children:[r.jsx("thead",{children:r.jsxs("tr",{className:"border-b border-bambu-dark-tertiary bg-bambu-dark-tertiary/20",children:[r.jsx("th",{className:"px-4 py-2 text-left text-xs font-medium text-bambu-gray uppercase tracking-wide",children:l("forecast.qty")}),r.jsx("th",{className:"px-4 py-2 text-left text-xs font-medium text-bambu-gray uppercase tracking-wide",children:l("forecast.material")}),r.jsx("th",{className:"px-4 py-2 text-left text-xs font-medium text-bambu-gray uppercase tracking-wide",children:l("forecast.weight")}),r.jsx("th",{className:"px-4 py-2 text-left text-xs font-medium text-bambu-gray uppercase tracking-wide",children:l("forecast.leadTime")}),r.jsx("th",{className:"px-4 py-2 text-left text-xs font-medium text-bambu-gray uppercase tracking-wide",children:l("forecast.expectedRestock")}),r.jsx("th",{className:"px-4 py-2 text-left text-xs font-medium text-bambu-gray uppercase tracking-wide",children:l("forecast.status")}),r.jsx("th",{className:"px-4 py-2 text-left text-xs font-medium text-bambu-gray uppercase tracking-wide",children:l("forecast.note")}),r.jsx("th",{className:"px-4 py-2 text-right text-xs font-medium text-bambu-gray uppercase tracking-wide",children:l("forecast.actions")})]})}),r.jsx("tbody",{className:"divide-y divide-bambu-dark-tertiary",children:t.map(b=>{const x=[b.brand,b.material,b.subtype].filter(Boolean).join(" "),S=g.some(H=>H.item.id===b.id),N=p.get(ww(b.material,b.subtype,b.brand))??null,C=N&&N.totalSpools>0?N.totalLabelG/N.totalSpools:1e3,P=Math.round(b.quantity_spools*C),T=N?.effectiveLeadTimeDays??n??0,A=T>0?Um(new Date,T):null,F=b.status==="purchased"||b.status==="received",_=b.status==="received",E=m.isPending;return r.jsxs("tr",{className:`hover:bg-bambu-dark-tertiary/30 transition-colors ${S&&!F?"bg-red-500/5":""}`,children:[r.jsx("td",{className:"px-4 py-2.5",children:r.jsxs("span",{className:"text-sm font-semibold text-bambu-green",children:[b.quantity_spools,"×"]})}),r.jsx("td",{className:"px-4 py-2.5",children:r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("span",{className:"text-sm text-white",children:x}),S&&!F&&r.jsx(Nn,{className:"w-3.5 h-3.5 text-red-400 flex-shrink-0","aria-label":l("forecast.stockBreakBefore")})]})}),r.jsx("td",{className:"px-4 py-2.5",children:r.jsx("span",{className:"text-sm text-white",children:P>=1e3?`${(P/1e3).toFixed(1)}kg`:`${P}g`})}),r.jsx("td",{className:"px-4 py-2.5",children:r.jsx("span",{className:"text-sm text-bambu-gray",children:T>0?`${T}d`:"—"})}),r.jsx("td",{className:"px-4 py-2.5",children:r.jsx("span",{className:"text-sm text-bambu-gray",children:A?wS(A):"—"})}),r.jsx("td",{className:"px-4 py-2.5",children:r.jsx("span",{className:`inline-flex items-center px-2 py-0.5 rounded text-xs font-medium ${_?"bg-bambu-green/20 text-bambu-green":F?"bg-blue-400/20 text-blue-400":"bg-bambu-dark-tertiary text-bambu-gray"}`,children:l(_?"forecast.received":F?"forecast.purchased":"forecast.pending")})}),r.jsx("td",{className:"px-4 py-2.5",children:r.jsx("span",{className:"text-xs text-bambu-gray",children:b.note||"—"})}),r.jsx("td",{className:"px-4 py-2.5",children:r.jsx("div",{className:"flex items-center justify-end gap-1",children:a&&r.jsxs(r.Fragment,{children:[r.jsx("button",{onClick:()=>m.mutate({id:b.id,status:F?"pending":"purchased"}),disabled:E||_,title:l(F?"forecast.resetToPending":"forecast.markPurchased"),className:`p-1 rounded transition-colors disabled:opacity-30 ${F?"text-blue-400 hover:text-bambu-gray":"text-bambu-gray hover:text-blue-400"}`,children:F?r.jsx(gs,{className:"w-3.5 h-3.5"}):r.jsx(Tge,{className:"w-3.5 h-3.5"})}),r.jsx("button",{onClick:()=>m.mutate({id:b.id,status:"received",item:b,avgSpoolG:C}),disabled:E||!F||_,title:l("forecast.markReceived"),className:"p-1 rounded transition-colors text-bambu-gray hover:text-bambu-green disabled:opacity-30",children:r.jsx(Mxe,{className:"w-3.5 h-3.5"})}),r.jsx("button",{onClick:()=>s(b.id),className:"p-1 text-bambu-gray hover:text-red-400 transition-colors",title:l("forecast.remove"),children:r.jsx(Jt,{className:"w-3.5 h-3.5"})})]})})})]},b.id)})})]})}):r.jsx("div",{className:"divide-y divide-bambu-dark-tertiary",children:f.filter(({item:b})=>b.status!=="received").map(({item:b,forecast:x})=>r.jsx(Iit,{item:b,forecast:x,globalLeadTime:n,canWrite:a,onRemove:()=>s(b.id)},b.id))})]})}function Iit({item:t,forecast:e,globalLeadTime:n,canWrite:a,onRemove:i}){const{t:s}=kt(),o=[t.brand,t.material,t.subtype].filter(Boolean).join(" "),l=y.useMemo(()=>{if(!e||e.dailyRateG===null||e.dailyRateG<=0)return null;const u=e.dailyRateG,m=e.effectiveLeadTimeDays,p=e.totalSpools>0?e.totalLabelG/e.totalSpools:1e3,f=t.quantity_spools*p,g=Math.max(0,e.totalRemainingG-u*m),w=g+f,b=Math.ceil(w/u),x=Math.min(m+b+5,365),S=[];for(let N=0;N<=x;N++){const C=Sw(Um(new Date,N));if(N===m)S.push({day:N,label:C,stock:Math.round(g),rop:Math.round(e.reorderPointG),safetyStock:Math.round(e.safetyStockG)}),S.push({day:N,label:C,stock:Math.round(w),rop:Math.round(e.reorderPointG),safetyStock:Math.round(e.safetyStockG),arrival:!0});else{const P=N{if(!e||e.dailyRateG===null||e.dailyRateG<=0)return null;const u=Math.floor(e.totalRemainingG/e.dailyRateG);return uu>=1e3?`${(u/1e3).toFixed(1)}kg`:`${u}g`,width:44}),r.jsx(nu,{contentStyle:{background:"#1a1a2e",border:"1px solid #374151",borderRadius:8,fontSize:11},labelStyle:{color:"#9CA3AF"},formatter:(u,m)=>typeof u!="number"?"":m==="stock"?`${u}g — ${s("forecast.stock")}`:m==="rop"?`${u}g — ${s("forecast.reorderPoint")}`:m==="safetyStock"?`${u}g — ${s("forecast.safetyMarginLabel")}`:`${u}`}),r.jsx(DA,{type:"linear",dataKey:"stock",stroke:"#1DB954",strokeWidth:2,fill:`url(#cart-post-${t.id})`,dot:!1,activeDot:{r:3}}),e.reorderPointG>0&&r.jsx(ru,{y:e.reorderPointG,stroke:"#F59E0B",strokeDasharray:"5 3",strokeOpacity:.8,label:{value:"ROP",position:"insideTopRight",fill:"#F59E0B",fontSize:9}}),e.safetyStockG>0&&r.jsx(ru,{y:e.safetyStockG,stroke:"#6B7280",strokeDasharray:"3 3",strokeOpacity:.6,label:{value:"SS",position:"insideTopRight",fill:"#6B7280",fontSize:9}}),r.jsx(ru,{x:Sw(Um(new Date,l.lt)),stroke:"#3B82F6",strokeWidth:1.5,strokeDasharray:"4 3",strokeOpacity:.9,label:{value:`+${l.arrivalG>=1e3?`${(l.arrivalG/1e3).toFixed(1)}kg`:`${Math.round(l.arrivalG)}g`} arrives (d${l.lt})`,position:"insideTopLeft",fill:"#3B82F6",fontSize:9}}),c!==null&&r.jsx(ru,{x:Sw(Um(new Date,c)),stroke:"#EF4444",strokeWidth:1.5,strokeOpacity:.9,label:{value:"OUT",position:"insideTopLeft",fill:"#EF4444",fontSize:9}})]})}),r.jsxs("div",{className:"flex flex-wrap items-center gap-3 mt-2 text-[10px] text-bambu-gray",children:[r.jsxs("span",{className:"flex items-center gap-1",children:[r.jsx("span",{className:"inline-block w-4 border-t-2 border-yellow-400 border-dashed"})," ",s("forecast.ropLabel")]}),r.jsxs("span",{className:"flex items-center gap-1",children:[r.jsx("span",{className:"inline-block w-4 border-t border-bambu-gray border-dashed"})," ",s("forecast.safetyStockLegend")]}),r.jsxs("span",{className:"flex items-center gap-1",children:[r.jsx("span",{className:"inline-block w-4 border-t-2 border-blue-400 border-dashed"})," ",s("forecast.stockArrivalLegend")]}),d&&r.jsxs("span",{className:"flex items-center gap-1 text-red-400",children:[r.jsx("span",{className:"inline-block w-4 border-t-2 border-red-400"})," ",s("forecast.stockoutLegend")]})]})]}):null]})}function Oit({forecast:t,onClose:e,onAdd:n}){const{t:a}=kt(),i=[t.group.brand,t.group.material,t.group.subtype].filter(Boolean).join(" "),[s,o]=y.useState("qty"),[l,c]=y.useState("1"),[d,u]=y.useState("30"),[m,p]=y.useState(""),f=y.useMemo(()=>{if(!t.dailyRateG||t.dailyRateG<=0)return null;const b=t.dailyRateG*Number(d),x=t.group.spools.length>0?t.group.spools.reduce((S,N)=>S+N.label_weight,0)/t.group.spools.length:1e3;return Math.ceil(b/x)},[t,d]),g=s==="qty"?parseInt(l,10)||1:f??1;function w(b){b.preventDefault(),n({material:t.group.material,subtype:t.group.subtype,brand:t.group.brand,quantity_spools:g,note:m||null})}return r.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm p-4",children:r.jsxs("div",{className:"bg-bambu-dark-secondary rounded-2xl border border-bambu-dark-tertiary w-full max-w-sm shadow-2xl",children:[r.jsxs("div",{className:"flex items-center justify-between px-5 pt-5 pb-4 border-b border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(lb,{className:"w-5 h-5 text-bambu-green"}),r.jsx("h2",{className:"text-base font-semibold text-white",children:a("forecast.addToCartTitle")})]}),r.jsx("button",{onClick:e,className:"p-1 text-bambu-gray hover:text-white transition-colors",children:r.jsx(Ht,{className:"w-5 h-5"})})]}),r.jsxs("form",{onSubmit:w,className:"p-5 space-y-4",children:[r.jsx("div",{className:"text-sm text-bambu-gray",children:i}),r.jsxs("div",{className:"flex bg-bambu-dark-tertiary rounded-lg p-0.5",children:[r.jsx("button",{type:"button",onClick:()=>o("qty"),className:`flex-1 py-1.5 text-xs font-medium rounded-md transition-colors ${s==="qty"?"bg-bambu-dark-secondary text-white shadow":"text-bambu-gray hover:text-white"}`,children:a("forecast.byQuantity")}),r.jsx("button",{type:"button",onClick:()=>o("duration"),className:`flex-1 py-1.5 text-xs font-medium rounded-md transition-colors ${s==="duration"?"bg-bambu-dark-secondary text-white shadow":"text-bambu-gray hover:text-white"}`,children:a("forecast.byDuration")})]}),s==="qty"?r.jsxs("div",{className:"space-y-1.5",children:[r.jsx("label",{className:"text-xs text-bambu-gray",children:a("forecast.numberOfSpools")}),r.jsx("input",{type:"number",min:1,max:99,value:l,onChange:b=>c(b.target.value),className:"w-full px-3 py-2 bg-bambu-dark-tertiary border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:outline-none focus:border-bambu-green",autoFocus:!0})]}):r.jsxs("div",{className:"space-y-2",children:[r.jsxs("div",{className:"space-y-1.5",children:[r.jsx("label",{className:"text-xs text-bambu-gray",children:a("forecast.lastHowManyDays")}),r.jsx("input",{type:"number",min:1,max:365,value:d,onChange:b=>u(b.target.value),className:"w-full px-3 py-2 bg-bambu-dark-tertiary border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:outline-none focus:border-bambu-green",autoFocus:!0})]}),t.dailyRateG!==null?r.jsxs("div",{className:"flex items-center gap-2 px-3 py-2 bg-bambu-dark-tertiary/50 rounded-lg",children:[r.jsx("span",{className:"text-xs text-bambu-gray",children:"≈"}),r.jsx("span",{className:"text-sm font-semibold text-bambu-green",children:a("forecast.spoolCount",{count:f??0})}),r.jsxs("span",{className:"text-xs text-bambu-gray",children:["at ",t.dailyRateG.toFixed(1),"g/day"]})]}):r.jsx("div",{className:"text-xs text-yellow-400 px-1",children:a("forecast.noUsageQty")})]}),r.jsxs("div",{className:"space-y-1.5",children:[r.jsx("label",{className:"text-xs text-bambu-gray",children:a("forecast.noteOptional")}),r.jsx("input",{type:"text",maxLength:200,value:m,onChange:b=>p(b.target.value),placeholder:a("forecast.notePlaceholder"),className:"w-full px-3 py-2 bg-bambu-dark-tertiary border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/40 focus:outline-none focus:border-bambu-green"})]}),r.jsxs("div",{className:"flex items-center gap-3 pt-1",children:[r.jsx("button",{type:"submit",className:"flex-1 py-2 bg-bambu-green text-white text-sm font-medium rounded-lg hover:bg-bambu-green/80 transition-colors",children:a("forecast.addNSpools",{count:g})}),r.jsx("button",{type:"button",onClick:e,className:"px-4 py-2 text-sm text-bambu-gray hover:text-white border border-bambu-dark-tertiary rounded-lg transition-colors",children:a("forecast.cancel")})]})]})]})})}const YI={material:"",subtype:"",brand:"",color_name:"",rgba:"808080FF",extra_colors:"",effect_type:"",label_weight:1e3,core_weight:250,core_weight_catalog_id:null,weight_used:0,slicer_filament:"",note:"",cost_per_kg:null,category:"",low_stock_threshold_pct:null,storage_location:"",spoolman_filament_id:null},zit=new Set(["material","subtype","brand","rgba","color_name","label_weight"]);function zce(t,e=!1,n=!1){const a={};return e||n?(!t.material&&!t.spoolman_filament_id&&(a.material="Material is required"),{isValid:Object.keys(a).length===0,errors:a}):(t.slicer_filament||(a.slicer_filament="Slicer preset is required"),t.material||(a.material="Material is required"),t.brand||(a.brand="Brand is required"),t.subtype||(a.subtype="Subtype is required"),{isValid:Object.keys(a).length===0,errors:a})}const Uce=["PLA","PETG","ABS","TPU","ASA","PC","PA","PVA","HIPS","PA-CF","PETG-CF","PLA-CF"],Uit=["Bambu","PolyLite","PolyTerra","eSUN","Overture","Fiberon","SUNLU","Inland","Hatchbox","Generic"],_w=["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"],Bce=[{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"}],Bit=[{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"}],bQ=[...Bce,...Bit],Hce="bambuddy-recent-colors",Hit=8,qit=[{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 Jh(t){let e=t.replace(/@.*$/,"").trim();e=e.replace(/\(Custom\)/i,"").trim(),e=e.replace(/^[#*]+\s*/,"").trim();const n=["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 a="",i=-1;for(const c of n){const d=e.toUpperCase().indexOf(c.toUpperCase());if(d!==-1){a=c,i=d;break}}let s="";i>0&&(s=e.substring(0,i).trim(),s=s.replace(/[-_\s]+$/,""));let o="";i!==-1&&a&&(o=e.substring(i+a.length).trim(),o=o.replace(/^[-_\s]+/,""));let l="";for(const c of _w)if(o.toLowerCase().includes(c.toLowerCase())){l=c;break}if(!l&&s)for(const c of _w){const d=new RegExp(`\\s+${c}$`,"i");if(d.test(s)){l=c,s=s.replace(d,"").trim();break}}return{brand:s,material:a,variant:l}}function qce(t,e){const n=new Set(Uit);for(const a of t){const{brand:i}=Jh(a.name);i&&i.length>1&&n.add(i)}if(e)for(const a of e)if(a.filament_vendor&&a.filament_vendor.length>1)n.add(a.filament_vendor);else{const{brand:i}=Jh(a.name);i&&i.length>1&&n.add(i)}return Array.from(n).sort((a,i)=>a.localeCompare(i))}function $it(t){const e=t.filter(a=>a.preset_type==="filament");return e.length===0?[]:e.map(a=>{const i=String(a.id),s=a.filament_type||i,o=Array.from(new Set([i,s]));return{code:i,name:a.name,displayName:a.name,isCustom:!1,allCodes:o}}).sort((a,i)=>a.displayName.localeCompare(i.displayName))}function $ce(t,e,n,a){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=n&&n.length>0?$it(n):[],c=[];if(a&&a.length>0)for(const u of a){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?qit:d.sort((u,m)=>u.displayName.localeCompare(m.displayName))}function Vce(t,e){if(!t)return;let n=e.find(a=>a.code===t);if(n||(n=e.find(a=>a.allCodes.includes(t))),!n){const a=t.toLowerCase();n=e.find(i=>i.code.toLowerCase()===a||i.allCodes.some(s=>s.toLowerCase()===a))}return n}function Gce(){try{const t=localStorage.getItem(Hce);if(t)return JSON.parse(t)}catch{}return[]}function Wce(t,e){const n=e.filter(i=>i.hex.toUpperCase()!==t.hex.toUpperCase()),a=[t,...n].slice(0,Hit);try{localStorage.setItem(Hce,JSON.stringify(a))}catch{}return a}function fF(t,e){if(!e.material)return!1;const a=(t.name||"").replace(/^High Flow[_\s]+/i,"").replace(/^Standard[_\s]+/i,"").replace(/^HF[_\s]+/i,"").replace(/^S[_\s]+/i,"").trim(),i=Jh(a);return!(!(i.material.toUpperCase()===e.material.toUpperCase())||e.brand&&!(i.brand.toLowerCase().includes(e.brand.toLowerCase())||e.brand.toLowerCase().includes(i.brand.toLowerCase()))||e.subtype&&!(i.variant.toLowerCase().includes(e.subtype.toLowerCase())||e.subtype.toLowerCase().includes(i.variant.toLowerCase())||a.toLowerCase().includes(e.subtype.toLowerCase())))}function Kce({formData:t,updateField:e,cloudAuthenticated:n,loadingCloudPresets:a,presetInputValue:i,setPresetInputValue:s,selectedPresetOption:o,filamentOptions:l,availableBrands:c,availableMaterials:d,quickAdd:u,quantity:m,onQuantityChange:p,errors:f}){const{t:g}=kt(),[w,b]=y.useState(!1),[x,S]=y.useState(!1),[N,C]=y.useState(!1),[P,T]=y.useState(!1),[A,F]=y.useState(""),[_,E]=y.useState(""),[H,I]=y.useState(""),[U,L]=y.useState(String(t.label_weight)),[Q,re]=y.useState(!1),J=y.useRef(null),ce=y.useRef(null),pe=y.useRef(null),ue=y.useRef(null);y.useEffect(()=>{const $=W=>{J.current&&!J.current.contains(W.target)&&b(!1),ue.current&&!ue.current.contains(W.target)&&T(!1),ce.current&&!ce.current.contains(W.target)&&S(!1),pe.current&&!pe.current.contains(W.target)&&C(!1)};return document.addEventListener("mousedown",$),()=>document.removeEventListener("mousedown",$)},[]);const X=y.useMemo(()=>{if(!i)return l;const $=i.toLowerCase();return l.filter(W=>W.displayName.toLowerCase().includes($)||W.code.toLowerCase().includes($))},[l,i]),ae=y.useMemo(()=>{if(!A)return c;const $=A.toLowerCase();return c.filter(D=>D.toLowerCase().includes($)).sort((D,j)=>{const B=D.toLowerCase()===$,Y=j.toLowerCase()===$;return B&&!Y?-1:!B&&Y?1:D.localeCompare(j)})},[c,A]),me=y.useMemo(()=>{if(!_)return _w;const $=_.toLowerCase();return _w.filter(W=>W.toLowerCase().includes($))},[_]),ge=y.useMemo(()=>{if(!H)return d;const $=H.toLowerCase();return d.filter(D=>D.toLowerCase().includes($)).sort((D,j)=>{const B=D.toLowerCase()===$,Y=j.toLowerCase()===$;return B&&!Y?-1:!B&&Y?1:D.localeCompare(j)})},[H,d]);y.useEffect(()=>{Q||L(String(t.label_weight))},[t.label_weight,Q]);const Pe=$=>{e("slicer_filament",$.code),s($.displayName),b(!1);const W=Jh($.name);W.material&&e("material",W.material),W.brand&&e("brand",W.brand),W.variant&&e("subtype",W.variant)};return r.jsxs("div",{className:"space-y-4",children:[!u&&r.jsx("div",{className:"flex items-center gap-2 text-xs text-bambu-gray",children:a?r.jsxs(r.Fragment,{children:[r.jsx(pt,{className:"w-3 h-3 animate-spin"})," ",g("inventory.loadingPresets")]}):n?r.jsxs(r.Fragment,{children:[r.jsx(Hh,{className:"w-3 h-3 text-bambu-green"})," ",g("inventory.cloudConnected")]}):r.jsxs(r.Fragment,{children:[r.jsx(UF,{className:"w-3 h-3"})," ",g("inventory.cloudNotConnected")]})}),!u&&r.jsxs("div",{children:[r.jsxs("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:[g("inventory.slicerPreset")," *"]}),r.jsxs("div",{className:"relative",ref:J,children:[r.jsx(Sr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50 pointer-events-none"}),r.jsx("input",{type:"text",className:"w-full pl-9 pr-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green",placeholder:g("inventory.searchPresets"),value:i,onChange:$=>{s($.target.value),b(!0)},onFocus:()=>{b(!0),s("")}}),w&&r.jsx("div",{className:"absolute z-50 w-full mt-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-lg max-h-64 overflow-y-auto",children:X.length===0?r.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:g("inventory.noPresetsFound")}):X.map($=>r.jsx("button",{type:"button",className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary truncate ${o?.code===$.code?"bg-bambu-green/10 text-bambu-green":"text-white"}`,onClick:()=>Pe($),children:$.displayName},`${$.code}::${$.name}`))})]}),o&&r.jsxs("div",{className:"mt-1 text-xs text-bambu-gray",children:[g("inventory.selectedPreset"),": ",r.jsx("span",{className:"font-mono text-bambu-green",children:o.code})]}),f?.slicer_filament&&r.jsx("p",{className:"mt-1 text-xs text-red-400",children:f.slicer_filament})]}),r.jsxs("div",{children:[r.jsxs("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:[g("inventory.material")," *"]}),r.jsxs("div",{className:"relative",ref:ue,children:[r.jsx("input",{type:"text",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green",placeholder:g("inventory.selectMaterial"),value:P?H:t.material,onChange:$=>{I($.target.value),T(!0)},onFocus:()=>{T(!0),I("")}}),r.jsx(Rn,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50 pointer-events-none"}),P&&r.jsxs("div",{className:"absolute z-50 w-full mt-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-lg max-h-48 overflow-y-auto",children:[ge.length===0?r.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:g("inventory.noResults")}):ge.map($=>r.jsx("button",{type:"button",className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary ${t.material===$?"bg-bambu-green/10 text-bambu-green":"text-white"}`,onClick:()=>{e("material",$),T(!1),I("")},children:$},$)),H&&!ge.includes(H)&&r.jsx("button",{type:"button",className:"w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary text-bambu-green border-t border-bambu-dark-tertiary",onClick:()=>{e("material",H),T(!1),I("")},children:g("inventory.useCustomMaterial",{material:H})})]})]}),f?.material&&r.jsx("p",{className:"mt-1 text-xs text-red-400",children:f.material})]}),r.jsxs("div",{children:[r.jsxs("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:[g("inventory.brand"),!u&&" *"]}),r.jsxs("div",{className:"relative",ref:ce,children:[r.jsx("input",{type:"text",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green",placeholder:g("inventory.searchBrand"),value:x?A:t.brand,onChange:$=>{F($.target.value),S(!0)},onFocus:()=>{S(!0),F("")}}),r.jsx(Rn,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50 pointer-events-none"}),x&&r.jsxs("div",{className:"absolute z-50 w-full mt-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-lg max-h-48 overflow-y-auto",children:[ae.length===0?r.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:g("inventory.noResults")}):ae.map($=>r.jsx("button",{type:"button",className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary ${t.brand===$?"bg-bambu-green/10 text-bambu-green":"text-white"}`,onClick:()=>{e("brand",$),S(!1),F("")},children:$},$)),A&&!ae.includes(A)&&r.jsx("button",{type:"button",className:"w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary text-bambu-green border-t border-bambu-dark-tertiary",onClick:()=>{e("brand",A),S(!1),F("")},children:g("inventory.useCustomBrand",{brand:A})})]})]}),f?.brand&&r.jsx("p",{className:"mt-1 text-xs text-red-400",children:f.brand})]}),r.jsxs("div",{children:[r.jsxs("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:[g("inventory.subtype"),!u&&" *"]}),r.jsxs("div",{className:"relative",ref:pe,children:[r.jsx("input",{type:"text",value:N?_:t.subtype,onChange:$=>{E($.target.value),C(!0)},onFocus:()=>{C(!0),E("")},placeholder:"Basic, Matte, Silk...",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green"}),r.jsx(Rn,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50 pointer-events-none"}),N&&r.jsxs("div",{className:"absolute z-50 w-full mt-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-lg max-h-48 overflow-y-auto",children:[me.length===0?r.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:g("inventory.noResults")}):me.map($=>r.jsx("button",{type:"button",className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary ${t.subtype===$?"bg-bambu-green/10 text-bambu-green":"text-white"}`,onClick:()=>{e("subtype",$),C(!1),E("")},children:$},$)),_&&!_w.some($=>$.toLowerCase()===_.toLowerCase().trim())&&r.jsx("button",{type:"button",className:"w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary text-bambu-green border-t border-bambu-dark-tertiary",onClick:()=>{e("subtype",_),C(!1),E("")},children:g("inventory.useCustomBrand",{brand:_})})]})]}),f?.subtype&&r.jsx("p",{className:"mt-1 text-xs text-red-400",children:f.subtype})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:g("inventory.labelWeight")}),r.jsxs("div",{className:"relative",children:[r.jsx("input",{type:"number",className:"w-full px-3 py-2 pr-7 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:outline-none focus:border-bambu-green",value:U,min:0,onFocus:()=>re(!0),onChange:$=>L($.target.value),onBlur:()=>{re(!1);const $=U.trim(),W=Number($);if(!$||!Number.isFinite(W)||W<0){L(String(t.label_weight));return}const D=Math.round(W);e("label_weight",D),L(String(D))}}),r.jsx("span",{className:"absolute right-2 top-1/2 -translate-y-1/2 text-xs text-bambu-gray",children:"g"})]})]}),u&&r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:g("inventory.quantity")}),r.jsx("input",{type:"number",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",value:m,min:1,max:100,onChange:$=>{const W=Math.max(1,Math.min(100,parseInt($.target.value)||1));p(W)}})]})]})}function Vit(t){const e=t.split(/[\s,]+/).map(i=>i.trim().replace(/^#/,"")).filter(Boolean),n=[],a=[];for(const i of e)(i.length===6||i.length===8)&&/^[0-9a-fA-F]+$/.test(i)?n.push(i.toLowerCase()):a.push(i);return{value:n.join(","),invalid:a}}function Yce({formData:t,updateField:e,recentColors:n,onColorUsed:a,catalogColors:i}){const{t:s}=kt(),[o,l]=y.useState(!1),[c,d]=y.useState(""),u=t.rgba.replace("#","").substring(0,6),m=F=>u.toUpperCase()===F.toUpperCase(),p=(F,_,E,H)=>{if(e("rgba",F.toUpperCase()+"FF"),e("color_name",_),E!==void 0){const I=E??"";S(I),C([]),P.current=I,e("extra_colors",I)}H!==void 0&&e("effect_type",H??""),a({name:_,hex:F})},f=y.useMemo(()=>{if(i.length===0)return[];const F=t.brand?.trim(),_=t.material?.toLowerCase().trim(),E=t.subtype?.toLowerCase().trim();if(!F&&!_)return[];const H=F?F.toLowerCase().split(/[\s\-_]+/).filter(L=>L.length>=2):[],I=L=>{if(H.length===0)return!0;const Q=L.toLowerCase();return H.some(re=>Q.includes(re))};if(F&&!_){const L=i.filter(Q=>I(Q.manufacturer));if(L.length>0)return L.map(Q=>({name:Q.color_name,hex:Q.hex_color.replace("#","").substring(0,6),manufacturer:Q.manufacturer,material:typeof Q.material=="string"?Q.material:void 0,extra_colors:Q.extra_colors??null,effect_type:Q.effect_type??null}))}const U=_&&E?`${_} ${E}`:"";if(U){const L=i.filter(re=>I(re.manufacturer)&&re.material?.toLowerCase()===U);if(L.length>0)return L.map(re=>({name:re.color_name,hex:re.hex_color.replace("#","").substring(0,6),manufacturer:re.manufacturer,material:typeof re.material=="string"?re.material:void 0,extra_colors:re.extra_colors??null,effect_type:re.effect_type??null}));const Q=U.replace(/\+$/,"");if(Q!==U){const re=i.filter(J=>I(J.manufacturer)&&J.material?.toLowerCase()===Q);if(re.length>0)return re.map(J=>({name:J.color_name,hex:J.hex_color.replace("#","").substring(0,6),manufacturer:J.manufacturer,material:typeof J.material=="string"?J.material:void 0}))}}if(_){const L=i.filter(Q=>I(Q.manufacturer)&&(!Q.material||Q.material.toLowerCase().startsWith(_)));if(L.length>0)return L.map(Q=>({name:Q.color_name,hex:Q.hex_color.replace("#","").substring(0,6),manufacturer:Q.manufacturer,material:typeof Q.material=="string"?Q.material:void 0,extra_colors:Q.extra_colors??null,effect_type:Q.effect_type??null}))}return[]},[i,t.brand,t.material,t.subtype]),g=y.useMemo(()=>{if(!c)return f;if(f.length===0)return[];const F=c.toLowerCase();return f.filter(E=>E.name.toLowerCase().includes(F)||(E.manufacturer?.toLowerCase().includes(F)??!1)||(E.material?.toLowerCase().includes(F)??!1))},[c,f]),w=f.length>0,b=y.useMemo(()=>c?bQ.filter(F=>F.name.toLowerCase().includes(c.toLowerCase())):o?bQ:Bce,[c,o]),[x,S]=y.useState(t.extra_colors),[N,C]=y.useState([]),P=y.useRef(t.extra_colors);y.useEffect(()=>{t.extra_colors!==P.current&&(S(t.extra_colors),C([]),P.current=t.extra_colors)},[t.extra_colors]);const T=y.useMemo(()=>rj({rgba:t.rgba,extraColors:t.extra_colors,effectType:t.effect_type,subtype:t.subtype,effectSize:"bar"}),[t.rgba,t.extra_colors,t.effect_type,t.subtype]),A=F=>{if(S(F),!F.trim()){C([]),P.current="",e("extra_colors","");return}const{value:_,invalid:E}=Vit(F);C(E),P.current=_,e("extra_colors",_)};return r.jsxs("div",{className:"space-y-3",children:[r.jsx("div",{className:"h-10 rounded-lg border border-bambu-dark-tertiary",style:T,"data-testid":"color-preview-banner"}),n.length>0&&r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-bambu-gray shrink-0",children:[r.jsx(Zn,{className:"w-3 h-3"}),r.jsx("span",{children:s("inventory.recentColors")})]}),r.jsx("div",{className:"flex flex-wrap gap-1.5",children:n.map(F=>r.jsx("button",{type:"button",onClick:()=>p(F.hex,F.name),className:`w-6 h-6 rounded border-2 transition-all hover:scale-110 ${m(F.hex)?"border-bambu-green ring-1 ring-bambu-green/30 scale-110":"border-bambu-dark-tertiary"}`,style:{backgroundColor:`#${F.hex}`},title:F.name},F.hex))})]}),r.jsxs("div",{className:"relative",children:[r.jsx(Sr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50 pointer-events-none"}),r.jsx("input",{type:"text",className:"w-full pl-9 pr-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green",placeholder:s("inventory.searchColors"),value:c,onChange:F=>d(F.target.value)})]}),w?r.jsxs("div",{className:"space-y-1.5",children:[r.jsx("span",{className:"text-xs text-bambu-gray",children:c?s("inventory.searchResults"):`${t.brand}${t.material?` ${t.material}`:""}`}),r.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[g.map(F=>r.jsx("button",{type:"button",onClick:()=>p(F.hex,F.name,F.extra_colors,F.effect_type),className:`w-6 h-6 rounded border-2 transition-all hover:scale-110 hover:z-20 relative group ${m(F.hex)?"border-bambu-green ring-1 ring-bambu-green/30 scale-110":"border-bambu-dark-tertiary"}`,style:{backgroundColor:`#${F.hex}`},title:F.manufacturer&&F.material?`${F.name} (${F.manufacturer} — ${F.material})`:F.manufacturer?`${F.name} (${F.manufacturer})`:F.name,children:r.jsx("span",{className:"absolute -bottom-7 left-1/2 -translate-x-1/2 px-2 py-0.5 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-xs whitespace-nowrap opacity-0 group-hover:opacity-100 transition-opacity pointer-events-none z-20 shadow-lg text-white",children:F.manufacturer&&F.material?`${F.name} (${F.manufacturer} — ${F.material})`:F.manufacturer?`${F.name} (${F.manufacturer})`:F.name})},`${F.hex}-${F.name}-${F.manufacturer??""}`)),g.length===0&&r.jsx("p",{className:"text-sm text-bambu-gray py-1",children:s("inventory.noColorsFound")})]})]}):r.jsxs("div",{className:"space-y-1.5",children:[r.jsxs("div",{className:"flex items-center justify-between text-xs text-bambu-gray",children:[r.jsx("span",{children:s(c?"inventory.searchResults":o?"inventory.allColors":"inventory.commonColors")}),!c&&r.jsx("button",{type:"button",onClick:()=>l(!o),className:"flex items-center gap-1 hover:text-white transition-colors",children:o?r.jsxs(r.Fragment,{children:[s("inventory.showLess")," ",r.jsx(tl,{className:"w-3 h-3"})]}):r.jsxs(r.Fragment,{children:[s("inventory.showAll")," ",r.jsx(Rn,{className:"w-3 h-3"})]})})]}),r.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[b.map(F=>r.jsx("button",{type:"button",onClick:()=>p(F.hex,F.name),className:`w-6 h-6 rounded border-2 transition-all hover:scale-110 hover:z-20 relative group ${m(F.hex)?"border-bambu-green ring-1 ring-bambu-green/30 scale-110":"border-bambu-dark-tertiary"}`,style:{backgroundColor:`#${F.hex}`},title:F.name,children:r.jsx("span",{className:"absolute -bottom-7 left-1/2 -translate-x-1/2 px-2 py-0.5 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-xs whitespace-nowrap opacity-0 group-hover:opacity-100 transition-opacity pointer-events-none z-20 shadow-lg text-white",children:F.name})},F.hex)),b.length===0&&r.jsx("p",{className:"text-sm text-bambu-gray py-1",children:s("inventory.noColorsFound")})]})]}),r.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:s("inventory.colorName")}),r.jsx("input",{type:"text",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green",placeholder:s("inventory.colorNamePlaceholder"),value:t.color_name,onChange:F=>e("color_name",F.target.value)})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:s("inventory.hexColor")}),r.jsxs("div",{className:"flex gap-2",children:[r.jsxs("div",{className:"relative flex-1",children:[r.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-bambu-gray",children:"#"}),r.jsx("input",{type:"text",className:"w-full pl-7 pr-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm font-mono uppercase focus:outline-none focus:border-bambu-green",placeholder:"RRGGBB",value:u.toUpperCase(),onChange:F=>{const _=F.target.value.replace("#","").replace(/[^0-9A-Fa-f]/g,"").toUpperCase();if(_.length>8)return;const E=_.length===8?_:_.length===7?_.substring(0,6)+"FF":_.padEnd(6,"0")+"FF";e("rgba",E)}})]}),r.jsx("input",{type:"color",className:"w-11 h-[38px] rounded-lg cursor-pointer border border-bambu-dark-tertiary shrink-0 bg-transparent",value:`#${u}`,onChange:F=>{const _=F.target.value.replace("#","").toUpperCase();e("rgba",_+"FF")},title:s("inventory.pickColor")})]})]})]}),r.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3 pt-2 border-t border-bambu-dark-tertiary/50",children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:s("inventory.extraColorsLabel")}),r.jsx("input",{type:"text",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm font-mono placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green",placeholder:s("inventory.extraColorsPlaceholder"),value:x,onChange:F=>A(F.target.value),"data-testid":"extra-colors-input"}),N.length>0&&r.jsx("p",{className:"text-xs text-red-400 mt-1",children:s("inventory.extraColorsInvalid",{tokens:N.join(", ")})}),!N.length&&r.jsx("p",{className:"text-xs text-bambu-gray/70 mt-1",children:s("inventory.extraColorsHint")})]}),r.jsxs("div",{children:[r.jsxs("label",{className:"block text-sm font-medium text-bambu-gray mb-1 flex items-center gap-1.5",children:[r.jsx(Dg,{className:"w-3.5 h-3.5"}),s("inventory.colorEffectLabel")]}),r.jsxs("div",{className:"flex gap-2 items-stretch",children:[r.jsx("select",{className:"flex-1 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",value:t.effect_type,onChange:F=>e("effect_type",F.target.value),"data-testid":"effect-type-select",children:WI.map(F=>r.jsx("option",{value:F.value,children:s(F.labelKey)},F.value||"none"))}),r.jsx(rU,{rgba:t.rgba,extraColors:t.extra_colors,effectType:t.effect_type,subtype:t.subtype,effectSize:"preview",className:"w-10 h-10",shape:"square"})]})]})]})]})}function Git({catalog:t,value:e,onChange:n,catalogId:a,onCatalogIdChange:i}){const{t:s}=kt(),[o,l]=y.useState(!1),[c,d]=y.useState(""),u=y.useRef(null),m=y.useRef(null);y.useEffect(()=>{const w=b=>{u.current&&!u.current.contains(b.target)&&l(!1)};return document.addEventListener("mousedown",w),()=>document.removeEventListener("mousedown",w)},[]),y.useEffect(()=>{if(t.length===0)return;const w=t.filter(b=>b.weight===e);if(a){const b=t.find(x=>x.id===a);if(b&&b.weight===e)return}w.length===1?i(w[0].id):w.length===0&&a!==null&&i(null)},[e,t,a,i]);const p=y.useMemo(()=>{if(!c)return t;const w=c.toLowerCase();return t.filter(b=>b.name.toLowerCase().includes(w)||b.weight.toString().includes(w))},[t,c]),f=y.useMemo(()=>t.filter(w=>w.weight===e),[t,e]),g=y.useMemo(()=>{if(o)return c;if(a){const w=t.find(b=>b.id===a);if(w)return w.name}return f.length>0?f[0].name:""},[o,c,a,t,f]);return r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:r.jsxs("span",{className:"flex items-center gap-2",children:[r.jsx(FZ,{className:"w-3.5 h-3.5 text-bambu-gray"}),s("inventory.coreWeight")]})}),r.jsxs("div",{className:"flex gap-2 items-center",children:[r.jsxs("div",{className:"flex-1 min-w-0 relative",ref:u,children:[r.jsx("input",{ref:m,type:"text",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green",placeholder:s("inventory.searchSpoolWeight"),value:g,onFocus:()=>{l(!0),d("")},onChange:w=>{d(w.target.value),l(!0)}}),o&&r.jsx("div",{className:"absolute z-50 w-full mt-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-lg max-h-64 overflow-y-auto",children:p.length===0?r.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:s("inventory.noResults")}):p.map(w=>r.jsxs("button",{type:"button",className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex justify-between items-center ${(a?w.id===a:w.weight===e)?"bg-bambu-green/10 text-bambu-green":"text-white"}`,onClick:()=>{i(w.id),n(w.weight),l(!1),d("")},children:[r.jsx("span",{className:"truncate",children:w.name}),r.jsxs("span",{className:"font-mono text-xs text-bambu-gray ml-2 shrink-0",children:[w.weight,"g"]})]},w.id))})]}),r.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[r.jsx("input",{type:"number",className:"w-16 px-2 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm text-center font-mono focus:outline-none focus:border-bambu-green",value:e,min:0,max:2e3,onChange:w=>{const b=parseInt(w.target.value);!isNaN(b)&&b>=0&&n(b)}}),r.jsx("span",{className:"text-bambu-gray text-sm",children:"g"})]})]})]})}function Xce({formData:t,updateField:e,spoolCatalog:n,currencySymbol:a,availableCategories:i,globalLowStockThreshold:s,spoolmanMode:o=!1}){const{t:l}=kt(),{showToast:c}=rn(),[d,u]=y.useState(""),[m,p]=y.useState(!1),[f,g]=y.useState(""),[w,b]=y.useState(!1),x=Math.max(0,t.label_weight-t.weight_used),S=t.core_weight+x;return y.useEffect(()=>{m||u(String(S))},[m,S]),y.useEffect(()=>{w||g(String(x))},[w,x]),r.jsxs("div",{className:"space-y-4",children:[o?r.jsx("p",{className:"text-xs text-bambu-gray px-1",children:l("inventory.spoolWeightManagedBySpoolman")}):r.jsx(Git,{catalog:n,value:t.core_weight,onChange:N=>e("core_weight",N),catalogId:t.core_weight_catalog_id,onCatalogIdChange:N=>e("core_weight_catalog_id",N)}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:l("inventory.currentWeight")}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsxs("div",{className:"relative flex-1",children:[r.jsx("input",{type:"number",value:f,min:0,max:t.label_weight,onFocus:()=>b(!0),onChange:N=>{g(N.target.value)},onBlur:()=>{b(!1);const N=f.trim(),C=Number(N);if(!N||!Number.isFinite(C)||C<0||C>t.label_weight){g(String(x));return}const P=Math.round(C);e("weight_used",Math.max(0,t.label_weight-P)),g(String(P))},className:"w-full px-3 py-2 pr-7 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:outline-none focus:border-bambu-green"}),r.jsx("span",{className:"absolute right-2 top-1/2 -translate-y-1/2 text-xs text-bambu-gray",children:"g"})]}),r.jsxs("span",{className:"text-xs text-bambu-gray shrink-0",children:["/ ",t.label_weight,"g"]})]})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:l("inventory.measuredWeight")}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsxs("div",{className:"relative flex-1",children:[r.jsx("input",{type:"number",value:d,min:0,onFocus:()=>p(!0),onChange:N=>{u(N.target.value)},onBlur:()=>{p(!1);const N=d.trim(),C=Number(N),P=t.core_weight,T=t.core_weight+t.label_weight;if(!N||!Number.isFinite(C)||CT){c(l("inventory.measuredWeightError",{min:P,max:T}),"error"),u(String(S));return}const A=Math.round(C),F=Math.max(0,Math.min(t.label_weight,A-t.core_weight));e("weight_used",Math.max(0,t.label_weight-F)),u(String(A))},className:"w-full px-3 py-2 pr-7 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:outline-none focus:border-bambu-green"}),r.jsx("span",{className:"absolute right-2 top-1/2 -translate-y-1/2 text-xs text-bambu-gray",children:"g"})]}),r.jsxs("span",{className:"text-xs text-bambu-gray shrink-0",children:["/ ",t.core_weight+t.label_weight,"g"]})]})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:l("inventory.costPerKg","Cost per kg")}),r.jsx("div",{className:"flex items-center gap-2",children:r.jsxs("div",{className:"relative flex-1",children:[r.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-bambu-gray text-sm pointer-events-none",children:a}),r.jsx("input",{type:"number",value:t.cost_per_kg??"",min:0,step:.01,placeholder:"0.00",onChange:N=>{const C=N.target.value===""?null:parseFloat(N.target.value);e("cost_per_kg",C)},style:{paddingLeft:`${Math.max(2,a.length*.6+1)}rem`},className:"w-full py-2 pr-3 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:outline-none focus:border-bambu-green"})]})})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",htmlFor:"spool-category",children:l("inventory.category")}),r.jsx("input",{id:"spool-category",type:"text",list:"spool-category-options",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green",placeholder:l("inventory.categoryPlaceholder"),value:t.category,maxLength:50,onChange:N=>e("category",N.target.value)}),i.length>0&&r.jsx("datalist",{id:"spool-category-options",children:i.map(N=>r.jsx("option",{value:N},N))})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",htmlFor:"spool-low-stock-threshold",children:l("inventory.lowStockThresholdOverride")}),r.jsx("div",{className:"flex items-center gap-2",children:r.jsxs("div",{className:"relative flex-1",children:[r.jsx("input",{id:"spool-low-stock-threshold",type:"number",className:"w-full px-3 py-2 pr-8 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green",placeholder:String(s),value:t.low_stock_threshold_pct??"",min:1,max:99,step:1,onChange:N=>{const C=N.target.value;if(C===""){e("low_stock_threshold_pct",null);return}const P=Number(C);Number.isFinite(P)&&e("low_stock_threshold_pct",Math.min(99,Math.max(1,Math.round(P))))}}),r.jsx("span",{className:"absolute right-3 top-1/2 -translate-y-1/2 text-xs text-bambu-gray pointer-events-none",children:"%"})]})}),r.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:l("inventory.lowStockThresholdOverrideHelp",{global:s})})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:l("inventory.note")}),r.jsx("textarea",{className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green resize-none min-h-[80px]",placeholder:l("inventory.notePlaceholder"),value:t.note,onChange:N=>e("note",N.target.value)})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:l("inventory.storageLocation")}),r.jsx("input",{type:"text",maxLength:255,className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green",placeholder:l("inventory.storageLocationPlaceholder"),value:t.storage_location,onChange:N=>e("storage_location",N.target.value)})]})]})}function Wit({filaments:t,isLoading:e,selectedId:n,onSelect:a}){const{t:i}=kt(),[s,o]=y.useState(!1),[l,c]=y.useState(""),d=y.useRef(null),u=y.useRef(null),m=y.useMemo(()=>t.find(b=>b.id===n)??null,[t,n]);y.useEffect(()=>{const b=x=>{d.current&&!d.current.contains(x.target)&&(o(!1),c(""))};return document.addEventListener("mousedown",b),()=>document.removeEventListener("mousedown",b)},[]);const p=y.useMemo(()=>{const b=l.toLowerCase().trim();return b?t.filter(x=>x.name.toLowerCase().includes(b)||(x.material?.toLowerCase().includes(b)??!1)||(x.vendor?.name.toLowerCase().includes(b)??!1)||(x.color_name?.toLowerCase().includes(b)??!1)):t},[t,l]);y.useEffect(()=>{s&&u.current?.focus()},[s]);const f=()=>{o(!0),c("")},g=b=>{a(b),o(!1),c("")},w=b=>b?`#${b.replace("#","")}`:"#808080";return r.jsxs("div",{ref:d,className:"relative",children:[r.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:i("inventory.pickFromSpoolmanCatalog")}),r.jsxs("button",{type:"button",onClick:f,className:"w-full flex items-center gap-2 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-left focus:outline-none focus:border-bambu-green hover:border-bambu-gray transition-colors",children:[e?r.jsx(pt,{className:"w-4 h-4 text-bambu-gray animate-spin shrink-0"}):m?r.jsxs(r.Fragment,{children:[r.jsx("span",{className:"w-4 h-4 rounded-full shrink-0 border border-white/20",style:{backgroundColor:w(m.color_hex)},"aria-label":i("inventory.spoolmanFilamentColorSwatch")}),r.jsxs("span",{className:"text-white text-sm truncate flex-1",children:[m.vendor?.name?`${m.vendor.name} — `:"",m.name]})]}):r.jsxs(r.Fragment,{children:[r.jsx(Br,{className:"w-4 h-4 text-bambu-gray shrink-0"}),r.jsx("span",{className:"text-bambu-gray text-sm flex-1",children:i("inventory.spoolmanFilamentCatalog")})]}),r.jsx(Rn,{className:"w-4 h-4 text-bambu-gray shrink-0 ml-auto"})]}),s&&r.jsxs("div",{className:"absolute z-50 w-full mt-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl",children:[r.jsx("div",{className:"p-2 border-b border-bambu-dark-tertiary",children:r.jsx("input",{ref:u,type:"text",value:l,onChange:b=>c(b.target.value),placeholder:i("inventory.pickFromSpoolmanCatalog"),className:"w-full px-2 py-1.5 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-sm placeholder-bambu-gray focus:outline-none focus:border-bambu-green"})}),r.jsx("ul",{className:"max-h-56 overflow-y-auto py-1",children:e?r.jsxs("li",{className:"flex items-center justify-center gap-2 py-4 text-bambu-gray text-sm",children:[r.jsx(pt,{className:"w-4 h-4 animate-spin"}),r.jsx("span",{children:i("common.loading","Loading…")})]}):p.length===0?r.jsx("li",{className:"py-4 text-center text-bambu-gray text-sm",children:i("inventory.noSpoolmanFilaments")}):p.map(b=>r.jsx("li",{children:r.jsxs("button",{type:"button",onClick:()=>g(b),className:`w-full flex items-center gap-2 px-3 py-2 text-left hover:bg-bambu-dark-tertiary transition-colors ${b.id===n?"bg-bambu-dark-tertiary":""}`,children:[r.jsx("span",{className:"w-4 h-4 rounded-full shrink-0 border border-white/20",style:{backgroundColor:w(b.color_hex)},"aria-label":i("inventory.spoolmanFilamentColorSwatch")}),r.jsxs("span",{className:"flex-1 min-w-0",children:[r.jsxs("span",{className:"block text-white text-sm truncate",children:[b.vendor?.name?`${b.vendor.name} — `:"",b.name]}),r.jsxs("span",{className:"block text-bambu-gray text-xs truncate",children:[[b.material,b.color_name].filter(Boolean).join(" · "),b.weight?` · ${b.weight}g`:""]})]})]})},b.id))})]})]})}function Qce({formData:t,printersWithCalibrations:e,selectedProfiles:n,setSelectedProfiles:a,expandedPrinters:i,setExpandedPrinters:s}){const{t:o}=kt(),l=p=>{s(f=>{const g=new Set(f);return g.has(p)?g.delete(p):g.add(p),g})},c=(p,f,g)=>{const w=`${p}:${f}:${g??"null"}`,b=`${p}:${g??"null"}`;a(x=>{const S=new Set(x);if(S.has(w))S.delete(w);else{for(const N of Array.from(S)){const C=N.split(":");`${C[0]}:${C[2]}`===b&&S.delete(N)}S.add(w)}return S})},d=()=>{const p=new Set;for(const{printer:f,calibrations:g}of e){if(!f.connected)continue;const w=g.filter(x=>fF(x,t)),b=new Map;for(const x of w){const S=`${x.extruder_id??"null"}`;b.has(S)||b.set(S,[]),b.get(S).push(x)}for(const[x,S]of b)if(S.length>0){const C=[...S].sort((P,T)=>T.k_value-P.k_value)[0];p.add(`${f.id}:${C.cali_idx}:${x}`)}}a(p)};if(!t.material)return r.jsx("div",{className:"p-6 bg-bambu-dark rounded-lg text-center",children:r.jsx("p",{className:"text-bambu-gray",children:o("inventory.selectMaterialFirst")})});if(e.length===0)return r.jsx("div",{className:"p-6 bg-bambu-dark rounded-lg text-center",children:r.jsx("p",{className:"text-bambu-gray",children:o("inventory.noPrintersConfigured")})});const u=e.reduce((p,{printer:f,calibrations:g})=>f.connected?p+g.filter(w=>fF(w,t)).length:p,0),m=(p,f)=>{const g=`${p.id}:${f.cali_idx}:${f.extruder_id??"null"}`,w=n.has(g);return r.jsxs("label",{className:`flex items-center gap-3 p-3 rounded-lg cursor-pointer transition-all border ${w?"bg-bambu-green/10 border-bambu-green/30":"bg-bambu-dark border-transparent hover:bg-bambu-dark/80"}`,children:[r.jsx("input",{type:"checkbox",checked:w,onChange:()=>c(String(p.id),f.cali_idx,f.extruder_id),className:"w-4 h-4 rounded border-bambu-dark-tertiary text-bambu-green focus:ring-bambu-green"}),r.jsx("div",{className:"flex-1 min-w-0",children:r.jsx("span",{className:`text-sm font-medium ${w?"text-bambu-green":"text-white"}`,children:f.name||f.filament_id})}),r.jsx("div",{className:"flex items-center gap-2 shrink-0",children:r.jsxs("span",{className:"text-xs font-mono px-2 py-0.5 rounded bg-bambu-dark text-bambu-gray",children:["K=",f.k_value.toFixed(3)]})})]},`${f.cali_idx}-${f.extruder_id}`)};return r.jsxs("div",{className:"space-y-4",children:[r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("p",{className:"text-xs text-bambu-gray",children:[o("inventory.matchingFilter"),": ",t.brand||o("inventory.anyBrand")," / ",t.material," / ",t.subtype||o("inventory.anyVariant")]}),u>0&&r.jsxs("button",{type:"button",onClick:d,className:"flex items-center gap-1.5 px-2 py-1 text-xs bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-bambu-gray hover:text-white hover:border-bambu-green transition-colors",children:[r.jsx(Dg,{className:"w-3.5 h-3.5"}),o("inventory.autoSelect")," (",u,")"]})]}),r.jsx("div",{className:"space-y-3",children:e.map(({printer:p,calibrations:f})=>{const g=i.has(String(p.id)),w=f.filter(C=>fF(C,t)),b=w.length,x=w.some(C=>C.extruder_id!==void 0&&C.extruder_id!==null&&C.extruder_id>0),S=w.filter(C=>C.extruder_id===1),N=w.filter(C=>C.extruder_id===0||C.extruder_id===void 0||C.extruder_id===null);return r.jsxs("div",{className:"border border-bambu-dark-tertiary rounded-lg overflow-hidden",children:[r.jsxs("button",{type:"button",onClick:()=>l(String(p.id)),className:"w-full px-4 py-3 flex items-center justify-between bg-bambu-dark-secondary hover:bg-bambu-dark-tertiary transition-colors",children:[r.jsxs("div",{className:"flex items-center gap-3",children:[g?r.jsx(Rn,{className:"w-4 h-4 text-bambu-gray"}):r.jsx(Va,{className:"w-4 h-4 text-bambu-gray"}),r.jsx("span",{className:"font-medium text-white",children:p.name}),b>0?r.jsxs("span",{className:"text-xs px-2 py-0.5 rounded-full bg-bambu-green/20 text-bambu-green",children:[b," ",o(b!==1?"inventory.matches":"inventory.match")]}):r.jsx("span",{className:"text-xs px-2 py-0.5 rounded-full bg-bambu-dark-tertiary text-bambu-gray",children:o("inventory.noMatches")})]}),r.jsx("span",{className:`text-xs px-2 py-1 rounded-full ${p.connected?"bg-green-500/20 text-green-500":"bg-bambu-gray/20 text-bambu-gray"}`,children:p.connected?o("inventory.connected"):o("inventory.offline")})]}),g&&r.jsx("div",{className:"px-4 py-3 space-y-3 bg-bambu-dark border-t border-bambu-dark-tertiary",children:p.connected?b===0?r.jsx("p",{className:"text-sm text-bambu-gray italic py-2",children:o("inventory.noKProfilesMatch")}):x?r.jsxs(r.Fragment,{children:[S.length>0&&r.jsxs("div",{className:"space-y-2",children:[r.jsx("p",{className:"text-xs font-medium text-bambu-gray uppercase tracking-wide",children:o("inventory.leftNozzle")}),r.jsx("div",{className:"space-y-2",children:S.map(C=>m(p,C))})]}),N.length>0&&r.jsxs("div",{className:"space-y-2",children:[r.jsx("p",{className:"text-xs font-medium text-bambu-gray uppercase tracking-wide",children:o("inventory.rightNozzle")}),r.jsx("div",{className:"space-y-2",children:N.map(C=>m(p,C))})]})]}):r.jsx("div",{className:"space-y-2",children:w.map(C=>m(p,C))}):r.jsx("p",{className:"text-sm text-bambu-gray italic py-2",children:o("inventory.printerOffline")})})]},p.id)})}),n.size>0&&r.jsx("div",{className:"p-3 bg-bambu-green/10 border border-bambu-green/30 rounded-lg",children:r.jsxs("p",{className:"text-sm text-white",children:[r.jsx("span",{className:"font-semibold",children:n.size})," ",o("inventory.profilesSelected")]})})]})}function Kit(t){const e=new Date(t);return e.toLocaleDateString("en-GB",{day:"2-digit",month:"2-digit",year:"2-digit"})+" "+e.toLocaleTimeString("en-GB",{hour:"2-digit",minute:"2-digit"})}const Yit={completed:"text-bambu-green",failed:"text-red-400",aborted:"text-yellow-400"};function Xit({spoolId:t}){const{t:e}=kt(),n=en(),{showToast:a}=rn(),{data:i,isLoading:s}=Ge({queryKey:["spool-usage",t],queryFn:()=>ie.getSpoolUsageHistory(t)}),o=it({mutationFn:()=>ie.clearSpoolUsageHistory(t),onSuccess:()=>{n.invalidateQueries({queryKey:["spool-usage",t]}),a(e("inventory.historyCleared"),"success")}});return s?r.jsx("div",{className:"flex justify-center py-4",children:r.jsx(pt,{className:"w-5 h-5 animate-spin text-bambu-green"})}):!i||i.length===0?r.jsxs("div",{className:"text-center py-4 text-bambu-gray text-sm",children:[r.jsx(Zn,{className:"w-5 h-5 mx-auto mb-2 opacity-50"}),e("inventory.noUsageHistory")]}):r.jsxs("div",{className:"space-y-2",children:[r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsx("h4",{className:"text-sm font-medium text-white",children:e("inventory.usageHistory")}),r.jsxs(Me,{variant:"ghost",size:"sm",onClick:()=>o.mutate(),disabled:o.isPending,className:"text-xs text-bambu-gray hover:text-red-400",children:[r.jsx(Jt,{className:"w-3 h-3 mr-1"}),e("inventory.clearHistory")]})]}),r.jsx("div",{className:"max-h-48 overflow-y-auto space-y-1",children:i.map(l=>r.jsxs("div",{className:"flex items-center justify-between p-2 rounded bg-bambu-dark/50 text-xs",children:[r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsx("span",{className:"text-bambu-gray",children:Kit(l.created_at)}),l.print_name&&r.jsx("span",{className:"text-white ml-2 truncate",title:l.print_name,children:l.print_name})]}),r.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0 ml-2",children:[r.jsxs("span",{className:"text-white font-medium",children:[l.weight_used.toFixed(1),"g"]}),r.jsxs("span",{className:"text-bambu-gray",children:["(",l.percent_used,"%)"]}),r.jsx("span",{className:Yit[l.status]||"text-bambu-gray",children:l.status})]})]},l.id))})]})}const xQ={tag_uid:null,tray_uuid:null,tag_type:null,data_origin:null};function Qit({isOpen:t,onClose:e,spool:n,mode:a,printersWithCalibrations:i=[],currencySymbol:s,onSpoolsCreated:o,spoolmanMode:l=!1,spoolsQueryKey:c=["inventory-spools"]}){const{t:d}=kt(),u=en(),{showToast:m}=rn(),p=a==="edit",f=a==="copy",[g,w]=y.useState(YI),[b,x]=y.useState({}),[S,N]=y.useState("filament"),[C,P]=y.useState(!1),[T,A]=y.useState(!1),[F,_]=y.useState(!1),[E,H]=y.useState(1),[I,U]=y.useState(!1),[L,Q]=y.useState(!1),[re,J]=y.useState([]),[ce,pe]=y.useState(""),[ue,X]=y.useState([]),[ae,me]=y.useState([]),[ge,Pe]=y.useState([]),[$,W]=y.useState([]),[D,j]=y.useState([]),[B,Y]=y.useState([]),[O,se]=y.useState(new Set),[z,G]=y.useState(new Set),K=i.length>0?i:B,Z=O.size,{data:oe=[],isLoading:ee,error:fe}=Ge({queryKey:["spoolman-inventory-filaments"],queryFn:()=>ie.getSpoolmanInventoryFilaments(),enabled:l&&t,staleTime:6e4,retry:!1});y.useEffect(()=>{j(Gce())},[]),y.useEffect(()=>{t&&((async()=>{Q(!0);try{const gt=await ie.getCloudStatus();if(U(gt.is_authenticated),gt.is_authenticated){const ct=await ie.getFilamentPresets();J(ct)}}catch(gt){console.error("Failed to fetch cloud presets:",gt),U(!1)}finally{Q(!1)}})(),l||ie.getSpoolCatalog().then(X).catch(console.error),ie.getColorCatalog().then(W).catch(console.error),ie.getLocalPresets().then(gt=>me(gt.filament)).catch(console.error),ie.getBuiltinFilaments().then(Pe).catch(console.error),i.length===0&&(async()=>{try{const gt=await ie.getPrinters(),ct=await Promise.all(gt.map(Ot=>ie.getPrinterStatus(Ot.id).catch(()=>null))),at=[];for(let Ot=0;Ot({cali_idx:dt.slot_id,filament_id:dt.filament_id,setting_id:dt.setting_id||"",name:dt.name,k_value:parseFloat(dt.k_value)||0,n_coef:parseFloat(dt.n_coef)||0,extruder_id:dt.extruder_id,nozzle_diameter:dt.nozzle_diameter}))}catch{}at.push({printer:{...Wt,connected:Yt},calibrations:un})}Y(at)}catch(gt){console.error("Failed to fetch printer calibrations:",gt)}})())},[t,i.length]);const de=y.useMemo(()=>$ce(re,new Set,ae,ge),[re,ae,ge]),le=y.useMemo(()=>{const Ke=qce(re,ae),gt=$.map(at=>at.manufacturer?.trim()).filter(at=>!!at),ct=new Set([...Ke,...gt]);return Array.from(ct).sort((at,Ot)=>at.localeCompare(Ot))},[re,ae,$]),q=y.useMemo(()=>{const Ke=$.map(ct=>ct.material?.trim()).filter(ct=>!!ct),gt=new Set([...Uce,...Ke]);return Array.from(gt).sort((ct,at)=>ct.localeCompare(at))},[$]),R=y.useMemo(()=>{const Ke=[];for(const gt of $){const ct=gt.manufacturer?.trim(),at=gt.material?.trim();ct&&at&&Ke.push({brand:ct,material:at})}for(const gt of re){const ct=Jh(gt.name);ct.brand&&ct.material&&Ke.push({brand:ct.brand,material:ct.material})}for(const gt of ae){const ct=Jh(gt.name),at=gt.filament_vendor?.trim()||ct.brand,Ot=ct.material;at&&Ot&&Ke.push({brand:at,material:Ot})}return Ke},[re,$,ae]),ne=y.useMemo(()=>{const Ke=new Map;for(const gt of R){const ct=gt.brand.toLowerCase(),at=gt.material.toLowerCase();Ke.has(ct)||Ke.set(ct,new Set),Ke.get(ct).add(at)}return Ke},[R]),xe=y.useMemo(()=>{const Ke=new Map;for(const gt of R){const ct=gt.brand.toLowerCase(),at=gt.material.toLowerCase();Ke.has(at)||Ke.set(at,new Set),Ke.get(at).add(ct)}return Ke},[R]),ve=y.useMemo(()=>{if(!g.material)return le;const Ke=g.material.toLowerCase(),gt=xe.get(Ke);return!gt||gt.size===0?le:le.filter(ct=>gt.has(ct.toLowerCase()))},[le,g.material,xe]),Ce=y.useMemo(()=>{if(!g.brand)return q;const Ke=g.brand.toLowerCase(),gt=ne.get(Ke);return!gt||gt.size===0?q:q.filter(ct=>gt.has(ct.toLowerCase()))},[q,g.brand,ne]),ye=y.useMemo(()=>Vce(g.slicer_filament,de),[g.slicer_filament,de]);y.useEffect(()=>{if(t){if(n){const Ke=n.rgba&&/^[0-9A-Fa-f]{8}$/.test(n.rgba)?n.rgba:"808080FF";if(w({material:n.material||"",subtype:n.subtype||"",brand:n.brand||"",color_name:n.color_name_is_synthesized?"":n.color_name||"",rgba:Ke,extra_colors:n.extra_colors||"",effect_type:n.effect_type||"",label_weight:n.label_weight||1e3,core_weight:n.core_weight||250,core_weight_catalog_id:n.core_weight_catalog_id??null,weight_used:f?0:n.weight_used||0,slicer_filament:n.slicer_filament||"",note:n.note||"",cost_per_kg:n.cost_per_kg??null,category:n.category||"",low_stock_threshold_pct:n.low_stock_threshold_pct??null,storage_location:n.storage_location||"",spoolman_filament_id:null}),pe(n.slicer_filament_name||n.slicer_filament||""),n.k_profiles&&n.k_profiles.length>0){const gt=new Set;for(const ct of n.k_profiles)ct.cali_idx!==null&&ct.cali_idx!==void 0&>.add(`${ct.printer_id}:${ct.cali_idx}:${ct.extruder??"null"}`);se(gt)}else se(new Set)}else w(YI),pe(""),se(new Set),_(!1),H(1);x({}),N("filament"),P(!1),A(!1)}},[t,n,a,f]),y.useEffect(()=>{t&&K.length>0&&G(new Set(K.map(Ke=>String(Ke.printer.id))))},[t,K]);const be=(Ke,gt)=>{const ct=zit.has(Ke);l&&ct&&g.spoolman_filament_id!==null&&m(d("inventory.spoolmanFilamentUnlinked"),"info"),w(at=>({...at,[Ke]:gt,...l&&ct&&at.spoolman_filament_id!==null?{spoolman_filament_id:null}:{}})),Ke==="weight_used"&&P(!0),Ke==="storage_location"&&A(!0),b[Ke]&&x(at=>({...at,[Ke]:void 0}))},Ee=Ke=>{const gt=Ke.material||"",ct=Ke.name||"",at=gt&&ct.startsWith(gt)?ct.slice(gt.length).trim():ct,Ot=(Ke.color_hex??"").replace("#","").toUpperCase(),Wt=/^[0-9A-F]{6}$/.test(Ot)?Ot:"808080";w(Zt=>({...Zt,spoolman_filament_id:Ke.id,material:gt,subtype:at,brand:Ke.vendor?.name||"",rgba:`${Wt}FF`,color_name:Ke.color_name||"",label_weight:Ke.weight??Zt.label_weight})),m(d("inventory.spoolmanFilamentSelected"),"success")},ze=Ke=>{j(gt=>Wce(Ke,gt))},Oe=it({mutationFn:Ke=>l?ie.createSpoolmanInventorySpool(Ke):ie.createSpool(Ke),onSuccess:async Ke=>{Ke?.id&&!await De(Ke.id)||(await u.invalidateQueries({queryKey:c}),o&&o([Ke]),m(d("inventory.spoolCreated"),"success"),e())},onError:Ke=>{Ke instanceof _i&&Ke.status===503?m(d("inventory.spoolmanUnreachable"),"error"):m(d("inventory.saveFailed"),"error")}}),Be=it({mutationFn:({data:Ke,qty:gt})=>l?ie.bulkCreateSpoolmanInventorySpools(Ke,gt):ie.bulkCreateSpools(Ke,gt),onSuccess:async Ke=>{const gt=l&&"created"in Ke?Ke:null,ct=gt?gt.created:Ke;if(O.size>0)for(const at of ct)await De(at.id);await u.invalidateQueries({queryKey:c}),o&&o(ct),gt&>.failed_count>0?m(d("inventory.spoolsPartiallyCreated",{created:ct.length,total:gt.requested_count}),"warning"):m(d("inventory.spoolsCreated",{count:ct.length}),"success"),e()},onError:Ke=>{Ke instanceof _i&&Ke.status===503?m(d("inventory.spoolmanUnreachable"),"error"):m(d("inventory.saveFailed"),"error")}}),Se=it({mutationFn:Ke=>l?ie.updateSpoolmanInventorySpool(n.id,Ke):ie.updateSpool(n.id,Ke),onSuccess:async()=>{n?.id&&!await De(n.id)||(await u.invalidateQueries({queryKey:c}),m(d("inventory.spoolUpdated"),"success"),e())},onError:Ke=>{Ke instanceof _i&&Ke.status===503?m(d("inventory.spoolmanUnreachable"),"error"):m(d("inventory.saveFailed"),"error")}}),$e=it({mutationFn:()=>l?ie.updateSpoolmanInventorySpool(n.id,xQ):ie.updateSpool(n.id,xQ),onSuccess:async()=>{await u.invalidateQueries({queryKey:c}),m(d("inventory.rfidCleared","RFID tag cleared"),"success"),e()},onError:Ke=>{Ke instanceof _i&&Ke.status===503?m(d("inventory.spoolmanUnreachable"),"error"):m(d("inventory.tagClearFailed"),"error")}}),{data:rt}=Ge({queryKey:["spool-assignments"],queryFn:()=>ie.getAssignments(),enabled:t&&p&&!l}),{data:ot}=Ge({queryKey:["spoolman-slot-assignments-all"],queryFn:()=>ie.getSpoolmanSlotAssignments(),enabled:t&&p&&l}),Le=(()=>{if(n)return l?ot?.find(Ke=>Ke.spoolman_spool_id===n.id):rt?.find(Ke=>Ke.spool_id===n.id)})(),{data:nt}=Ge({queryKey:["inventory-spools"],queryFn:()=>ie.getSpools(!0),enabled:t}),{data:Ne}=Ge({queryKey:["settings"],queryFn:ie.getSettings,enabled:t}),Qe=(()=>{const Ke=new Set;for(const gt of nt??[]){const ct=gt.category?.trim();ct&&Ke.add(ct)}return Array.from(Ke).sort((gt,ct)=>gt.localeCompare(ct))})(),Ue=Ne?.low_stock_threshold??20,ke=it({mutationFn:async()=>{if(!Le)throw new Error("No assignment");if(l){if(!n)throw new Error("No spool");await ie.unassignSpoolmanSlot(n.id);return}await ie.unassignSpool(Le.printer_id,Le.ams_id,Le.tray_id)},onSuccess:async()=>{l?(await u.invalidateQueries({queryKey:["spoolman-slot-assignments-all"]}),await u.invalidateQueries({queryKey:["spoolman-slot-assignments"]})):await u.invalidateQueries({queryKey:["spool-assignments"]}),m(d("inventory.unassignSuccess","Spool unassigned"),"success"),e()},onError:Ke=>{m(Ke.message,"error")}}),De=async Ke=>{const gt=l?ie.saveSpoolmanKProfiles:ie.saveSpoolKProfiles;if(O.size===0)try{return await gt(Ke,[]),!0}catch(Ot){return console.error("Failed to save K-profiles:",Ot),m(d("inventory.kProfileSaveFailed"),"warning"),!1}const ct=[];let at=0;for(const Ot of O){const[Wt,Zt,Yt]=Ot.split(":"),un=parseInt(Wt),bn=parseInt(Zt),dt=Yt==="null"?0:parseInt(Yt),st=K.find(vt=>vt.printer.id===un);if(st){const vt=st.calibrations.find(_t=>_t.cali_idx===bn);vt?ct.push({printer_id:un,extruder:dt,nozzle_diameter:vt.nozzle_diameter||"0.4",k_value:vt.k_value,name:vt.name||null,cali_idx:vt.cali_idx,setting_id:vt.setting_id||null}):at++}else at++}if(at>0)return console.error(`saveKProfiles: ${at} profile key(s) could not be resolved`,Array.from(O)),m(d("inventory.kProfileSaveFailed"),"warning"),!1;if(ct.length>0)try{return await gt(Ke,ct),!0}catch(Ot){return console.error("Failed to save K-profiles:",Ot),m(d("inventory.kProfileSaveFailed"),"warning"),!1}return!0};if(y.useEffect(()=>{if(!t)return;const Ke=gt=>{gt.key==="Escape"&&e()};return document.addEventListener("keydown",Ke),()=>document.removeEventListener("keydown",Ke)},[t,e]),!t)return null;const Ae=()=>{const Ke=zce(g,F,l);if(!Ke.isValid){x(Ke.errors),(Ke.errors.slicer_filament||Ke.errors.material||Ke.errors.brand||Ke.errors.subtype)&&N("filament");return}const gt=ye?.displayName||ce||null,ct={material:g.material||null,subtype:g.subtype||null,brand:g.brand||null,color_name:g.color_name||null,rgba:g.rgba||null,extra_colors:g.extra_colors||null,effect_type:g.effect_type||null,label_weight:g.label_weight,...l?{}:{core_weight:g.core_weight,core_weight_catalog_id:g.core_weight_catalog_id},slicer_filament:g.slicer_filament||null,slicer_filament_name:gt,nozzle_temp_min:null,nozzle_temp_max:null,note:g.note||null,cost_per_kg:g.cost_per_kg,category:g.category.trim()||null,low_stock_threshold_pct:g.low_stock_threshold_pct,...l?{spoolman_filament_id:g.spoolman_filament_id}:{}};(!p||C)&&(ct.weight_used=g.weight_used),(!p||T)&&(ct.storage_location=g.storage_location||null),p?Se.mutate(ct):E>1?Be.mutate({data:ct,qty:E}):Oe.mutate(ct)},Xe=Oe.isPending||Be.isPending||Se.isPending||$e.isPending||ke.isPending;return r.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[r.jsx("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-sm",onClick:e}),r.jsxs("div",{className:"relative w-full max-w-xl mx-4 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl max-h-[90vh] flex flex-col",children:[r.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary flex-shrink-0",children:[r.jsx("h2",{className:"text-lg font-semibold text-white",children:d(p?"inventory.editSpool":f?"inventory.copySpool":"inventory.addSpool")}),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"})})]}),a==="create"&&r.jsxs("div",{className:"flex items-center justify-between px-4 py-2 border-b border-bambu-dark-tertiary flex-shrink-0",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(Cc,{className:"w-4 h-4 text-amber-400"}),r.jsx("span",{className:"text-sm text-white",children:d("inventory.quickAdd")})]}),r.jsx("button",{type:"button",onClick:()=>{_(!F),F||N("filament")},className:`relative inline-flex h-5 w-9 items-center rounded-full transition-colors ${F?"bg-bambu-green":"bg-bambu-dark-tertiary"}`,children:r.jsx("span",{className:`inline-block h-3.5 w-3.5 rounded-full bg-white transition-transform ${F?"translate-x-4":"translate-x-0.5"}`})})]}),r.jsxs("div",{className:"flex border-b border-bambu-dark-tertiary flex-shrink-0",children:[r.jsxs("button",{onClick:()=>N("filament"),className:`flex-1 px-4 py-2.5 text-sm font-medium flex items-center justify-center gap-2 transition-colors ${S==="filament"?"text-bambu-green border-b-2 border-bambu-green":"text-bambu-gray hover:text-white"}`,children:[r.jsx(jS,{className:"w-4 h-4"}),d("inventory.filamentInfoTab")]}),!F&&r.jsxs("button",{onClick:()=>N("pa-profile"),className:`flex-1 px-4 py-2.5 text-sm font-medium flex items-center justify-center gap-2 transition-colors ${S==="pa-profile"?"text-bambu-green border-b-2 border-bambu-green":"text-bambu-gray hover:text-white"}`,children:[r.jsx(yfe,{className:"w-4 h-4"}),d("inventory.paProfileTab"),Z>0&&r.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded-full bg-bambu-green/20 text-bambu-green",children:Z})]})]}),r.jsx("div",{className:"p-4 overflow-y-auto flex-1",style:{scrollbarGutter:"stable"},children:S==="filament"?r.jsxs("div",{className:"space-y-6",children:[l&&!p&&r.jsx("div",{children:fe?r.jsx("p",{className:"text-sm text-red-400 px-1",children:d("inventory.spoolmanCatalogLoadFailed")}):r.jsx(Wit,{filaments:oe,isLoading:ee,selectedId:g.spoolman_filament_id,onSelect:Ee})}),r.jsxs("div",{children:[r.jsx("h3",{className:"text-sm font-semibold text-bambu-gray uppercase tracking-wide mb-3",children:d("inventory.filamentInfo")}),r.jsx(Kce,{formData:g,updateField:be,cloudAuthenticated:I,loadingCloudPresets:L,presetInputValue:ce,setPresetInputValue:pe,selectedPresetOption:ye,filamentOptions:de,availableBrands:ve,availableMaterials:Ce,quickAdd:F,quantity:E,onQuantityChange:H,errors:b})]}),r.jsxs("div",{children:[r.jsx("h3",{className:"text-sm font-semibold text-bambu-gray uppercase tracking-wide mb-3",children:d("inventory.color")}),r.jsx(Yce,{formData:g,updateField:be,recentColors:D,onColorUsed:ze,catalogColors:$})]}),r.jsxs("div",{children:[r.jsx("h3",{className:"text-sm font-semibold text-bambu-gray uppercase tracking-wide mb-3",children:d("inventory.additional")}),r.jsx(Xce,{formData:g,updateField:be,spoolCatalog:ue,currencySymbol:s,availableCategories:Qe,globalLowStockThreshold:Ue,spoolmanMode:l})]}),p&&n&&!l&&r.jsx("div",{children:r.jsx(Xit,{spoolId:n.id})})]}):r.jsx(Qce,{formData:g,updateField:be,printersWithCalibrations:K,selectedProfiles:O,setSelectedProfiles:se,expandedPrinters:z,setExpandedPrinters:G})}),r.jsxs("div",{className:"flex gap-2 p-4 border-t border-bambu-dark-tertiary flex-shrink-0",children:[p&&r.jsxs("div",{className:"flex gap-2 mr-auto",children:[r.jsxs(Me,{variant:"secondary",onClick:()=>$e.mutate(),disabled:Xe||!n?.tag_uid,children:[r.jsx($m,{className:"w-4 h-4"}),d("inventory.clearRfid","Clear RFID Tag")]}),r.jsxs(Me,{variant:"secondary",onClick:()=>ke.mutate(),disabled:Xe||!Le,children:[r.jsx(iu,{className:"w-4 h-4"}),d("inventory.unassignSpool","Unassign")]})]}),r.jsxs("div",{className:"flex gap-2 ml-auto",children:[r.jsx(Me,{variant:"secondary",onClick:e,children:d("common.cancel")}),r.jsx(Me,{onClick:Ae,disabled:Xe,children:Xe?r.jsxs(r.Fragment,{children:[r.jsx(pt,{className:"w-4 h-4 animate-spin"}),d("common.saving")]}):r.jsxs(r.Fragment,{children:[r.jsx(us,{className:"w-4 h-4"}),d(p?"common.save":f?"inventory.copySpool":"inventory.addSpool")]})})]})]})]})]})}function Zit({isOpen:t,onClose:e,columns:n,defaultColumns:a,onSave:i}){const{t:s}=kt(),[o,l]=y.useState(n),[c,d]=y.useState(null),u=y.useRef(null);if(y.useEffect(()=>{t&&l(n.map(C=>({...C})))},[t,n]),y.useEffect(()=>{if(!t)return;const C=P=>{P.key==="Escape"&&e()};return window.addEventListener("keydown",C),()=>window.removeEventListener("keydown",C)},[t,e]),!t)return null;const m=C=>{l(P=>P.map((T,A)=>A===C?{...T,visible:!T.visible}:T))},p=(C,P)=>{P<0||P>=o.length||l(T=>{const A=[...T],[F]=A.splice(C,1);return A.splice(P,0,F),A})},f=(C,P)=>{u.current=P,d(P),C.dataTransfer.effectAllowed="move"},g=(C,P)=>{C.preventDefault(),C.dataTransfer.dropEffect="move";const T=u.current;T!==null&&T!==P&&(p(T,P),u.current=P,d(P))},w=C=>{C.preventDefault()},b=()=>{u.current=null,d(null)},x=()=>{l(a.map(C=>({...C})))},S=()=>{i(o),e()},N=o.filter(C=>C.visible).length;return r.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",onClick:e,children:r.jsx(Ct,{className:"w-full max-w-md max-h-[80vh] flex flex-col",onClick:C=>C.stopPropagation(),children:r.jsxs(At,{className:"p-6 flex flex-col min-h-0",children:[r.jsx("h3",{className:"text-lg font-semibold text-white mb-2",children:s("inventory.configureColumns")}),r.jsxs("p",{className:"text-sm text-bambu-gray mb-4",children:[s("inventory.configureColumnsDesc"),r.jsxs("span",{className:"ml-2 text-bambu-gray/60",children:["(",N," ",s("inventory.of")," ",o.length," ",s("inventory.visible"),")"]})]}),r.jsx("div",{className:"space-y-1 overflow-y-auto flex-1 min-h-0 pr-1",children:o.map((C,P)=>r.jsxs("div",{className:`flex items-center gap-2 p-2 rounded-lg border transition-colors ${c===P?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary bg-bambu-dark-tertiary/50"} ${C.visible?"":"opacity-50"}`,draggable:!0,onDragStart:T=>f(T,P),onDragOver:T=>g(T,P),onDrop:w,onDragEnd:b,children:[r.jsx("div",{className:"cursor-grab text-bambu-gray/50 hover:text-bambu-gray",children:r.jsx(Ph,{className:"w-4 h-4"})}),r.jsx("span",{className:"flex-1 font-medium text-sm text-white",children:C.label}),r.jsxs("div",{className:"flex items-center gap-0.5",children:[r.jsx("button",{onClick:()=>p(P,P-1),disabled:P===0,className:"p-1 rounded text-bambu-gray hover:bg-bambu-dark-secondary disabled:opacity-30 disabled:cursor-not-allowed",title:s("inventory.moveUp"),children:r.jsx(tl,{className:"w-4 h-4"})}),r.jsx("button",{onClick:()=>p(P,P+1),disabled:P===o.length-1,className:"p-1 rounded text-bambu-gray hover:bg-bambu-dark-secondary disabled:opacity-30 disabled:cursor-not-allowed",title:s("inventory.moveDown"),children:r.jsx(Rn,{className:"w-4 h-4"})})]}),r.jsx("button",{onClick:()=>m(P),className:`p-1.5 rounded transition-colors ${C.visible?"text-bambu-green hover:bg-bambu-green/10":"text-bambu-gray/50 hover:bg-bambu-dark-secondary"}`,title:C.visible?s("inventory.hideColumn"):s("inventory.showColumn"),children:C.visible?r.jsx(Dl,{className:"w-4 h-4"}):r.jsx(sb,{className:"w-4 h-4"})})]},C.id))}),r.jsxs("div",{className:"flex items-center gap-3 mt-4 pt-4 border-t border-bambu-dark-tertiary",children:[r.jsxs(Me,{variant:"secondary",onClick:x,className:"mr-auto",children:[r.jsx(gs,{className:"w-4 h-4"}),s("inventory.reset")]}),r.jsx(Me,{variant:"secondary",onClick:e,children:s("inventory.cancel")}),r.jsx(Me,{onClick:S,children:s("inventory.applyChanges")})]})]})})})}const Jit=[{value:"ams_30x15",i18nKey:"ams",fallbackLabel:"AMS holder (30 × 15 mm)",fallbackHint:"Single label per page; fits the popular AMS filament label holder."},{value:"box_40x30",i18nKey:"box40x30",fallbackLabel:"Box label (40 × 30 mm)",fallbackHint:"Single label per page; common DK/Brother roll size, good for filament-bag and storage-bin labels."},{value:"box_62x29",i18nKey:"box",fallbackLabel:"Box label (62 × 29 mm)",fallbackHint:"Single label per page; sized for Brother PT/QL and Dymo small labels."},{value:"avery_l7160",i18nKey:"averyL7160",fallbackLabel:"Avery L7160 — A4 sheet (38.1 × 63.5 mm × 21)",fallbackHint:"EU sheet stock; 21 labels per A4 page."},{value:"avery_5160",i18nKey:"avery5160",fallbackLabel:"Avery 5160 — US Letter sheet (25.4 × 66.7 mm × 30)",fallbackHint:"US sheet stock; 30 labels per Letter page."}];function est(t){const e=window.URL.createObjectURL(t);if(!window.open(e,"_blank","noopener,noreferrer")){const a=document.createElement("a");a.href=e,a.download="bambuddy-labels.pdf",document.body.appendChild(a),a.click(),document.body.removeChild(a)}setTimeout(()=>window.URL.revokeObjectURL(e),6e4)}function tst(t){if(!t)return{backgroundColor:"#808080"};const e=t.replace(/^#/,"").slice(0,6);return e.length===6?{backgroundColor:`#${e}`}:{backgroundColor:"#808080"}}function nst(t){const e=t.color_name??`${t.material}${t.subtype?` ${t.subtype}`:""}`,n=t.brand?` · ${t.brand}`:"";return`${e}${n}`}function rst(t){return[t.color_name,t.material,t.subtype,t.brand,`#${t.id}`].filter(Boolean).join(" ").toLowerCase()}function ast({isOpen:t,onClose:e,availableSpools:n,initialSelectedIds:a,spoolmanMode:i}){const{t:s}=kt(),{showToast:o}=rn(),[l,c]=y.useState(null),[d,u]=y.useState(new Set),[m,p]=y.useState(""),[f,g]=y.useState("");y.useEffect(()=>{if(t){const E=new Set(n.map(H=>H.id));u(new Set(a.filter(H=>E.has(H)))),p(""),g(""),c(null)}},[t]);const w=y.useMemo(()=>[...n].sort((E,H)=>E.id-H.id),[n]),b=y.useMemo(()=>{const E=new Set;for(const H of w)H.material&&E.add(H.material.toUpperCase());return[...E].sort()},[w]),x=y.useMemo(()=>{const E=m.trim().toLowerCase();return w.filter(H=>!(f&&(H.material||"").toUpperCase()!==f||E&&!rst(H).includes(E)))},[w,m,f]),S=x.length>0&&x.every(E=>d.has(E.id));if(!t)return null;const N=d.size,C=N===0;function P(E){u(H=>{const I=new Set(H);return I.has(E)?I.delete(E):I.add(E),I})}function T(){u(E=>{const H=new Set(E);for(const I of x)H.add(I.id);return H})}function A(){u(E=>{const H=new Set(E);for(const I of x)H.delete(I.id);return H})}function F(){u(new Set)}async function _(E){if(C||l)return;const H=[...d].sort((I,U)=>I-U);c(E);try{const I=i?await ie.printSpoolmanSpoolLabels({spool_ids:H,template:E}):await ie.printSpoolLabels({spool_ids:H,template:E});est(I),e()}catch(I){const U=I instanceof Error?I.message:String(I);o(s("inventory.labels.error","Could not generate labels: {{msg}}",{msg:U}),"error")}finally{c(null)}}return r.jsxs("div",{className:"fixed inset-0 z-50 flex items-start sm:items-center justify-center p-4 overflow-y-auto",children:[r.jsx("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-sm",onClick:e}),r.jsxs("div",{className:"relative w-full max-w-3xl bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl max-h-[90vh] overflow-hidden flex flex-col my-auto",children:[r.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(pr,{className:"w-5 h-5 text-bambu-green"}),r.jsx("h2",{className:"text-lg font-semibold text-white",children:s("inventory.labels.title","Print spool labels")}),N>0&&r.jsxs("span",{className:"text-sm text-bambu-gray",children:["(",s("inventory.labels.selectedCount","{{count}} selected",{count:N}),")"]})]}),r.jsx("button",{onClick:e,className:"p-1 text-bambu-gray hover:text-white rounded transition-colors","aria-label":s("common.close","Close"),children:r.jsx(Ht,{className:"w-5 h-5"})})]}),r.jsxs("div",{className:"p-4 space-y-2 border-b border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"relative",children:[r.jsx(Sr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"}),r.jsx("input",{type:"search",value:m,onChange:E=>p(E.target.value),placeholder:s("inventory.labels.searchPlaceholder","Search name, brand, or #ID"),className:"w-full pl-9 pr-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray focus:outline-none focus:border-bambu-green"})]}),b.length>1&&r.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[r.jsx("span",{className:"text-xs text-bambu-gray mr-1",children:s("inventory.labels.filterByMaterial","Material:")}),r.jsx("button",{type:"button",onClick:()=>g(""),className:`px-2 py-0.5 text-xs rounded-full border transition ${f===""?"bg-bambu-green text-bambu-dark border-bambu-green":"bg-bambu-dark text-bambu-gray border-bambu-dark-tertiary hover:border-bambu-gray"}`,children:s("inventory.labels.allMaterials","All")}),b.map(E=>r.jsx("button",{type:"button",onClick:()=>g(E),className:`px-2 py-0.5 text-xs rounded-full border transition ${f===E?"bg-bambu-green text-bambu-dark border-bambu-green":"bg-bambu-dark text-bambu-gray border-bambu-dark-tertiary hover:border-bambu-gray"}`,children:E},E))]})]}),r.jsxs("div",{className:"px-4 pt-3 pb-2 flex items-center justify-between gap-3 flex-wrap",children:[r.jsx("span",{className:"text-sm text-bambu-gray",children:s("inventory.labels.pickSpools","Pick which spools to print labels for:")}),r.jsxs("div",{className:"flex items-center gap-3 text-xs",children:[r.jsx("button",{type:"button",onClick:S?A:T,disabled:x.length===0,className:"text-bambu-green hover:underline disabled:opacity-50 disabled:no-underline disabled:cursor-not-allowed",children:S?s("inventory.labels.deselectVisible","Deselect visible"):s("inventory.labels.selectVisible","Select all visible ({{count}})",{count:x.length})}),r.jsx("button",{type:"button",onClick:F,disabled:N===0,className:"text-bambu-gray hover:text-white hover:underline disabled:opacity-50 disabled:no-underline disabled:cursor-not-allowed",children:s("inventory.labels.clearAll","Clear all")})]})]}),r.jsx("div",{className:"flex-1 overflow-y-auto px-2 pb-2 min-h-0",children:x.length===0?r.jsx("div",{className:"text-center text-sm text-bambu-gray py-6",children:w.length===0?s("inventory.labels.noSpoolsToShow","No spools to show. Adjust your filter and try again."):s("inventory.labels.noMatches","No spools match the current search or filter.")}):r.jsx("ul",{className:"space-y-0.5",children:x.map(E=>{const H=d.has(E.id);return r.jsx("li",{children:r.jsxs("label",{className:"flex items-center gap-3 px-2 py-1.5 rounded hover:bg-bambu-dark-tertiary/50 cursor-pointer",children:[H?r.jsx(bs,{className:"w-4 h-4 text-bambu-green shrink-0"}):r.jsx(so,{className:"w-4 h-4 text-bambu-gray shrink-0"}),r.jsx("input",{type:"checkbox",checked:H,onChange:()=>P(E.id),className:"sr-only"}),r.jsx("span",{className:"w-4 h-4 rounded border border-black/20 shrink-0",style:tst(E.rgba)}),r.jsx("span",{className:"flex-1 min-w-0 truncate text-sm text-white",children:nst(E)}),r.jsxs("span",{className:"text-xs font-mono text-bambu-gray shrink-0",children:["#",E.id]})]})},E.id)})})}),r.jsx("div",{className:"px-3 pt-2 pb-2 grid grid-cols-1 sm:grid-cols-2 gap-2 border-t border-bambu-dark-tertiary",children:Jit.map(E=>{const H=l===E.value,I=s(`inventory.labels.templates.${E.i18nKey}.label`,E.fallbackLabel),U=s(`inventory.labels.templates.${E.i18nKey}.hint`,E.fallbackHint);return r.jsxs("button",{disabled:C||l!==null,onClick:()=>_(E.value),title:`${I} — ${U}`,className:"w-full text-left p-2.5 rounded-lg border border-bambu-dark-tertiary bg-bambu-dark hover:border-bambu-green hover:bg-bambu-green/10 disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:border-bambu-dark-tertiary disabled:hover:bg-bambu-dark transition flex items-center gap-3",children:[r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsx("div",{className:"font-medium text-white text-sm truncate",children:I}),r.jsx("div",{className:"text-xs text-bambu-gray mt-0.5 truncate",children:U})]}),H&&r.jsx(pt,{className:"w-4 h-4 animate-spin text-bambu-green shrink-0"})]},E.value)})}),r.jsx("div",{className:"flex justify-end gap-2 px-5 py-2 border-t border-bambu-dark-tertiary",children:r.jsx(Me,{variant:"secondary",onClick:e,disabled:l!==null,children:s("common.cancel","Cancel")})})]})]})}function yQ(t){return`${t.material}|${t.subtype||""}|${t.brand||""}|${t.color_name||""}|${t.rgba||""}|${t.extra_colors||""}|${t.effect_type||""}|${t.label_weight}`}const Zce="bambuddy-inventory-columns",HN=[{id:"id",label:"#",visible:!0},{id:"added_time",label:"Added",visible:!0},{id:"encode_time",label:"Encoded",visible:!1},{id:"last_used_time",label:"Last Used",visible:!1},{id:"rgba",label:"Color",visible:!0},{id:"material",label:"Material",visible:!0},{id:"subtype",label:"Subtype",visible:!0},{id:"color_name",label:"Color Name",visible:!1},{id:"brand",label:"Brand",visible:!0},{id:"slicer_filament",label:"Slicer Filament",visible:!1},{id:"location",label:"Location",visible:!0},{id:"storage_location",label:"Storage Location",visible:!1},{id:"label_weight",label:"Label",visible:!0},{id:"net",label:"Net",visible:!0},{id:"gross",label:"Gross",visible:!1},{id:"added_full",label:"Full",visible:!1},{id:"used",label:"Used",visible:!1},{id:"printed_total",label:"Printed Total",visible:!1},{id:"printed_since_weight",label:"Printed Since Weight",visible:!1},{id:"note",label:"Note",visible:!1},{id:"pa_k",label:"PA(K)",visible:!0},{id:"tag_id",label:"Tag ID",visible:!1},{id:"data_origin",label:"Data Origin",visible:!1},{id:"tag_type",label:"Linked Tag Type",visible:!1},{id:"stock",label:"Stock",visible:!1},{id:"remaining",label:"Remaining",visible:!0},{id:"spool_name",label:"Spool",visible:!1},{id:"cost_per_kg",label:"Cost/kg",visible:!1},{id:"weight_check",label:"Weight Check",visible:!1}];function ist(){try{const t=localStorage.getItem(Zce);if(t){const e=JSON.parse(t),n=new Set(HN.map(o=>o.id)),a=new Set(e.map(o=>o.id)),i=e.filter(o=>n.has(o.id)),s=HN.filter(o=>!a.has(o.id));return[...i,...s]}}catch{}return HN.map(t=>({...t}))}function sst(t){try{localStorage.setItem(Zce,JSON.stringify(t))}catch{}}function au(t,e=!1){return e&&t>=1e3?`${(t/1e3).toFixed(1)}kg`:`${Math.round(t)}g`}const ost={PLA:"bg-green-500/20 text-green-400",ABS:"bg-red-500/20 text-red-400",PETG:"bg-blue-500/20 text-blue-400",TPU:"bg-purple-500/20 text-purple-400",ASA:"bg-orange-500/20 text-orange-400",PA:"bg-yellow-500/20 text-yellow-400",PC:"bg-cyan-500/20 text-cyan-400",PET:"bg-sky-500/20 text-sky-400"};function gF(t,e="system"){if(!t)return"-";const n=Xn(t);return n?YF(n,e):"-"}const lst={id:()=>"#",added_time:()=>"Added",encode_time:()=>"Encoded",last_used_time:()=>"Last Used",rgba:t=>t("inventory.color"),material:t=>t("inventory.material"),subtype:t=>t("inventory.subtype"),color_name:t=>t("inventory.colorName"),brand:t=>t("inventory.brand"),slicer_filament:t=>t("inventory.slicerFilament"),location:()=>"Location",storage_location:t=>t("inventory.storageLocation"),label_weight:t=>t("inventory.labelWeight"),net:t=>t("inventory.net"),gross:()=>"Gross",added_full:()=>"Full",used:t=>t("inventory.weightUsed"),printed_total:()=>"Printed Total",printed_since_weight:()=>"Printed Since Weight",note:t=>t("inventory.note"),pa_k:()=>"PA(K)",tag_id:()=>"Tag ID",data_origin:()=>"Data Origin",tag_type:()=>"Linked Tag Type",stock:t=>t("inventory.stock"),remaining:t=>t("inventory.remaining"),spool_name:t=>t("inventory.spoolName"),cost_per_kg:t=>t("inventory.costPerKg"),weight_check:t=>t("inventory.weightCheck")},XI={id:({spool:t})=>r.jsx("span",{className:"text-sm font-medium text-white",children:t.id}),added_time:({spool:t,dateFormat:e})=>r.jsx("span",{className:"text-sm text-bambu-gray",children:gF(t.created_at,e)}),encode_time:({spool:t,dateFormat:e})=>r.jsx("span",{className:"text-sm text-bambu-gray",children:gF(t.encode_time,e)}),last_used_time:({spool:t,dateFormat:e})=>r.jsx("span",{className:"text-sm text-bambu-gray",children:t.last_used?gF(t.last_used,e):"Never"}),rgba:({spool:t})=>r.jsx("div",{className:"flex items-center justify-center",children:r.jsx(rU,{rgba:t.rgba,extraColors:t.extra_colors,effectType:t.effect_type,effectSize:"table",subtype:t.subtype})}),material:({spool:t})=>r.jsx("span",{className:"text-sm text-white",children:t.material}),subtype:({spool:t})=>r.jsx("span",{className:"text-sm text-bambu-gray",children:t.subtype||"-"}),color_name:({spool:t})=>r.jsx("span",{className:"text-sm text-bambu-gray",children:PT(t.color_name,t.rgba)||"-"}),brand:({spool:t})=>r.jsx("span",{className:"text-sm text-bambu-gray",children:t.brand||"-"}),slicer_filament:({spool:t})=>r.jsx("span",{className:"text-sm text-bambu-gray",title:t.slicer_filament||void 0,children:t.slicer_filament_name||t.slicer_filament||"-"}),location:({spool:t,assignmentMap:e})=>{const n=e[t.id];if(!n)return r.jsx("span",{className:"text-sm text-bambu-gray",children:"-"});const a=n.printer_name||`Printer ${n.printer_id}`,i=n.ams_id===254||n.ams_id===255,s=!i&&n.ams_id>=128,o=c_(n.ams_id,n.tray_id,s,i);return r.jsxs("span",{className:"inline-flex items-center px-1.5 py-0.5 rounded text-xs font-medium bg-purple-500/20 text-purple-400",children:[a," ",o,n.ams_label?` (${n.ams_label})`:""]})},storage_location:({spool:t})=>t.storage_location?r.jsx("span",{className:"inline-flex items-center px-1.5 py-0.5 rounded text-xs font-medium bg-blue-500/20 text-blue-400",children:t.storage_location}):r.jsx("span",{className:"text-sm text-bambu-gray",children:"-"}),label_weight:({spool:t})=>r.jsx("span",{className:"text-sm text-white",children:au(t.label_weight)}),net:({remaining:t})=>r.jsx("span",{className:"text-sm text-white",children:au(t)}),gross:({spool:t,remaining:e})=>r.jsx("span",{className:"text-sm text-bambu-gray",children:au(e+t.core_weight)}),added_full:({spool:t})=>r.jsx("span",{className:"text-sm text-bambu-gray",children:t.added_full==null?"-":t.added_full?"Yes":"No"}),used:({spool:t})=>r.jsx("span",{className:"text-sm text-bambu-gray",children:t.weight_used>0?au(t.weight_used):"-"}),printed_total:()=>r.jsx("span",{className:"text-sm text-bambu-gray/50",children:"-"}),printed_since_weight:()=>r.jsx("span",{className:"text-sm text-bambu-gray/50",children:"-"}),note:({spool:t})=>r.jsx("span",{className:"text-sm text-bambu-gray max-w-[150px] truncate block",title:t.note||void 0,children:t.note||"-"}),pa_k:({spool:t})=>(t.k_profiles?.length??0)===0?r.jsx("span",{className:"text-sm text-bambu-gray",children:"-"}):r.jsx("span",{className:"inline-flex items-center px-1.5 py-0.5 rounded text-xs font-medium bg-bambu-green/20 text-bambu-green",children:"K"}),tag_id:({spool:t})=>{const e=t.tag_uid||t.tray_uuid;return e?r.jsx("span",{className:"text-sm text-bambu-gray font-mono",title:e,children:e.length>12?`${e.slice(0,6)}...${e.slice(-4)}`:e}):r.jsx("span",{className:"text-sm text-bambu-gray/50",children:"-"})},data_origin:({spool:t})=>r.jsx("span",{className:"text-sm text-bambu-gray",children:t.data_origin||"-"}),tag_type:({spool:t})=>r.jsx("span",{className:"text-sm text-bambu-gray",children:t.tag_type||"-"}),stock:({spool:t,t:e})=>t.slicer_filament?r.jsx("span",{className:"text-sm text-bambu-gray",children:"-"}):r.jsx("span",{className:"inline-flex items-center px-1.5 py-0.5 rounded text-xs font-medium bg-amber-500/20 text-amber-400",children:e("inventory.stock")}),remaining:({remaining:t,pct:e})=>r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("div",{className:"flex-1 h-2 bg-bambu-dark-tertiary rounded-full overflow-hidden",children:r.jsx("div",{className:`h-full rounded-full ${e>50?"bg-bambu-green":e>20?"bg-yellow-500":"bg-red-500"}`,style:{width:`${Math.min(e,100)}%`}})}),r.jsxs("span",{className:"text-xs text-bambu-gray min-w-[40px] text-right",children:[Math.round(t),"g"]})]}),spool_name:({spool:t,catalogMap:e})=>{const n=t.core_weight_catalog_id!=null?e[t.core_weight_catalog_id]:void 0;return r.jsx("span",{className:"text-sm text-bambu-gray",children:n?.name||"-"})},cost_per_kg:({spool:t,currencySymbol:e})=>r.jsx("span",{className:"text-sm text-bambu-gray",children:t.cost_per_kg!=null?`${e}${t.cost_per_kg.toFixed(2)}`:"-"}),weight_check:({spool:t,onSyncWeight:e})=>{const n=t.last_scale_weight;if(n==null)return r.jsx("span",{className:"text-sm text-bambu-gray/50",title:"No scale measurement",children:"-"});const a=t.core_weight||0,i=Math.max(0,t.label_weight-t.weight_used)+a;let s,o;n0?`+${Math.round(s)}`:`${Math.round(s)}`,c=o?`Scale: ${Math.round(n)}g Calculated: ${Math.round(i)}g Difference: ${l}g (within tolerance)`:`Scale: ${Math.round(n)}g Calculated: ${Math.round(i)}g diff --git a/static/index.html b/static/index.html index 25687109e..c7946a182 100644 --- a/static/index.html +++ b/static/index.html @@ -26,7 +26,7 @@ - +