From 32fcd858273968d9314dfb9e9fba990d7f39a48e Mon Sep 17 00:00:00 2001 From: maziggy Date: Sat, 23 May 2026 08:20:50 +0200 Subject: [PATCH] fix(library): "All Files" view now shows files inside subfolders (#1499) The File Manager sidebar's "All Files" entry was passing include_root=true to GET /library/files because the boolean was derived from `selectedFolderId === null`. The backend's include_root flag means *root files only* when folder_id is null, so a library where every file lived in a subfolder rendered as empty. Pass include_root=false from "All Files" so the backend returns every active file across folders. Adds a regression test that mounts the page, mocks the endpoint to distinguish include_root=true vs false, and asserts both a root file and a nested file appear. --- CHANGELOG.md | 1 + .../__tests__/pages/FileManagerPage.test.tsx | 51 +++++++++++++++++++ frontend/src/pages/FileManagerPage.tsx | 5 +- .../{index-BL4kzp1A.js => index-B5qvYtQq.js} | 2 +- static/index.html | 2 +- 5 files changed, 58 insertions(+), 3 deletions(-) rename static/assets/{index-BL4kzp1A.js => index-B5qvYtQq.js} (98%) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1166e1f51..ff2c361c6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -23,6 +23,7 @@ All notable changes to Bambuddy will be documented in this file. - **PyJWT CVE-2025-45768 (PYSEC-2025-183 / GHSA-65pc-fj4g-8rjx): permanently ignored in pip-audit** — Advisory is disputed by the PyJWT maintainers, with the advisory description literally noting *"this is disputed by the Supplier because the key length is chosen by the application that uses the library."* `fix_versions=[]` on the advisory confirms no PyJWT patch exists or will exist. Bambuddy is not affected: `backend/app/core/auth.py:184` auto-generates secrets via `secrets.token_urlsafe(64)` (~86 chars of entropy, far above any sane minimum) and the file-loaded path at `:177` rejects secrets shorter than 32 chars. Added a permanent `--ignore-vuln CVE-2025-45768` to `.github/workflows/security.yml` with an inline comment citing the file:line evidence so a future maintainer reviewing the ignore list sees why it's load-bearing. Also dropped the stale `--ignore-vuln CVE-2026-4539` for Pygments — Pygments has since shipped a patched version and the ignore is no longer load-bearing (verified: `pip-audit --ignore-vuln CVE-2025-45768` alone reports clean). ### Fixed +- **File Manager "All Files" view showed nothing when every file lived in a subfolder (#1499)** — The sidebar entry was meant to list every file across the library but instead returned only files at the library root, so a library with two folders and three files (all nested) appeared empty. Cause was an inverted boolean on the React Query call: `getLibraryFiles(selectedFolderId, selectedFolderId === null)` passed `include_root=true` for the "All Files" selection, which on the backend (`library.py` `list_files`) means *root files only* — the opposite of what the UI wanted. **Fix**: pass `include_root=false` for "All Files" so the backend returns every active file across folders (it remains a no-op when a specific folder is selected — `folder_id` takes precedence). A new vitest regression case renders the page with one root file and one nested file and asserts both appear, and that the request goes out with `include_root=false`. 48/48 FileManagerPage tests green; frontend build clean. - **Archive filament colour now reflects the assigned inventory spool, not the slicer's 3MF (#1494, reported by @IndividualGhost1905)** — A user added a `#000000` black filament to the built-in inventory, assigned it to the printer, and printed from the desktop slicer; the print, AMS and inventory all showed it as black and the correct spool's weight decremented — but the resulting archive (and the Color Distribution graph) showed `#161616`. Root cause is two independent colour sources: an archive's `filament_color` is parsed verbatim from the print job's 3MF (`archive.py` `_extract_filament_info` reads `filament_colour` from `project_settings.config`), which carries the *slicer's* filament-slot colour — a value the user picks separately from the exact hex they curate on the Bambuddy inventory spool. The two are "close but not equal" (slicer near-black `#161616` vs inventory `#000000`), which is exactly the "always a similar colour, never an unrelated one" pattern the report describes. **Fix**: once usage tracking has resolved the print's filament slots to inventory spools, the spool colours are authoritative — `_track_from_3mf` (built-in inventory) and `report_usage` (Spoolman mode) now overwrite the archive's `filament_color` with the slot-ordered, de-duplicated colours of the matched spools. The rewrite is **all-or-nothing**: it only applies when *every* used slot resolved to a spool that carries a colour, so a partially-mapped multi-colour print never silently loses the unmatched slots' colours (the 3MF value is kept). Shipped for both inventory modes in the same drop — built-in spools read `Spool.rgba`, Spoolman spools read the spool's `filament.color_hex` (fetched for tag-less slot-assignment matches). New helpers `_spool_color_to_hex` / `_archive_colors_from_spools` in `usage_tracker.py`, reused by `spoolman_tracking.py` via `_apply_spool_colors_to_archive`. **Tests**: 12 new in `test_usage_tracker.py` (hex normalisation, the all-or-nothing slot-colour rule across single/multi/partial/no-colour/AMS-fallback cases, and end-to-end that a `#000000` spool rewrites a `#161616` archive) + 4 in `test_spoolman_tracking.py` (the Spoolman-mode rewrite, empty/partial/missing-archive no-ops). 70 usage + Spoolman tracking tests green; backend ruff clean. - **Re-slicing across the single-nozzle / dual-nozzle boundary now fails fast with a clear message** — Re-slicing a model that was sliced for a single-nozzle printer (X1C, P1S, A1, …) onto a dual-nozzle printer (H2D / H2D Pro), or vice versa, produced a cryptic BambuStudio rejection — *"temperature difference of the filaments used is too large"* or *"G-code in unprintable area of multi-extruder printers"* — and an attempt at automatically converting the embedded single-nozzle layout segfaults the slicer CLI. Full cross-nozzle-class re-slicing isn't supported yet (it needs a proper dual-nozzle `project_settings` reconciliation — tracked separately). Until then, both slice routes (`POST /archives/{id}/slice`, `POST /library/files/{id}/slice`) now detect a nozzle-class mismatch up front and reject it synchronously with a `400` and a plain explanation, instead of letting the user wait for a confusing slicer failure. The guard is fail-open — it only fires when both the source's `sliced_for_model` and the target printer resolve to known models of *different* nozzle class; an un-sliced source (first-time slice) or an undeterminable target is never blocked. As part of this, the dual-nozzle model classification — previously an inline `("H2D", "H2D PRO", …)` tuple **duplicated across three call sites** (`start_print`, the two K-profile routes) — is centralized into `DUAL_NOZZLE_MODELS` + `is_dual_nozzle_model()` in `printer_models.py`, and all three sites plus the new guard now consume that single source of truth. **Tests**: `is_dual_nozzle_model` (H2D/Pro/internal-codes dual, X1C/P1S/A1/H2S single, None safe); `_canonical_printer_model` (strips the `"# "` clone prefix and `" 0.4 nozzle"` suffix); `guard_nozzle_class_reslice` (blocks single→dual and dual→single, allows same-class, no-ops on an un-sliced source); and an end-to-end test that an X1C archive re-sliced for an H2D preset returns `400` before any job is enqueued. 305 slicer/MQTT/K-profile tests + 31 slice-API + the printer-model suite all green; backend ruff clean. - **Sliced files no longer report "0 g" filament usage** — A slice result — and the re-sliced archive's card — showed `filament_used_g: 0` (and `0 mm`) even for a real multi-hour print, while the print time came through fine. Bambuddy reads filament totals from the slicer sidecar's `X-Filament-Used-G` / `X-Filament-Used-Mm` response headers, and some sidecar builds simply don't populate them. **Fix**: `ThreeMFParser._parse_gcode_header` now also reads the slicer's own totals — `; total filament weight [g] : …` and `; total filament length [mm] : …` — from the produced 3MF's G-code header (verified against a real sliced output: 126.26 g / 41661.4 mm extracted correctly). Both slice-persist paths (`slice_and_persist` for library files, `slice_and_persist_as_archive`) now fall back to those parsed totals when the sidecar header is 0, applying the corrected figure to the stored metadata, the archive's `filament_used_grams` column, and the slice response. The G-code-header read is a fallback only — `slice_info.config` still wins when it carries per-filament `used_g`. **Tests**: 2 new in `test_archive_service.py` (`_parse_gcode_header` extracts weight + length; absent header lines leave the keys unset). 36 archive-service + 23 slice-API tests green; backend ruff clean. diff --git a/frontend/src/__tests__/pages/FileManagerPage.test.tsx b/frontend/src/__tests__/pages/FileManagerPage.test.tsx index 09aa341f2..3bdda61da 100644 --- a/frontend/src/__tests__/pages/FileManagerPage.test.tsx +++ b/frontend/src/__tests__/pages/FileManagerPage.test.tsx @@ -932,4 +932,55 @@ describe('FileManagerPage', () => { expect(setItemMock).toHaveBeenCalledWith('library-collapse-folders', 'false'); }); }); + + describe('"All Files" view (#1499)', () => { + it('requests every file (include_root=false) so subfolder contents are visible', async () => { + const rootFile = { + id: 10, + filename: 'root-file.3mf', + file_path: '/library/root-file.3mf', + file_size: 1024, + file_type: '3mf', + folder_id: null, + thumbnail_path: null, + print_name: 'Root File', + print_time_seconds: 0, + print_count: 0, + duplicate_count: 0, + created_at: '2024-01-01T00:00:00Z', + }; + const nestedFile = { + ...rootFile, + id: 11, + filename: 'nested-file.3mf', + file_path: '/library/Functional Parts/nested-file.3mf', + folder_id: 1, + print_name: 'Nested File', + }; + + const includeRootValues: string[] = []; + server.use( + http.get('/api/v1/library/files', ({ request }) => { + const url = new URL(request.url); + const includeRoot = url.searchParams.get('include_root'); + includeRootValues.push(includeRoot ?? ''); + // Mirror the backend: include_root=false returns everything; true + // returns only files with folder_id IS NULL. + if (includeRoot === 'false') { + return HttpResponse.json([rootFile, nestedFile]); + } + return HttpResponse.json([rootFile]); + }), + ); + + render(); + + await waitFor(() => { + expect(screen.getByText('Root File')).toBeInTheDocument(); + expect(screen.getByText('Nested File')).toBeInTheDocument(); + }); + // Sanity-check: the buggy call would have sent include_root=true here. + expect(includeRootValues).toContain('false'); + }); + }); }); diff --git a/frontend/src/pages/FileManagerPage.tsx b/frontend/src/pages/FileManagerPage.tsx index 50362be75..5d9fc5ace 100644 --- a/frontend/src/pages/FileManagerPage.tsx +++ b/frontend/src/pages/FileManagerPage.tsx @@ -1049,7 +1049,10 @@ export function FileManagerPage() { const { data: files, isLoading: filesLoading } = useQuery({ queryKey: ['library-files', selectedFolderId], - queryFn: () => api.getLibraryFiles(selectedFolderId, selectedFolderId === null), + // "All Files" (selectedFolderId === null) lists every file across folders, + // so include_root must be false — true would scope the result to files at + // the library root only and hide everything nested in subfolders (#1499). + queryFn: () => api.getLibraryFiles(selectedFolderId, false), }); const { data: stats } = useQuery({ diff --git a/static/assets/index-BL4kzp1A.js b/static/assets/index-B5qvYtQq.js similarity index 98% rename from static/assets/index-BL4kzp1A.js rename to static/assets/index-B5qvYtQq.js index a35c836f3..ad3988c1d 100644 --- a/static/assets/index-BL4kzp1A.js +++ b/static/assets/index-B5qvYtQq.js @@ -8717,7 +8717,7 @@ Accuracy: ${t.time_accuracy.toFixed(0)}%`:t.actual_time_seconds?`Actual: ${hs(t. `+a+"]";if(typeof t=="object"){const n=Object.entries(t);return n.length===0?"{}":`{ `+n.map(([s,o])=>a+" "+JSON.stringify(s)+": "+iO(o,e+1)).join(`, `)+` -`+a+"}"}return String(t)}function jit({setting:t,onClose:e,onDeleted:a,onDuplicate:n,onEdit:i,hasPermission:s,t:o}){const{showToast:l}=na(),c=ta(),[d,u]=y.useState(!1),{data:m,isLoading:p}=Qe({queryKey:["cloudSettingDetail",t.setting_id],queryFn:()=>re.getCloudSettingDetail(t.setting_id)}),f=ot({mutationFn:()=>re.deleteCloudSetting(t.setting_id),onSuccess:()=>{l(o("profiles.presets.toast.deleted")),c.invalidateQueries({queryKey:["cloudSettings"]}),a()},onError:b=>l(b.message,"error")}),g=NS(t.setting_id),w=xU(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(Tt,{className:"w-full max-w-3xl max-h-[90vh] flex flex-col overflow-hidden",children:r.jsxs(Mt,{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($t,{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:iO(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(ba,{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(je,{variant:"secondary",onClick:()=>u(!1),disabled:f.isPending,className:"flex-1",children:o("common.cancel")}),r.jsxs(je,{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(ea,{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(je,{variant:"secondary",onClick:e,className:"flex-1",children:o("common.close")}),r.jsxs(je,{variant:"secondary",onClick:n,disabled:!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.presets.noDuplicatePermission"),children:[r.jsx(xi,{className:"w-4 h-4"}),o("profiles.presets.duplicate")]}),g&&r.jsxs(r.Fragment,{children:[r.jsxs(je,{variant:"secondary",onClick:i,disabled:p||!m||!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.presets.noEditPermission"),children:[r.jsx(yi,{className:"w-4 h-4"}),o("common.edit")]}),r.jsx(je,{variant:"danger",onClick:()=>u(!0),disabled:!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.presets.noDeletePermission"),children:r.jsx(ea,{className:"w-4 h-4"})})]})]})})]})})})}function ide(){try{const t=localStorage.getItem("bambusy_preset_templates");return t?JSON.parse(t):[]}catch{return[]}}function sde(t){localStorage.setItem("bambusy_preset_templates",JSON.stringify(t))}function Mit({onClose:t,onApply:e,t:a}){const{showToast:n}=na(),[i,s]=y.useState(ide),[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(O=>O.type===o),P=O=>{s(O),sde(O)},T=O=>{const L=i.filter(X=>X.id!==O);P(L),N(null),n(a("profiles.templates.toast.deleted"))},j=O=>{d(O.id),m(O.name),f(O.description),w(JSON.stringify(O.settings,null,2)),x(null)},F=()=>{if(!(!c||!u.trim()))try{const O=JSON.parse(g),L=i.map(X=>X.id===c?{...X,name:u.trim(),description:p.trim(),settings:O}:X);P(L),d(null),n(a("profiles.templates.toast.updated"))}catch(O){x(O.message)}},k=()=>{d(null),m(""),f(""),w("{}"),x(null)},M=O=>{const L=i.map(X=>X.id===O?{...X,showInModal:!X.showInModal}:X);P(L)},q={filament:{label:a("profiles.presets.types.filament"),icon:AT,color:"text-amber-400"},print:{label:a("profiles.presets.types.process"),icon:mu,color:"text-blue-400"},printer:{label:a("profiles.presets.types.printer"),icon:gr,color:"text-purple-400"}},I=S?i.find(O=>O.id===S):null;return y.useEffect(()=>{const O=L=>{L.key==="Escape"&&(S?N(null):c?k():t())};return window.addEventListener("keydown",O),()=>window.removeEventListener("keydown",O)},[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(Tt,{className:"w-full max-w-md",children:r.jsxs(Mt,{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(ba,{className:"w-6 h-6 text-red-400"})}),r.jsxs("div",{children:[r.jsx("h3",{className:"text-lg font-semibold text-white",children:a("profiles.templates.deleteTitle")}),r.jsx("p",{className:"text-sm text-bambu-gray",children:a("profiles.templates.deleteWarning")})]})]}),r.jsx("p",{className:"text-white mb-6",children:a("profiles.templates.deleteConfirm",{name:I.name})}),r.jsxs("div",{className:"flex gap-2",children:[r.jsx(je,{variant:"secondary",onClick:()=>N(null),className:"flex-1",children:a("common.cancel")}),r.jsxs(je,{onClick:()=>T(S),className:"flex-1 bg-red-500 hover:bg-red-600",children:[r.jsx(ea,{className:"w-4 h-4"}),a("common.delete")]})]})]})})}),r.jsx(Tt,{className:"w-full max-w-2xl max-h-[80vh] flex flex-col",children:r.jsxs(Mt,{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(Ig,{className:"w-5 h-5 text-amber-400"}),a("profiles.templates.title")]}),r.jsx("button",{onClick:t,className:"text-bambu-gray hover:text-white",children:r.jsx($t,{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:a("profiles.templates.typeFilter")}),["all","filament","print","printer"].map(O=>r.jsx("button",{onClick:()=>l(O),className:`px-3 py-1 text-sm rounded-lg transition-colors ${o===O?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:O==="all"?a("common.all"):q[O].label},O))]}),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(Ig,{className:"w-12 h-12 mx-auto mb-4 opacity-30"}),r.jsx("p",{children:a("profiles.templates.noTemplates")}),r.jsx("p",{className:"text-sm mt-1",children:a("profiles.templates.createFirst")})]}):r.jsx("div",{className:"space-y-2",children:C.map(O=>{const L=q[O.type],X=L.icon;return c===O.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:ee=>m(ee.target.value),placeholder:a("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:ee=>f(ee.target.value),placeholder:a("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:a("profiles.templates.settingsJson")}),r.jsx("textarea",{value:g,onChange:ee=>{w(ee.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(je,{size:"sm",onClick:F,disabled:!u.trim(),children:[r.jsx(fs,{className:"w-4 h-4"}),"Save"]}),r.jsx(je,{size:"sm",variant:"secondary",onClick:k,children:"Cancel"})]})]},O.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(X,{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:O.name}),r.jsx("p",{className:"text-xs text-bambu-gray truncate",children:O.description})]}),r.jsx("span",{className:"text-xs text-bambu-gray-dark px-2 py-1 bg-bambu-dark-secondary rounded",children:a("profiles.templates.fieldsCount",{count:Object.keys(O.settings).length})}),r.jsx("button",{onClick:()=>M(O.id),className:`p-1 transition-colors ${O.showInModal?"text-bambu-green hover:text-bambu-green/70":"text-bambu-gray hover:text-white"}`,title:O.showInModal?a("profiles.templates.shownInModals"):a("profiles.templates.hiddenInModals"),children:O.showInModal?r.jsx(Ml,{className:"w-4 h-4"}):r.jsx(db,{className:"w-4 h-4"})}),r.jsx("button",{onClick:()=>e(O),className:"px-3 py-1 text-xs bg-bambu-green/20 text-bambu-green rounded hover:bg-bambu-green/30 transition-colors",children:a("profiles.templates.apply")}),r.jsx("button",{onClick:()=>j(O),className:"p-1 text-bambu-gray hover:text-white",title:a("common.edit"),children:r.jsx(yi,{className:"w-4 h-4"})}),r.jsx("button",{onClick:()=>N(O.id),className:"p-1 text-bambu-gray hover:text-red-400",title:a("common.delete"),children:r.jsx(ea,{className:"w-4 h-4"})})]},O.id)})})})]})})]})}function ode({onClose:t,leftPreset:e,rightPreset:a,leftLabel:n,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(a)]),w=[];for(const b of g){if(b==="inherits"||b==="version")continue;const x=e[b],S=a[b],N=b in e,C=b in a;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,a]),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(Tt,{className:"w-full max-w-4xl max-h-[85vh] flex flex-col overflow-hidden",children:r.jsxs(Mt,{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(ry,{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($t,{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:n})]}),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(er,{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(lC,{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(rC,{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(gE,{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(fr,{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(gE,{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:n}),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(er,{className:"w-3.5 h-3.5 text-green-400"}),removed:r.jsx(lC,{className:"w-3.5 h-3.5 text-red-400"}),changed:r.jsx(rC,{className:"w-3.5 h-3.5 text-amber-400"}),same:r.jsx(gE,{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 Eit({onClose:t,initialData:e,allPresets:a,t:n}){const{showToast:i}=na(),s=ta(),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),[j,F]=y.useState(""),[k,M]=y.useState(!1),[q,I]=y.useState(""),[O,L]=y.useState(!1),[X,ee]=y.useState(ide),[Q,le]=y.useState(!1),[de,me]=y.useState(""),[Z,ce]=y.useState(""),[he,ue]=y.useState(!0),[xe,H]=y.useState(null),[J,A]=y.useState(!1),E=y.useMemo(()=>({filament:a.filament,print:a.process,printer:a.printer})[d]||[],[a,d]),B=y.useMemo(()=>E.filter(Re=>NS(Re.setting_id)),[E]),{data:W}=Qe({queryKey:["cloudFields",d],queryFn:()=>re.getCloudFields(d==="print"?"process":d),staleTime:1e3*60*60}),{data:z}=Qe({queryKey:["allPresetDetails",d,B.map(Re=>Re.setting_id).join(",")],queryFn:async()=>{const Re={};for(let Ue=0;Ue{try{const Ne=await re.getCloudSettingDetail(st.setting_id);return{id:st.setting_id,detail:Ne}}catch{return null}}))).forEach(st=>{st&&(Re[st.id]=st.detail)})}return Re},enabled:B.length>0,staleTime:1e3*60*10}),{data:ie,isLoading:U}=Qe({queryKey:["cloudSettingDetail",f],queryFn:()=>re.getCloudSettingDetail(f),enabled:!!f});y.useEffect(()=>{l!=="json"&&C(JSON.stringify(x,null,2))},[x,l]);const G=y.useMemo(()=>({filament:a.filament,print:a.process,printer:a.printer}[d]||[]).filter(Ke=>!NS(Ke.setting_id)).sort((Ke,Ue)=>Ke.name.localeCompare(Ue.name)),[a,d]);y.useEffect(()=>{if(!f)return;const Re=G.find(Ke=>Ke.setting_id===f);Re&&(b(Re.name),o||(S({inherits:Re.name}),C(JSON.stringify({inherits:Re.name},null,2))))},[f,G,o]);const K=y.useMemo(()=>{const Re=W?.fields||[],Ke=new Set(Re.map(st=>st.key)),Ue=new Set,lt=new Set(["inherits","updated_time","compatible_printers","compatible_prints"]);z&&Object.values(z).forEach(st=>{st?.setting&&Object.keys(st.setting).forEach(Ne=>{!Ke.has(Ne)&&!lt.has(Ne)&&Ue.add(Ne)})}),Object.keys(x).forEach(st=>{!Ke.has(st)&&!lt.has(st)&&Ue.add(st)});const Ee=Array.from(Ue).sort().map(st=>({key:st,label:st.replace(/_/g," ").replace(/\b\w/g,Ne=>Ne.toUpperCase()),type:"text",category:"discovered",description:n("profiles.presets.discoveredFromPresets")}));return[...Re,...Ee]},[W,z,x,n]),Y=K.filter(Re=>Re.label.toLowerCase().includes(j.toLowerCase())||Re.key.toLowerCase().includes(j.toLowerCase())),se=()=>{if(q.trim()){const Re=q.trim().toLowerCase().replace(/\s+/g,"_");oe(Re,""),I(""),L(!1),i(n("profiles.presets.toast.fieldAdded",{key:Re}))}},oe=(Re,Ke)=>{S(Ue=>{const lt={...Ue};return Ke===""||Ke===void 0?delete lt[Re]:lt[Re]=Ke,lt})},fe=Re=>{S(Ke=>({...Ke,...Re.settings})),H(Re.name),i(n("profiles.templates.toast.applied"))},ae=()=>{if(!de.trim())return;const Re={...x};if(delete Re.inherits,Object.keys(Re).length===0){i(n("profiles.presets.noOverridesToSave"),"error");return}const Ke={id:Date.now().toString(),name:de.trim(),description:Z.trim()||n("profiles.presets.customTemplate"),type:d,settings:Re,showInModal:he},Ue=[...X,Ke];ee(Ue),sde(Ue),le(!1),me(""),ce(""),ue(!0),i(n("profiles.templates.toast.created"))},pe=y.useMemo(()=>X.filter(Re=>Re.type===d&&Re.showInModal),[d,X]),$=Re=>{C(Re);try{const Ke=JSON.parse(Re);S(Ke),T(null)}catch(Ke){T(Ke.message)}},R=Re=>{Re.preventDefault(),M(!1);const Ke=Re.dataTransfer.files[0];if(Ke&&Ke.name.endsWith(".json")){const Ue=new FileReader;Ue.onload=lt=>{try{const Ee=lt.target?.result,st=JSON.parse(Ee),Ne=st.setting||st;S(Ze=>({...Ze,...Ne})),C(JSON.stringify({...x,...Ne},null,2)),i(n("profiles.presets.fileImported"))}catch{i(n("profiles.presets.invalidJsonFile"),"error")}},Ue.readAsText(Ke)}},ne=ot({mutationFn:()=>{const Re={...x},Ke=d==="filament"?"filament_settings_id":d==="print"?"print_settings_id":"printer_settings_id";Re[Ke]=`"${m}"`;const Ue={type:d,name:m,base_id:f,setting:Re};return re.createCloudSetting(Ue)},onSuccess:async()=>{i(n("profiles.presets.toast.created")),await s.refetchQueries({queryKey:["cloudSettings"]}),t()},onError:Re=>i(Re.message,"error")}),be=ot({mutationFn:()=>{if(!e?.setting_id)throw new Error(n("profiles.presets.noSettingId"));return re.updateCloudSetting(e.setting_id,{name:m,setting:x})},onSuccess:async()=>{i(n("profiles.presets.toast.updated")),s.removeQueries({queryKey:["cloudSettingDetail"]}),await s.refetchQueries({queryKey:["cloudSettings"]}),t()},onError:Re=>i(Re.message,"error")}),ve=o?be:ne,ke=ie?.setting?.inherits,ye=ke?G.find(Re=>Re.name===ke):void 0,{data:ge}=Qe({queryKey:["cloudSettingDetail",ye?.setting_id],queryFn:()=>re.getCloudSettingDetail(ye.setting_id),enabled:!!ye?.setting_id}),Me=y.useMemo(()=>{const Re=ge?.setting||{},Ke=ie?.setting||{},Ue=f&&z?.[f]?.setting?z[f].setting:{};return{...Re,...Ke,...Ue}},[f,ie,ge,z]),Be=Re=>{if(Re==null)return"";if(Array.isArray(Re)){const Ke=[...new Set(Re.map(Ue=>String(Ue)))];return Ke.length===1?Ke[0]:Re.join(", ")}return String(Re)},Le=Re=>{const Ke=x[Re.key],Ue=Me[Re.key],lt=Be(Ue),Ee=U?n("common.loading"):lt||"",st="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(Re.type==="boolean"){const Ne=Ke==="1"||Ke===void 0&&Ue==="1";return r.jsx("button",{type:"button",onClick:()=>oe(Re.key,Ke==="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 Re.type==="select"?r.jsxs("select",{value:Ke||"",onChange:Ne=>oe(Re.key,Ne.target.value),className:st,children:[r.jsx("option",{value:"",children:Ee}),Re.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:Re.type==="number"?"number":"text",value:Ke!==void 0?String(Ke):"",onChange:Ne=>oe(Re.key,Ne.target.value),step:Re.step,min:Re.min,max:Re.max,placeholder:Ee,className:st}),Re.unit&&r.jsx("span",{className:"text-xs text-bambu-gray whitespace-nowrap",children:Re.unit})]})},Oe=y.useMemo(()=>ie?.setting?ie.setting:{},[ie]);return r.jsxs("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",onDragOver:Re=>{Re.preventDefault(),M(!0)},onDragLeave:()=>M(!1),onDrop:R,children:[J&&f&&r.jsx(ode,{onClose:()=>A(!1),leftPreset:Oe,rightPreset:x,leftLabel:n("profiles.presets.baseLabel",{name:w||f}),rightLabel:n("profiles.presets.currentLabel",{name:m||n("profiles.presets.newPreset")}),t:n}),r.jsx(Tt,{className:"w-full max-w-6xl max-h-[90vh] flex flex-col overflow-y-auto",children:r.jsxs(Mt,{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:n(o?"profiles.presets.editPreset":e?"profiles.presets.duplicatePreset":"profiles.presets.createNewPreset")}),r.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:n("profiles.presets.customizeSettings")})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[f&&r.jsxs("button",{onClick:()=>A(!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:n("profiles.presets.compareWithBase"),children:[r.jsx(ry,{className:"w-4 h-4"}),n("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($t,{className:"w-5 h-5"})})]})]}),k&&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(Sn,{className:"w-12 h-12 text-bambu-green mx-auto mb-2"}),r.jsx("p",{className:"text-bambu-green font-medium",children:n("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:n("common.type")}),r.jsxs("select",{value:d,onChange:Re=>{u(Re.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:n("profiles.presets.types.filament")}),r.jsx("option",{value:"print",children:n("profiles.presets.types.process")}),r.jsx("option",{value:"printer",children:n("profiles.presets.types.printer")})]})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("profiles.presets.basePreset")}),r.jsxs("select",{value:f,onChange:Re=>g(Re.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:n("profiles.presets.selectBasePreset")}),G.map(Re=>r.jsx("option",{value:Re.setting_id,children:Re.name},Re.setting_id))]})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("profiles.presets.presetName")}),r.jsx("input",{type:"text",value:m,onChange:Re=>p(Re.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",placeholder:n("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(kr,{className:"w-3 h-3 text-bambu-green"}),n("profiles.presets.inheritsFrom")," ",r.jsx("span",{className:"text-white",children:w}),U&&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(w8,{className:"w-4 h-4"}),n("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(FS,{className:"w-4 h-4"}),n("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(Zy,{className:"w-4 h-4"}),"JSON",P&&r.jsx(qn,{className:"w-3 h-3 text-red-400"})]}),r.jsx("div",{className:"flex-1 max-[640px]:hidden"}),r.jsxs("button",{onClick:()=>{const Re={name:m,type:d,base_id:f,setting:x},Ke=new Blob([JSON.stringify(Re,null,2)],{type:"application/json"}),Ue=URL.createObjectURL(Ke),lt=document.createElement("a");lt.href=Ue,lt.download=`${m||"preset"}.json`,document.body.appendChild(lt),lt.click(),document.body.removeChild(lt),URL.revokeObjectURL(Ue),i(n("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:n("profiles.presets.exportToJson"),children:[r.jsx(Ur,{className:"w-4 h-4"}),n("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:n("profiles.presets.importFromJson"),children:[r.jsx(Sn,{className:"w-4 h-4"}),n("common.upload")]}),r.jsx("input",{id:"file-import",type:"file",accept:".json",className:"hidden",onChange:Re=>{const Ke=Re.target.files?.[0];if(Ke){const Ue=new FileReader;Ue.onload=lt=>{try{const Ee=JSON.parse(lt.target?.result),st=Ee.setting||Ee;S(Ne=>({...Ne,...st})),i(n("profiles.presets.fileImported"))}catch{i(n("profiles.presets.invalidJson"),"error")}},Ue.readAsText(Ke)}}})]}),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(Ig,{className:"w-4 h-4 text-amber-400"}),n("profiles.templates.title")]}),Object.keys(x).filter(Re=>Re!=="inherits").length>0&&r.jsxs("button",{onClick:()=>le(!Q),className:"text-xs text-bambu-gray hover:text-white flex items-center gap-1 transition-colors",children:[r.jsx(fs,{className:"w-3 h-3"}),n("profiles.presets.saveAsTemplate")]})]}),Q&&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:de,onChange:Re=>me(Re.target.value),placeholder:n("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:Z,onChange:Re=>ce(Re.target.value),placeholder:n("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(je,{size:"sm",onClick:ae,disabled:!de.trim(),children:[r.jsx(fs,{className:"w-3 h-3"}),n("common.save")]}),r.jsx(je,{size:"sm",variant:"secondary",onClick:()=>le(!1),children:n("common.cancel")})]}),r.jsxs("button",{onClick:()=>ue(!he),className:`flex items-center gap-1.5 text-xs transition-colors ${he?"text-bambu-green":"text-bambu-gray hover:text-white"}`,children:[he?r.jsx(Ml,{className:"w-3.5 h-3.5"}):r.jsx(db,{className:"w-3.5 h-3.5"}),n(he?"profiles.templates.shownInModals":"profiles.templates.hiddenInModals")]})]})]}),xe&&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(kr,{className:"w-4 h-4 text-bambu-green"}),r.jsxs("span",{className:"text-sm text-bambu-green",children:[n("profiles.presets.templateApplied")," ",r.jsx("span",{className:"font-medium",children:xe})]}),r.jsx("button",{onClick:()=>H(null),className:"ml-auto text-bambu-green/70 hover:text-bambu-green",children:r.jsx($t,{className:"w-4 h-4"})})]}),r.jsxs("div",{className:"grid grid-cols-3 gap-2",children:[pe.map(Re=>r.jsxs("button",{onClick:()=>fe(Re),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:Re.name}),r.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:Re.description})]},Re.id)),pe.length===0&&r.jsx("p",{className:"col-span-3 text-center text-bambu-gray text-sm py-4",children:n("profiles.presets.noTemplatesSelected")})]}),r.jsx("p",{className:"text-xs text-bambu-gray-dark mt-2 text-center",children:n("profiles.presets.manageTemplatesHint")})]}),r.jsxs("div",{children:[r.jsx("h3",{className:"text-sm font-medium text-white mb-3",children:n("profiles.presets.commonSettings")}),r.jsx("div",{className:"grid grid-cols-2 gap-x-6 gap-y-3",children:K.slice(0,10).map(Re=>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:Re.label}),r.jsx("div",{className:"w-48 max-[640px]:w-full",children:Le(Re)})]},Re.key))})]}),Object.keys(x).length>1&&r.jsxs("div",{children:[r.jsx("h3",{className:"text-sm font-medium text-white mb-3",children:n("profiles.presets.currentOverrides")}),r.jsx("div",{className:"flex flex-wrap gap-2",children:Object.entries(x).filter(([Re])=>Re!=="inherits").map(([Re,Ke])=>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:[Re,": ",String(Ke).slice(0,20),r.jsx("button",{onClick:()=>oe(Re,void 0),className:"hover:text-white",children:r.jsx($t,{className:"w-3 h-3"})})]},Re))})]})]}),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:n("profiles.presets.availableFields")}),r.jsx("span",{className:"text-xs text-bambu-gray",children:z?n("profiles.templates.fieldsCount",{count:K.length}):n("common.loading")})]}),r.jsxs("div",{className:"relative mb-3 flex-shrink-0",children:[r.jsx(fr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),r.jsx("input",{type:"text",value:j,onChange:Re=>F(Re.target.value),placeholder:n("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:[Y.filter(Re=>!(Re.key in x)).map(Re=>{const Ke=Me[Re.key],Ue=Be(Ke);return r.jsxs("div",{onClick:()=>{S(lt=>({...lt,[Re.key]:Ue||""}))},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:Re.label}),r.jsx("p",{className:"text-xs text-bambu-gray-dark truncate",children:Re.key})]}),r.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[Ue&&r.jsxs("span",{className:"text-xs text-bambu-gray bg-bambu-dark px-2 py-0.5 rounded max-w-32 truncate",title:Ue,children:[Ue.slice(0,20),Ue.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(er,{className:"w-4 h-4 text-bambu-gray group-hover:text-bambu-green transition-colors"})})]})]},Re.key)}),Y.filter(Re=>!(Re.key in x)).length===0&&r.jsx("p",{className:"text-center text-bambu-gray py-4 text-sm",children:n(j?"profiles.presets.noMatchingFields":"profiles.presets.allFieldsAdded")})]}),r.jsx("div",{className:"pt-3 mt-3 border-t border-bambu-dark-tertiary flex-shrink-0",children:O?r.jsxs("div",{className:"flex gap-2",children:[r.jsx("input",{type:"text",value:q,onChange:Re=>I(Re.target.value),onKeyDown:Re=>Re.key==="Enter"&&se(),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(je,{size:"sm",onClick:se,disabled:!q.trim(),children:r.jsx(er,{className:"w-4 h-4"})}),r.jsx(je,{size:"sm",variant:"secondary",onClick:()=>{L(!1),I("")},children:r.jsx($t,{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(er,{className:"w-4 h-4"}),n("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:n("profiles.presets.yourOverrides")}),r.jsx("span",{className:"text-xs text-bambu-gray",children:n("profiles.templates.fieldsCount",{count:Object.keys(x).filter(Re=>Re!=="inherits").length})})]}),r.jsxs("div",{className:"flex-1 overflow-y-auto space-y-2 pr-2 min-h-0",children:[Object.entries(x).filter(([Re])=>Re!=="inherits").map(([Re,Ke])=>{const Ue=K.find(lt=>lt.key===Re);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:Ue?.label||Re}),r.jsx("p",{className:"text-xs text-bambu-gray-dark",children:Re})]}),r.jsx("button",{onClick:()=>oe(Re,void 0),className:"p-1 text-bambu-gray hover:text-red-400 transition-colors",children:r.jsx($t,{className:"w-4 h-4"})})]}),Ue?Le(Ue):r.jsx("input",{type:"text",value:String(Ke),onChange:lt=>oe(Re,lt.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"})]},Re)}),Object.keys(x).filter(Re=>Re!=="inherits").length===0&&r.jsxs("div",{className:"text-center py-8 text-bambu-gray",children:[r.jsx(w8,{className:"w-8 h-8 mx-auto mb-2 opacity-50"}),r.jsx("p",{className:"text-sm",children:n("profiles.presets.noOverridesYet")}),r.jsx("p",{className:"text-xs mt-1",children:n("profiles.presets.clickFieldsToAdd")})]})]}),Object.keys(x).filter(Re=>Re!=="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:()=>{le(!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(fs,{className:"w-4 h-4"}),n("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(qn,{className:"w-4 h-4"}),P]}),r.jsx("textarea",{value:N,onChange:Re=>$(Re.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:n("profiles.presets.jsonTip")})]})]}),r.jsxs("div",{className:"p-4 border-t border-bambu-dark-tertiary flex gap-2",children:[r.jsx(je,{variant:"secondary",onClick:t,className:"flex-1",children:n("common.cancel")}),r.jsxs(je,{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(fs,{className:"w-4 h-4"}):r.jsx(er,{className:"w-4 h-4"}),n(o?"common.save":e?"common.duplicate":"common.create")]})]})]})})]})}function Dit({settings:t,lastSyncTime:e,onRefresh:a,isRefreshing:n,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),[j,F]=y.useState(!1),[k,M]=y.useState(!1),[q,I]=y.useState(null),[O,L]=y.useState(null),[X,ee]=y.useState(null),[Q,le]=y.useState(!1),[de,me]=y.useState([null,null]),[Z,ce]=y.useState(!1),[he,ue]=y.useState(null),xe=ta(),H=y.useMemo(()=>[...t.filament.map(se=>({...se,type:"filament"})),...t.printer.map(se=>({...se,type:"printer"})),...t.process.map(se=>({...se,type:"process"}))].map(se=>({...se,meta:xU(se.name)})),[t]),J=y.useMemo(()=>{const Y=new Set,se=new Set,oe=new Set;return H.forEach(fe=>{fe.meta.nozzle&&Y.add(fe.meta.nozzle),fe.meta.filamentType&&se.add(fe.meta.filamentType),fe.meta.layerHeight&&oe.add(fe.meta.layerHeight)}),{printers:i.map(fe=>({id:fe.id.toString(),name:fe.name})),nozzles:Array.from(Y).sort((fe,ae)=>parseFloat(fe)-parseFloat(ae)),filaments:Array.from(se).sort(),layerHeights:Array.from(oe).sort((fe,ae)=>parseFloat(fe)-parseFloat(ae))}},[H,i]),A=y.useMemo(()=>f==="all"?null:i.find(se=>se.id.toString()===f)?.model||null,[f,i]),E=y.useMemo(()=>H.filter(Y=>d==="all"||Y.type===d).filter(Y=>{if(m==="all")return!0;const se=NS(Y.setting_id);return m==="custom"?se:!se}).filter(Y=>{if(f==="all"||!A)return!0;const se=Y.meta.printer?.toLowerCase()||"",oe=A.toLowerCase();return se.includes(oe)||oe.includes(se)}).filter(Y=>w==="all"||Y.meta.nozzle===w).filter(Y=>x==="all"||Y.meta.filamentType===x).filter(Y=>N==="all"||Y.meta.layerHeight===N).filter(Y=>l===""||Y.name.toLowerCase().includes(l.toLowerCase())).sort((Y,se)=>Y.name.localeCompare(se.name)),[H,d,m,f,A,w,x,N,l]),B=Y=>{if(Q){const se=de[0]?.setting_id===Y.setting_id,oe=de[1]?.setting_id===Y.setting_id;if(se)me([de[1],null]);else if(oe)me([de[0],null]);else if(!de[0])me([Y,null]);else if(de[1]){if(de[0].type!==Y.type)return;me([de[0],Y])}else{if(de[0].type!==Y.type)return;me([de[0],Y])}}else T(Y)},W=Y=>{if(de[0]?.setting_id===Y.setting_id)return 0;if(de[1]?.setting_id===Y.setting_id)return 1},z=async Y=>{try{const se=await re.getCloudSettingDetail(Y.setting_id),oe=Y.type==="process"?"print":Y.type;I({type:oe,name:Y.name,base_id:se.base_id||"GFSA00",setting:se.setting||{}}),T(null)}catch(se){console.error("Failed to fetch preset details for duplication:",se)}},ie=async Y=>{try{xe.removeQueries({queryKey:["cloudSettingDetail",Y.setting_id]});const se=await re.getCloudSettingDetail(Y.setting_id),oe=Y.type==="process"?"print":Y.type;L({type:oe,name:Y.name,base_id:se.base_id||"GFSA00",setting:se.setting||{},setting_id:Y.setting_id}),T(null)}catch(se){console.error("Failed to fetch preset details for editing:",se)}},U=()=>{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(fr,{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:Y=>c(Y.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(je,{variant:Q?"primary":"secondary",onClick:()=>{Q?(le(!1),me([null,null])):le(!0)},children:[r.jsx(ry,{className:"w-4 h-4"}),o(Q?"common.cancel":"profiles.presets.compare")]}),r.jsxs(je,{variant:"secondary",onClick:()=>M(!0),disabled:!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.cloudView.noTemplatesPermission"),children:[r.jsx(Ig,{className:"w-4 h-4"}),o("profiles.cloudView.templates")]}),r.jsxs(je,{variant:"secondary",onClick:a,disabled:n||!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.cloudView.noRefreshPermission"),children:[r.jsx(Xa,{className:`w-4 h-4 ${n?"animate-spin":""}`}),o("profiles.cloudView.refresh")]}),r.jsxs(je,{onClick:()=>F(!0),disabled:!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.cloudView.noCreatePermission"),children:[r.jsx(er,{className:"w-4 h-4"}),o("profiles.cloudView.newPreset")]})]})]}),r.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[r.jsx(jS,{className:"w-4 h-4 text-bambu-gray"}),r.jsx(zx,{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:Y=>u(Y)}),r.jsx(zx,{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:Y=>p(Y)}),J.printers.length>0&&r.jsx(zx,{label:o("profiles.cloudView.filters.printer"),value:f,options:[{value:"all",label:o("profiles.cloudView.filters.all")},...J.printers.map(Y=>({value:Y.id,label:Y.name}))],onChange:g}),J.nozzles.length>0&&r.jsx(zx,{label:o("profiles.cloudView.filters.nozzle"),value:w,options:[{value:"all",label:o("profiles.cloudView.filters.all")},...J.nozzles.map(Y=>({value:Y,label:Y}))],onChange:b}),J.filaments.length>0&&(d==="all"||d==="filament")&&r.jsx(zx,{label:o("profiles.cloudView.filters.filament"),value:x,options:[{value:"all",label:o("profiles.cloudView.filters.all")},...J.filaments.map(Y=>({value:Y,label:Y}))],onChange:S}),J.layerHeights.length>0&&(d==="all"||d==="process")&&r.jsx(zx,{label:o("profiles.cloudView.filters.layer"),value:N,options:[{value:"all",label:o("profiles.cloudView.filters.all")},...J.layerHeights.map(Y=>({value:Y,label:Y}))],onChange:C}),G&&r.jsx("button",{onClick:U,className:"px-3 py-2 text-sm text-bambu-gray hover:text-white transition-colors",children:o("profiles.cloudView.clearFilters")})]})]}),Q&&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(ry,{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:de[0]?o("profiles.cloudView.selectAnotherPreset",{type:de[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] ${de[0]?"bg-blue-500/30 text-blue-700 dark:text-blue-300":"bg-bambu-dark text-bambu-gray"}`,children:de[0]?de[0].name:o("profiles.cloudView.selectFirst")}),r.jsx(rC,{className:"w-4 h-4 text-bambu-gray"}),r.jsx("span",{className:`px-2 py-1 text-sm rounded truncate max-w-[200px] ${de[1]?"bg-blue-500/30 text-blue-700 dark:text-blue-300":"bg-bambu-dark text-bambu-gray"}`,children:de[1]?de[1].name:o("profiles.cloudView.selectSecond")})]}),de[0]&&de[1]&&r.jsxs(je,{size:"sm",onClick:async()=>{try{const[Y,se]=await Promise.all([re.getCloudSettingDetail(de[0].setting_id),re.getCloudSettingDetail(de[1].setting_id)]);ue([Y.setting||{},se.setting||{}]),ce(!0)}catch{}},children:[r.jsx(ry,{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(Za,{className:"w-3 h-3"}),o("profiles.cloudView.lastSynced")," ",Fh(e.toISOString(),"system",o)]}),r.jsx("span",{children:o("profiles.cloudView.showingCount",{showing:E.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")]})]})]}),E.length===0?r.jsxs("div",{className:"text-center py-16",children:[r.jsx(cn,{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:U,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(AT,{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:["(",E.filter(Y=>Y.type==="filament").length,")"]})]}),r.jsxs("div",{className:"space-y-1 max-h-[calc(100vh-320px)] overflow-y-auto pr-1",children:[E.filter(Y=>Y.type==="filament").map(Y=>r.jsx(k3,{setting:Y,onClick:()=>B(Y),onDuplicate:()=>z(Y),compareMode:Q,isCompareSelected:W(Y)!==void 0,compareIndex:W(Y),compareDisabled:Q&&!!de[0]&&de[0].type!==Y.type,t:o},Y.setting_id)),E.filter(Y=>Y.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(mu,{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:["(",E.filter(Y=>Y.type==="process").length,")"]})]}),r.jsxs("div",{className:"space-y-1 max-h-[calc(100vh-320px)] overflow-y-auto pr-1",children:[E.filter(Y=>Y.type==="process").map(Y=>r.jsx(k3,{setting:Y,onClick:()=>B(Y),onDuplicate:()=>z(Y),compareMode:Q,isCompareSelected:W(Y)!==void 0,compareIndex:W(Y),compareDisabled:Q&&!!de[0]&&de[0].type!==Y.type,t:o},Y.setting_id)),E.filter(Y=>Y.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(gr,{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:["(",E.filter(Y=>Y.type==="printer").length,")"]})]}),r.jsxs("div",{className:"space-y-1 max-h-[calc(100vh-320px)] overflow-y-auto pr-1",children:[E.filter(Y=>Y.type==="printer").map(Y=>r.jsx(k3,{setting:Y,onClick:()=>B(Y),onDuplicate:()=>z(Y),compareMode:Q,isCompareSelected:W(Y)!==void 0,compareIndex:W(Y),compareDisabled:Q&&!!de[0]&&de[0].type!==Y.type,t:o},Y.setting_id)),E.filter(Y=>Y.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(jit,{setting:P,onClose:()=>T(null),onDeleted:()=>T(null),onDuplicate:()=>z(P),onEdit:()=>ie(P),hasPermission:s,t:o}),(j||q||O||X)&&r.jsx(Eit,{onClose:()=>{F(!1),I(null),L(null),ee(null)},initialData:O||q||(X?{type:X.type,name:"",base_id:"",setting:X.setting}:void 0),allPresets:t,t:o}),k&&r.jsx(Mit,{onClose:()=>M(!1),onApply:Y=>{ee({type:Y.type,setting:Y.settings}),M(!1)},t:o}),Z&&he&&de[0]&&de[1]&&r.jsx(ode,{onClose:()=>{ce(!1),ue(null)},leftPreset:he[0],rightPreset:he[1],leftLabel:de[0].name,rightLabel:de[1].name,t:o})]})}function Fit(){const{t}=vt(),e=ta(),{showToast:a}=na(),{hasPermission:n}=dr(),[i,s]=y.useState("cloud"),[o,l]=y.useState(),{data:c,isLoading:d}=Qe({queryKey:["cloudStatus"],queryFn:re.getCloudStatus}),{data:u=[]}=Qe({queryKey:["printers"],queryFn:re.getPrinters}),{data:m,isLoading:p,refetch:f,dataUpdatedAt:g}=Qe({queryKey:["cloudSettings"],queryFn:()=>re.getCloudSettings(),enabled:!!c?.is_authenticated,retry:!1,staleTime:1e3*60*5});y.useEffect(()=>{g&&l(new Date(g))},[g]);const w=ot({mutationFn:re.cloudLogout,onSuccess:()=>{e.invalidateQueries({queryKey:["cloudStatus"]}),e.removeQueries({queryKey:["cloudSettings"]}),a(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(Gh,{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(Gh,{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(ub,{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(MS,{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(je,{variant:"secondary",size:"sm",onClick:()=>w.mutate(),disabled:w.isPending||!n("cloud:auth"),title:n("cloud:auth")?void 0:t("profiles.noLogoutPermission"),children:[r.jsx(ny,{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(Dit,{settings:m,lastSyncTime:o,onRefresh:()=>f(),isRefreshing:p,printers:u,hasPermission:n,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(je,{onClick:()=>f(),children:t("profiles.retry")})]}):r.jsx(Tit,{onSuccess:b,t})]}),i==="local"&&r.jsx(Pit,{}),i==="kprofiles"&&r.jsx(kit,{}),r.jsx(Ait,{})]})}function Lit(t,e){const a=(e||"").toUpperCase().replace(/[- ]/g,""),n=a.includes("X1"),i=a.includes("P1"),s=a.includes("A1MINI"),o=a.includes("A1")&&!s,l=a.includes("H2D"),c=a.includes("H2C"),d=a.includes("H2S"),u=l||c||d,m=a.includes("P2S"),p=a.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 n||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 n?"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 n||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 n||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 J0={Droplet:AT,Flame:xm,Ruler:Tye,Sparkles:Ig,Square:lo,Cable:NO,Wrench:Zm,Calendar:vn,Timer:Xd,Cog:du,Fan:GZ,Zap:Nc,Wind:sJ,Thermometer:zS,Layers:cn,Box:Mi,Target:aJ,RefreshCw:Xa,Settings:vy,Filter:jS,CircleDot:Mge};function Cw(t){return t&&J0[t]||Zm}function Ux(t,e,a){if(e==="days"){if(t<1)return a?a("common.today"):"Today";if(t===1)return a?a("maintenance.day"):"1 day";if(t<7){const i=Math.round(t);return a?a("maintenance.days",{count:i}):`${i} days`}if(t<180){const i=Math.round(t/7);return i===1?a?a("maintenance.week"):"1 week":a?a("maintenance.weeks",{count:i}):`${i} weeks`}const n=Math.round(t/30);return n===1?a?a("maintenance.month"):"1 month":a?a("maintenance.months",{count:n}):`${n} 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 n=t/24;if(n<7)return`${n<2?n.toFixed(1):Math.round(n)}d`;const i=n/7;return i<12?`${i<2?i.toFixed(1):Math.round(i)}w`:`${Math.round(i/4)}mo`}}function _3(t,e,a){return e==="days"?t===1?a?a("maintenance.day"):"1 day":t===7?a?a("maintenance.week"):"1 week":t===14?a?a("maintenance.weeks",{count:2}):"2 weeks":t===30?a?a("maintenance.month"):"1 month":t===60?a?a("maintenance.months",{count:2}):"2 months":t===90?a?a("maintenance.months",{count:3}):"3 months":t===180?a?a("maintenance.months",{count:6}):"6 months":t===365?a?a("maintenance.year"):"1 year":a?a("maintenance.days",{count:t}):`${t} days`:`${t}h`}function Rit({item:t,onPerform:e,onToggle:a,hasPermission:n,t:i}){const s=Cw(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:Ux(Math.abs(f),"days",i)}):t.is_warning?i("maintenance.dueIn",{duration:Ux(f,"days",i)}):i("maintenance.timeLeft",{duration:Ux(f,"days",i)})}else return t.is_due?i("maintenance.overdueBy",{duration:Ux(Math.abs(t.hours_until_due),"hours",i)}):t.is_warning?i("maintenance.dueIn",{duration:Ux(t.hours_until_due,"hours",i)}):i("maintenance.timeLeft",{duration:Ux(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(vn,{className:"w-3.5 h-3.5 text-bambu-gray shrink-0"})}),(()=>{const f=t.maintenance_type_wiki_url||Lit(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(Mr,{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(ba,{className:"w-3 h-3"}),t.is_warning&&!t.is_due&&r.jsx(Za,{className:"w-3 h-3"}),!t.is_due&&!t.is_warning&&t.enabled&&r.jsx(kr,{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:n("maintenance:update")?void 0:i("maintenance.noPermissionUpdate"),children:r.jsx(ja,{checked:t.enabled,onChange:f=>a(t.id,f),disabled:!n("maintenance:update")})}),r.jsxs(je,{size:"sm",variant:t.is_due?"primary":"secondary",onClick:()=>e(t.id),disabled:!t.enabled||!n("maintenance:update"),title:n("maintenance:update")?void 0:i("maintenance.noPermissionPerform"),className:"!px-3",children:[r.jsx(vs,{className:"w-3.5 h-3.5"}),i("common.reset")]})]})]})})}function Iit({overview:t,onPerform:e,onToggle:a,onSetHours:n,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&&(n(t.printer_id,w),d(!1))};return r.jsxs(Tt,{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(ba,{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(Za,{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(kr,{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(al,{className:"w-4 h-4"}):r.jsx(Da,{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(je,{size:"sm",onClick:g,children:s("common.save")}),r.jsx(je,{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(Rg,{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=Cw(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(Mt,{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(Rit,{item:w,onPerform:e,onToggle:a,hasPermission:i,t:s},w.id))})})]})}function Oit({overview:t,types:e,onUpdateInterval:a,onAddType:n,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,j]=y.useState("100"),[F,k]=y.useState("hours"),[M,q]=y.useState("Wrench"),[I,O]=y.useState(""),[L,X]=y.useState(new Set),[ee,Q]=y.useState(null),[le,de]=y.useState(null),me=y.useMemo(()=>t?t.map($=>({id:$.printer_id,name:$.printer_name})):[],[t]),Z=$=>t?t.filter(R=>R.maintenance_items.some(ne=>ne.maintenance_type_id===$)).map(R=>({printerId:R.printer_id,printerName:R.printer_name,itemId:R.maintenance_items.find(ne=>ne.maintenance_type_id===$)?.id})):[],ce=$=>{if(!t)return[];const R=new Set(Z($).map(ne=>ne.printerId));return me.filter(ne=>!R.has(ne.id))},[he,ue]=y.useState(null),[xe,H]=y.useState(""),[J,A]=y.useState(""),[E,B]=y.useState("hours"),[W,z]=y.useState("Wrench"),[ie,U]=y.useState(""),G=$=>{ue($),H($.name),A($.default_interval_hours.toString()),B($.interval_type||"hours"),z($.icon||"Wrench"),U($.wiki_url||"")},K=()=>{he&&xe.trim()&&parseFloat(J)>0&&(i(he.id,{name:xe.trim(),default_interval_hours:parseFloat(J),interval_type:E,icon:W,wiki_url:ie.trim()||null}),ue(null))},Y=($,R,ne)=>{const be=parseFloat(g);if(!isNaN(be)&&be>0){const ve=Math.abs(be-R)<.01?null:be;a($,{custom_interval_hours:ve,custom_interval_type:b!==ne?b:null})}f(null)},se=$=>{$.preventDefault(),C.trim()&&parseFloat(T)>0&&L.size>0&&(n({name:C.trim(),default_interval_hours:parseFloat(T),interval_type:F,icon:M,wiki_url:I.trim()||null},Array.from(L)),P(""),j("100"),k("hours"),O(""),X(new Set),N(!1))},oe=$=>{X(R=>{const ne=new Set(R);return ne.has($)?ne.delete($):ne.add($),ne})},fe=t?.map($=>({printerId:$.printer_id,printerName:$.printer_name,items:$.maintenance_items.sort((R,ne)=>R.maintenance_type_id-ne.maintenance_type_id)})).sort(($,R)=>$.printerName.localeCompare(R.printerName))||[],ae=e.filter($=>$.is_system),pe=e.filter($=>!$.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(je,{variant:"secondary",onClick:o,disabled:!u("maintenance:delete")||l,title:u("maintenance:delete")?void 0:m("maintenance.noPermissionDeleteTypes"),children:m("maintenance.restoreDefaults")}),r.jsxs(je,{onClick:()=>N(!S),disabled:!u("maintenance:create"),title:u("maintenance:create")?void 0:m("maintenance.noPermissionEditTypes"),children:[r.jsx(er,{className:"w-4 h-4"}),m("maintenance.addCustomType")]})]})]}),S&&r.jsx(Tt,{className:"mb-6",children:r.jsx(Mt,{className:"py-4",children:r.jsxs("form",{onSubmit:se,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:$=>P($.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:$=>{k($.target.value),$.target.value==="days"?j("30"):j("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:$=>j($.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(J0).map($=>{const R=J0[$];return r.jsx("button",{type:"button",onClick:()=>q($),className:`p-2 rounded-lg transition-colors ${M===$?"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"})},$)})})]})}),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:$=>O($.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:me.map($=>r.jsx("button",{type:"button",onClick:()=>oe($.id),className:`px-3 py-1.5 rounded-lg text-sm transition-colors ${L.has($.id)?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary"}`,children:$.name},$.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(je,{type:"button",variant:"secondary",onClick:()=>{N(!1),X(new Set)},children:m("common.cancel")}),r.jsx(je,{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:[ae.map($=>{const R=Cw($.icon),ne=$.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:$.name}),r.jsxs("div",{className:"text-xs text-bambu-gray mt-0.5 flex items-center gap-1",children:[ne==="days"?r.jsx(vn,{className:"w-3 h-3"}):r.jsx(Xd,{className:"w-3 h-3"}),_3($.default_interval_hours,ne,m)]})]}),r.jsx("button",{onClick:()=>{u("maintenance:delete")&&de($)},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(ea,{className:"w-4 h-4"})})]})},$.id)}),pe.map($=>{const R=Cw($.icon),ne=$.interval_type||"hours";if(he?.id===$.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:xe,onChange:ge=>H(ge.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:E,onChange:ge=>B(ge.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:J,onChange:ge=>A(ge.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(J0).map(ge=>{const Me=J0[ge];return r.jsx("button",{type:"button",onClick:()=>z(ge),className:`p-1.5 rounded transition-colors ${W===ge?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:r.jsx(Me,{className:"w-3.5 h-3.5"})},ge)})}),r.jsx("input",{type:"url",value:ie,onChange:ge=>U(ge.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(je,{size:"sm",onClick:K,disabled:!xe.trim(),children:m("common.save")}),r.jsx(je,{size:"sm",variant:"secondary",onClick:()=>ue(null),children:m("common.cancel")})]})]})},$.id);const ve=Z($.id),ke=ce($.id),ye=ee===$.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:$.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(vn,{className:"w-3 h-3"}):r.jsx(Xd,{className:"w-3 h-3"}),_3($.default_interval_hours,ne,m)]})]}),r.jsxs("button",{onClick:()=>Q(ye?null:$.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(gr,{className:"w-3 h-3"}),r.jsx("span",{className:"text-xs font-medium",children:ve.length}),r.jsx(Da,{className:`w-3 h-3 transition-transform ${ye?"rotate-180":""}`})]}),r.jsx("button",{onClick:()=>G($),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(Rg,{className:"w-4 h-4"})}),r.jsx("button",{onClick:()=>{confirm(m("maintenance.deleteTypeConfirm",{name:$.name}))&&s($.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(ea,{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(ge=>r.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-1 bg-bambu-dark rounded text-xs text-white",children:[ge.printerName,r.jsx("button",{onClick:()=>ge.itemId&&d(ge.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:"×"})]},ge.printerId))}),ke.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")}),ke.map(ge=>r.jsxs("button",{onClick:()=>c(ge.id,$.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:["+ ",ge.name]},ge.id))]})]})]},$.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($=>r.jsx(Tt,{children:r.jsxs(Mt,{className:"py-4",children:[r.jsx("h3",{className:"text-sm font-medium text-white mb-3",children:$.printerName}),r.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-2",children:$.items.map(R=>{const ne=Cw(R.maintenance_type_icon),be=e.find(Me=>Me.id===R.maintenance_type_id),ve=be?.default_interval_hours||R.interval_hours,ke=be?.interval_type||"hours",ye=R.interval_type||"hours",ge=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}),ge?r.jsxs("div",{className:"flex items-center gap-1",children:[b==="days"?r.jsx(vn,{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:Me=>x(Me.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:Me=>w(Me.target.value),onKeyDown:Me=>{Me.key==="Enter"&&Y(R.id,ve,ke),Me.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(je,{size:"sm",onClick:()=>Y(R.id,ve,ke),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(vn,{className:"w-3 h-3"}):r.jsx(Xd,{className:"w-3 h-3"}),_3(R.interval_hours,ye,m),r.jsx(Rg,{className:"w-3 h-3 text-bambu-gray"})]})]},R.id)})})]})},$.printerId))})]}),fe.length===0&&r.jsx(Tt,{children:r.jsxs(Mt,{className:"text-center py-12",children:[r.jsx(Za,{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")})]})}),le&&r.jsx(wa,{title:m("maintenance.deleteSystemTypeTitle"),message:m("maintenance.deleteSystemTypeMessage",{name:le.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(le.id),de(null)},onCancel:()=>de(null)})]})}function zit(){const{t}=vt(),e=ta(),{showToast:a}=na(),{hasPermission:n}=dr(),[i,s]=y.useState("status"),{data:o,isLoading:l}=Qe({queryKey:["maintenanceOverview"],queryFn:re.getMaintenanceOverview}),{data:c}=Qe({queryKey:["maintenanceTypes"],queryFn:re.getMaintenanceTypes}),d=ot({mutationFn:({id:T,notes:j})=>re.performMaintenance(T,j),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]}),e.invalidateQueries({queryKey:["maintenanceSummary"]}),a(t("maintenance.maintenanceComplete"))},onError:T=>{a(T.message,"error")}}),u=ot({mutationFn:({id:T,data:j})=>re.updateMaintenanceItem(T,j),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]})},onError:T=>{a(T.message,"error")}}),m=ot({mutationFn:({id:T,data:j})=>re.updateMaintenanceType(T,j),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceTypes"]}),e.invalidateQueries({queryKey:["maintenanceOverview"]}),a(t("maintenance.typeUpdated"))},onError:T=>{a(T.message,"error")}}),p=ot({mutationFn:re.deleteMaintenanceType,onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceTypes"]}),e.invalidateQueries({queryKey:["maintenanceOverview"]}),a(t("maintenance.typeDeleted"))},onError:T=>{a(T.message,"error")}}),f=ot({mutationFn:re.restoreDefaultMaintenanceTypes,onSuccess:T=>{e.invalidateQueries({queryKey:["maintenanceTypes"]}),e.invalidateQueries({queryKey:["maintenanceOverview"]}),a(t("maintenance.defaultsRestored",{count:T.restored}))},onError:T=>{a(T.message,"error")}}),g=ot({mutationFn:({printerId:T,hours:j})=>re.setPrinterHours(T,j),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]}),e.invalidateQueries({queryKey:["maintenanceSummary"]}),a(t("maintenance.printHoursUpdated"))},onError:T=>{a(T.message,"error")}}),w=ot({mutationFn:({printerId:T,typeId:j})=>re.assignMaintenanceType(T,j),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]}),a(t("maintenance.printerAssigned"))},onError:T=>{a(T.message,"error")}}),b=ot({mutationFn:re.removeMaintenanceItem,onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]}),a(t("maintenance.printerRemoved"))},onError:T=>{a(T.message,"error")}}),x=T=>{d.mutate({id:T})},S=(T,j)=>{u.mutate({id:T,data:{enabled:j}})},N=(T,j)=>{g.mutate({printerId:T,hours:j})};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,j)=>T+j.due_count,0)||0,P=o?.reduce((T,j)=>T+j.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(Zm,{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,j)=>{const F=T.due_count*10+T.warning_count,k=j.due_count*10+j.warning_count;return F!==k?k-F:T.printer_name.localeCompare(j.printer_name)}).map(T=>r.jsx(Iit,{overview:T,onPerform:x,onToggle:S,onSetHours:N,hasPermission:n,t},T.printer_id)):r.jsx(Tt,{children:r.jsxs(Mt,{className:"text-center py-16",children:[r.jsx(Zm,{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(Oit,{overview:o,types:c||[],onUpdateInterval:(T,j)=>u.mutate({id:T,data:j}),onAddType:async(T,j)=>{const F=await re.createMaintenanceType(T);for(const k of j)await re.assignMaintenanceType(k,F.id);e.invalidateQueries({queryKey:["maintenanceTypes"]}),e.invalidateQueries({queryKey:["maintenanceOverview"]}),a(t("maintenance.typeUpdated"))},onUpdateType:(T,j)=>m.mutate({id:T,data:j}),onDeleteType:T=>p.mutate(T),onRestoreDefaults:()=>f.mutate(),isRestoringDefaults:f.isPending,onAssignType:(T,j)=>w.mutate({printerId:T,typeId:j}),onRemoveItem:T=>b.mutate(T),hasPermission:n,t})]})}const AX=["#ef4444","#f97316","#eab308","#22c55e","#06b6d4","#3b82f6","#8b5cf6","#ec4899","#6b7280"];function lde({project:t,onClose:e,onSave:a,isLoading:n,currencySymbol:i,t:s}){const[o,l]=y.useState(t?.name||""),[c,d]=y.useState(t?.description||""),[u,m]=y.useState(t?.color||AX[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,j]=y.useState(t?.priority||"normal"),[F,k]=y.useState(t?.budget?.toString()||""),[M,q]=y.useState(t?.url||""),[I,O]=y.useState(null),L=ta(),[X,ee]=y.useState(t?.cover_image_filename||null),Q=y.useRef(null),[le,de]=y.useState(!1),[me,Z]=y.useState(0),ce=async xe=>{const H=xe.target.files?.[0];if(!(!H||!t)){de(!0);try{const J=await re.uploadProjectCoverImage(t.id,H);ee(J.filename),Z(A=>A+1),L.invalidateQueries({queryKey:["projects"]})}catch{}finally{de(!1),Q.current&&(Q.current.value="")}}},he=async()=>{if(t){de(!0);try{await re.deleteProjectCoverImage(t.id),ee(null),Z(xe=>xe+1),L.invalidateQueries({queryKey:["projects"]})}finally{de(!1)}}},ue=xe=>{xe.preventDefault();const H=M.trim();if(H&&!/^https?:\/\//i.test(H)){O(s("projects.urlInvalid"));return}O(null),a({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?H||null:H||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:ue,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:xe=>l(xe.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:xe=>d(xe.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:M,onChange:xe=>{q(xe.target.value),I&&O(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:X?r.jsx("img",{src:`${re.getProjectCoverImageUrl(t.id)}?v=${me}`,alt:s("projects.coverImageAlt"),className:"w-full h-full object-cover"}):r.jsx(uu,{className:"w-6 h-6 text-bambu-gray"})}),r.jsxs("div",{className:"flex flex-col gap-2",children:[r.jsx("input",{ref:Q,type:"file",accept:"image/jpeg,image/png,image/gif,image/webp",onChange:ce,className:"hidden"}),r.jsxs(je,{type:"button",variant:"secondary",onClick:()=>Q.current?.click(),disabled:le,children:[le?r.jsx(pt,{className:"w-4 h-4 animate-spin"}):r.jsx(Sn,{className:"w-4 h-4 mr-1"}),s(X?"projects.coverImageReplace":"projects.coverImageUpload")]}),X&&r.jsxs(je,{type:"button",variant:"secondary",onClick:he,disabled:le,children:[r.jsx($t,{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:AX.map(xe=>r.jsx("button",{type:"button",onClick:()=>m(xe),className:`w-8 h-8 rounded-full transition-transform ${u===xe?"ring-2 ring-white ring-offset-2 ring-offset-bambu-dark-secondary scale-110":""}`,style:{backgroundColor:xe}},xe))})]}),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:xe=>f(xe.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:xe=>w(xe.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:xe=>N(xe.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:xe=>P(xe.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:xe=>j(xe.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:xe=>k(xe.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:xe=>x(xe.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(je,{type:"button",variant:"secondary",onClick:e,children:s("common.cancel")}),r.jsx(je,{type:"submit",disabled:!o.trim()||n,children:n?r.jsx(pt,{className:"w-4 h-4 animate-spin"}):s(t?"common.save":"projects.create")})]})]})]})})}function Uit({projectId:t,altText:e}){const a=y.useRef(null),[n,i]=y.useState(!1),[s,o]=y.useState(null),l=()=>{if(!a.current)return;const d=a.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:a,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:re.getProjectCoverImageUrl(t),alt:e,className:"w-full h-full object-cover",loading:"lazy"})}),n&&s&&pc.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:re.getProjectCoverImageUrl(t),alt:"",className:"w-full h-full object-contain",loading:"lazy"})}),document.body)]})}function Bit({project:t,onClick:e,onEdit:a,onDelete:n,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:ro,color:"text-bambu-green",bg:"bg-bambu-green/10"}:d?{icon:io,color:"text-bambu-gray",bg:"bg-bambu-gray/10"}:t.queue_count>0?{icon:Za,color:"text-blue-400",bg:"bg-blue-400/10"}:{icon:so,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(Uit,{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(Mr,{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(Nm,{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")&&(a(),m(!1))},disabled:!i("projects:update"),title:i("projects:update")?void 0:s("projects.noEditPermission"),children:[r.jsx(Rg,{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")&&(n(),m(!1))},disabled:!i("projects:delete"),title:i("projects:delete")?void 0:s("projects.noDeletePermission"),children:[r.jsx(ea,{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(io,{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(ba,{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(Za,{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:re.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(qr,{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(ba,{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(cn,{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(qr,{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(ba,{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(tL,{className:"w-3.5 h-3.5"}),r.jsx("span",{children:t.queue_count})]})]}),r.jsx(Hn,{className:"w-4 h-4 text-bambu-gray/50 group-hover:text-bambu-gray transition-colors"})]})]})]})}function qit(){const{t}=vt(),e=Oi(),a=ta(),{showToast:n}=na(),{hasPermission:i}=dr(),[s,o]=y.useState(!1),[l,c]=y.useState(),[d,u]=y.useState("active"),[m,p]=y.useState(null),{data:f}=Qe({queryKey:["settings"],queryFn:re.getSettings}),g=Go(f?.currency||"USD"),{data:w,isLoading:b}=Qe({queryKey:["projects",d==="all"?void 0:d],queryFn:()=>re.getProjects(d==="all"?void 0:d)}),x=ot({mutationFn:X=>re.createProject(X),onSuccess:()=>{a.invalidateQueries({queryKey:["projects"]}),o(!1),n(t("projects.toast.created"),"success")},onError:X=>{n(X.message,"error")}}),S=ot({mutationFn:({id:X,data:ee})=>re.updateProject(X,ee),onSuccess:()=>{a.invalidateQueries({queryKey:["projects"]}),o(!1),c(void 0),n(t("projects.toast.updated"),"success")},onError:X=>{n(X.message,"error")}}),N=ot({mutationFn:X=>re.deleteProject(X),onSuccess:()=>{p(null),n(t("projects.toast.deleted"),"success"),setTimeout(()=>window.location.reload(),100)},onError:X=>{p(null),n(X.message,"error")}}),C=ot({mutationFn:X=>re.importProject(X),onSuccess:()=>{a.invalidateQueries({queryKey:["projects"]}),n(t("projects.toast.imported"),"success")},onError:X=>{n(X.message,"error")}}),P=y.useRef(null),T=async()=>{try{const X=await re.getProjects(),ee=await Promise.all(X.map(async me=>await re.exportProjectJson(me.id))),Q=new Blob([JSON.stringify(ee,null,2)],{type:"application/json"}),le=URL.createObjectURL(Q),de=document.createElement("a");de.href=le,de.download=`bambuddy_projects_${new Date().toISOString().split("T")[0]}.json`,de.click(),URL.revokeObjectURL(le),n(t("projects.toast.exported"),"success")}catch(X){n(X.message,"error")}},j=()=>{P.current?.click()},F=async X=>{const ee=X.target.files?.[0];if(ee){try{if(ee.name.toLowerCase().endsWith(".zip"))await re.importProjectFile(ee),a.invalidateQueries({queryKey:["projects"]}),n(t("projects.toast.imported"),"success");else{const le=await ee.text(),de=JSON.parse(le),me=Array.isArray(de)?de:[de];for(const Z of me)await C.mutateAsync(Z);me.length>1&&n(t("projects.toast.multipleImported",{count:me.length}),"success")}}catch(Q){n(`${t("projects.toast.importFailed")}: ${Q.message}`,"error")}X.target.value=""}},k=X=>{l?S.mutate({id:l.id,data:X}):x.mutate(X)},M=X=>{c(X),o(!0)},q=X=>{e(`/projects/${X.id}`)},I=X=>{p(X)},O=()=>{m!==null&&N.mutate(m)},L=w?.reduce((X,ee)=>(X[ee.status]=(X[ee.status]||0)+1,X.all=(X.all||0)+1,X),{})||{};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(so,{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(je,{variant:"secondary",onClick:j,disabled:!i("projects:create"),title:i("projects:create")?t("projects.importProject"):t("projects.noImportPermission"),children:[r.jsx(Sn,{className:"w-4 h-4 mr-2"}),t("projects.import")]}),r.jsxs(je,{variant:"secondary",onClick:T,disabled:!i("projects:read"),title:i("projects:read")?t("projects.exportAll"):t("projects.noExportPermission"),children:[r.jsx(Ur,{className:"w-4 h-4 mr-2"}),t("projects.export")]}),r.jsxs(je,{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(er,{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:Za},{key:"completed",label:t("projects.statusCompleted"),icon:ro},{key:"archived",label:t("projects.statusArchived"),icon:io},{key:"all",label:t("common.all"),icon:so}].map(({key:X,label:ee,icon:Q})=>r.jsxs("button",{onClick:()=>u(X),className:`flex items-center gap-2 px-4 py-2 text-sm rounded-lg transition-all ${d===X?"bg-bambu-card text-white shadow-sm":"text-bambu-gray hover:text-white"}`,children:[r.jsx(Q,{className:"w-4 h-4"}),r.jsx("span",{children:ee}),L[X]>0&&r.jsx("span",{className:`text-xs px-1.5 py-0.5 rounded-full ${d===X?"bg-bambu-green/20 text-bambu-green":"bg-bambu-dark-tertiary"}`,children:L[X]})]},X))}),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(so,{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(je,{onClick:()=>o(!0),disabled:!i("projects:create"),title:i("projects:create")?void 0:t("projects.noCreatePermission"),children:[r.jsx(er,{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(X=>r.jsx(Bit,{project:X,onClick:()=>q(X),onEdit:()=>M(X),onDelete:()=>I(X.id),hasPermission:i,t},X.id))}),m!==null&&r.jsx(wa,{title:t("projects.deleteProject"),message:t("projects.deleteConfirm"),confirmText:t("projects.deleteProject"),variant:"danger",onConfirm:O,onCancel:()=>p(null)}),s&&r.jsx(lde,{project:l,onClose:()=>{o(!1),c(void 0)},onSave:k,isLoading:x.isPending||S.isPending,currencySymbol:g,t})]})}function Hit(t){const e=t.toLowerCase();return e.endsWith(".gcode")||e.endsWith(".gcode.3mf")}function $it(t){return t>=1e3?`${(t/1e3).toFixed(2)}kg`:`${Math.round(t)}g`}function Vit({status:t,t:e}){const a={active:"bg-bambu-green/20 text-bambu-green",completed:"bg-blue-500/20 text-blue-400",archived:"bg-bambu-gray/20 text-bambu-gray"},n=a[t]||a.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 ${n}`,children:i[t]||t.charAt(0).toUpperCase()+t.slice(1)})}function jX({icon:t,label:e,value:a,subValue:n,hint:i,color:s="text-bambu-gray"}){return r.jsx(Tt,{children:r.jsx(Mt,{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:a}),n&&r.jsx("p",{className:"text-xs text-bambu-gray/70",children:n})]})]})})})}function Git({archives:t,t:e}){return t.length===0?r.jsxs("div",{className:"text-center py-8 text-bambu-gray",children:[r.jsx(qr,{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(a=>r.jsxs(Is,{to:`/archives?search=${encodeURIComponent(a.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:[a.thumbnail_path?r.jsx("img",{src:re.getArchiveThumbnail(a.id),alt:a.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(qr,{className:"w-8 h-8"})}),a.status==="failed"&&r.jsx("div",{className:"absolute inset-0 bg-red-500/30 flex items-center justify-center",children:r.jsx(jr,{className:"w-8 h-8 text-white"})}),a.status==="completed"&&r.jsx("div",{className:"absolute top-1 right-1",children:r.jsx(hr,{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:a.print_name||"Unknown"})})]},a.id))})}function Wit({priority:t,t:e}){const a={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:n,label:i}=a[t]||a.normal;return r.jsxs("span",{className:`px-2 py-1 rounded text-xs font-medium flex items-center gap-1 ${n}`,children:[t==="urgent"&&r.jsx(ba,{className:"w-3 h-3"}),i]})}function N3(t,e){if(!t)return null;const a=Qa(t);if(!a)return null;const n=new Date,i=Math.ceil((a.getTime()-n.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 Kit(){const{id:t}=TS(),e=Oi(),{t:a}=vt(),n=ta(),{showToast:i}=na(),{hasPermission:s}=dr(),[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}=Qe({queryKey:["project",b],queryFn:()=>re.getProject(b),enabled:b>0}),{data:C,isLoading:P}=Qe({queryKey:["project-archives",b],queryFn:()=>re.getProjectArchives(b),enabled:b>0}),{data:T,isLoading:j}=Qe({queryKey:["project-bom",b],queryFn:()=>re.getProjectBOM(b),enabled:b>0}),{data:F,isLoading:k}=Qe({queryKey:["project-timeline",b],queryFn:()=>re.getProjectTimeline(b,20),enabled:b>0}),{data:M}=Qe({queryKey:["settings"],queryFn:re.getSettings}),{data:q}=Qe({queryKey:["project-folders",b],queryFn:()=>re.getLibraryFoldersByProject(b),enabled:b>0}),{data:I,isLoading:O}=Qe({queryKey:["project-files",b],queryFn:()=>re.getLibraryFiles(null,!1,b),enabled:b>0}),L=y.useMemo(()=>{const Te=new Map;for(const Fe of I??[])if(Fe.folder_id!=null){const et=Te.get(Fe.folder_id)??[];et.push(Fe),Te.set(Fe.folder_id,et)}return Te},[I]),X=Go(M?.currency||"USD"),ee=M?.time_format||"system",Q=ot({mutationFn:Te=>re.updateProject(b,Te),onSuccess:()=>{n.invalidateQueries({queryKey:["project",b]}),n.invalidateQueries({queryKey:["projects"]}),l(!1),d(!1),i(a("projectDetail.toast.projectUpdated"),"success")},onError:Te=>{i(Te.message,"error")}}),le=()=>{m(x?.notes||""),d(!0)},de=()=>{Q.mutate({notes:u})},me=()=>{d(!1),m("")},[Z,ce]=y.useState(""),[he,ue]=y.useState(1),[xe,H]=y.useState(""),[J,A]=y.useState(""),[E,B]=y.useState(""),[W,z]=y.useState(!1),[ie,U]=y.useState(!1),[G,K]=y.useState(null),[Y,se]=y.useState(""),[oe,fe]=y.useState(1),[ae,pe]=y.useState(""),[$,R]=y.useState(""),[ne,be]=y.useState(""),[ve,ke]=y.useState({isOpen:!1,title:"",message:"",onConfirm:()=>{}}),ye=ot({mutationFn:Te=>re.createBOMItem(b,Te),onSuccess:()=>{n.invalidateQueries({queryKey:["project-bom",b]}),n.invalidateQueries({queryKey:["project",b]}),ce(""),ue(1),H(""),A(""),B(""),z(!1),i(a("projectDetail.toast.partAdded"),"success")},onError:Te=>i(Te.message,"error")}),ge=ot({mutationFn:({itemId:Te,data:Fe})=>re.updateBOMItem(b,Te,Fe),onSuccess:()=>{n.invalidateQueries({queryKey:["project-bom",b]}),n.invalidateQueries({queryKey:["project",b]}),K(null)},onError:Te=>i(Te.message,"error")}),Me=ot({mutationFn:Te=>re.deleteBOMItem(b,Te),onSuccess:()=>{n.invalidateQueries({queryKey:["project-bom",b]}),n.invalidateQueries({queryKey:["project",b]}),i(a("projectDetail.toast.partRemoved"),"success")},onError:Te=>i(Te.message,"error")}),Be=Te=>{Te.preventDefault(),Z.trim()&&ye.mutate({name:Z.trim(),quantity_needed:he,unit_price:xe?parseFloat(xe):void 0,sourcing_url:J.trim()||void 0,remarks:E.trim()||void 0})},Le=Te=>{const Fe=Te.is_complete?0:Te.quantity_needed;ge.mutate({itemId:Te.id,data:{quantity_acquired:Fe}})},Oe=(Te,Fe)=>{ke({isOpen:!0,title:a("projectDetail.bom.deletePart"),message:a("projectDetail.bom.deleteConfirm",{name:Fe}),onConfirm:()=>{ke(et=>({...et,isOpen:!1})),Me.mutate(Te)}})},Re=Te=>{K(Te),se(Te.name),fe(Te.quantity_needed),pe(Te.unit_price?.toString()||""),R(Te.sourcing_url||""),be(Te.remarks||"")},Ke=Te=>{Te.preventDefault(),!(!G||!Y.trim())&&ge.mutate({itemId:G.id,data:{name:Y.trim(),quantity_needed:oe,unit_price:ae?parseFloat(ae):void 0,sourcing_url:$.trim()||void 0,remarks:ne.trim()||void 0}})},Ue=()=>{K(null)},lt=async()=>{try{const{blob:Te,filename:Fe}=await re.exportProjectZip(Number(b)),et=URL.createObjectURL(Te),We=document.createElement("a");We.href=et,We.download=Fe||`${x?.name||"project"}_${new Date().toISOString().split("T")[0]}.zip`,We.click(),URL.revokeObjectURL(et),i(a("projectDetail.toast.projectExported"),"success")}catch(Te){i(Te.message,"error")}},Ee=ot({mutationFn:()=>re.createTemplateFromProject(b),onSuccess:()=>{n.invalidateQueries({queryKey:["projects"]}),i(a("projectDetail.toast.templateCreated"),"success")},onError:Te=>i(Te.message,"error")}),st=Te=>Ug(Te,ee,{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?`${a("common.error")}: ${N.message}`:a("projectDetail.notFound")}),r.jsx(je,{variant:"secondary",className:"mt-4",onClick:()=>e("/projects"),children:a("projectDetail.backToProjects")})]});const Ne=x.stats,Ze=Ne?.progress_percent??0,Ye=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:a("nav.projects")}),r.jsx(Hn,{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(PT,{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(Vit,{status:x.status,t:a})]}),r.jsxs("div",{className:"flex gap-2",children:[r.jsxs(je,{variant:"secondary",onClick:lt,disabled:!s("projects:read"),title:s("projects:read")?a("projectDetail.exportProject"):a("projectDetail.noExportPermission"),children:[r.jsx(Ur,{className:"w-4 h-4 mr-2"}),a("projectDetail.export")]}),r.jsxs(je,{onClick:()=>l(!0),disabled:!s("projects:update"),title:s("projects:update")?void 0:a("projectDetail.noEditPermission"),children:[r.jsx(Rg,{className:"w-4 h-4 mr-2"}),a("common.edit")]})]})]}),(x.target_count||x.target_parts_count)&&r.jsx(Tt,{children:r.jsxs(Mt,{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:a("projectDetail.progress.platesProgress")}),r.jsxs("span",{className:"text-sm font-medium text-white",children:[Ne?.total_archives||0," / ",x.target_count," ",a("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(Ze,100)}%`,backgroundColor:Ze>=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:a("projectDetail.progress.percentComplete",{percent:Ze.toFixed(0)})}),Ne?.remaining_prints!=null&&Ne.remaining_prints>0&&r.jsx("span",{className:"text-xs text-bambu-gray/70",children:a("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:a("projectDetail.progress.partsProgress")}),r.jsxs("span",{className:"text-sm font-medium text-white",children:[Ne?.completed_prints||0," / ",x.target_parts_count," ",a("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(Ye,100)}%`,backgroundColor:Ye>=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:a("projectDetail.progress.percentComplete",{percent:Ye.toFixed(0)})}),Ne?.remaining_parts!=null&&Ne.remaining_parts>0&&r.jsx("span",{className:"text-xs text-bambu-gray/70",children:a("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(Tt,{children:r.jsx(Mt,{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(qr,{className:"w-5 h-5"})}),r.jsxs("div",{children:[r.jsx("p",{className:"text-sm text-bambu-gray",children:a("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:a("projectDetail.stats.total")})]}),Ne.failed_prints>0&&r.jsx("p",{className:"text-sm text-status-error",children:a("projectDetail.stats.failed",{count:Ne.failed_prints})}),r.jsx("p",{className:"text-sm text-bambu-gray",children:a("projectDetail.stats.partsPrinted",{count:Ne.completed_prints})})]})]})})}),r.jsx(jX,{icon:Za,label:a("projectDetail.stats.printTime"),value:g0e(Ne.total_print_time_hours),color:"text-yellow-400"}),r.jsx(jX,{icon:gr,label:a("projectDetail.stats.filamentUsed"),value:$it(Ne.total_filament_grams),color:"text-purple-400"})]}),Ne&&(()=>{const Te=Ne.estimated_cost+Ne.total_energy_cost+Ne.bom_cost;return Ne.estimated_cost>0||Te>0||x.budget!==null})()&&r.jsx(Tt,{children:r.jsxs(Mt,{className:"p-4",children:[r.jsx("h2",{className:"text-lg font-semibold text-white mb-3",children:a("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:a("projectDetail.cost.filamentCost")}),r.jsxs("p",{className:"text-lg font-semibold text-white",children:[X,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:a("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:["(",X,Ne.total_energy_cost.toFixed(2),")"]})]})]}),(()=>{const Te=Ne.estimated_cost+Ne.total_energy_cost+Ne.bom_cost;return Te<=0?null:r.jsxs("div",{children:[r.jsx("p",{className:"text-xs text-bambu-gray uppercase",children:a("projectDetail.cost.totalCost")}),r.jsxs("p",{className:"text-lg font-semibold text-bambu-green",children:[X,Te.toFixed(2)]}),Ne.bom_cost>0&&r.jsx("p",{className:"text-xs text-bambu-gray/70",children:a("projectDetail.cost.includesBom")})]})})(),x.budget!==null&&(()=>{const Te=Ne.estimated_cost+Ne.total_energy_cost+Ne.bom_cost,Fe=x.budget-Te;return r.jsxs("div",{children:[r.jsx("p",{className:"text-xs text-bambu-gray uppercase",children:a("projectDetail.cost.budget")}),r.jsxs("p",{className:"text-sm text-bambu-gray",children:[a("projectDetail.cost.total"),": ",r.jsxs("span",{className:"text-white font-semibold",children:[X,x.budget.toFixed(2)]})]}),r.jsxs("p",{className:`text-sm ${Fe>=0?"text-bambu-green":"text-red-400"}`,children:[a("projectDetail.cost.remaining"),": ",r.jsxs("span",{className:"font-semibold",children:[X,Fe.toFixed(2)]})]})]})})()]})]})}),x.children&&x.children.length>0&&r.jsx(Tt,{children:r.jsxs(Mt,{className:"p-4",children:[r.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2 mb-3",children:[r.jsx(Hbe,{className:"w-5 h-5"}),a("projectDetail.subProjects.title",{count:x.children.length})]}),r.jsx("div",{className:"space-y-2",children:x.children.map(Te=>r.jsxs(Is,{to:`/projects/${Te.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:Te.color||"#6b7280"}}),r.jsx("span",{className:"text-white",children:Te.name}),r.jsx("span",{className:`text-xs px-2 py-0.5 rounded ${Te.status==="completed"?"bg-status-ok/20 text-status-ok":Te.status==="archived"?"bg-bambu-gray/20 text-bambu-gray":"bg-blue-500/20 text-blue-400"}`,children:Te.status})]}),Te.progress_percent!==null&&r.jsxs("span",{className:"text-sm text-bambu-gray",children:[Te.progress_percent.toFixed(0),"%"]})]},Te.id))})]})}),x.parent_id&&x.parent_name&&r.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[r.jsx(cn,{className:"w-4 h-4 text-bambu-gray"}),r.jsx("span",{className:"text-bambu-gray",children:a("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:a("projectDetail.priorityLabel")}),r.jsx(Wit,{priority:x.priority,t:a})]}),x.due_date&&r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(vn,{className:"w-4 h-4 text-bambu-gray"}),r.jsx("span",{className:"text-sm text-white",children:zg(x.due_date,{year:"numeric",month:"short",day:"numeric"})}),N3(x.due_date,a)&&r.jsxs("span",{className:`text-xs ${N3(x.due_date,a).color}`,children:["(",N3(x.due_date,a).label,")"]})]}),x.tags&&r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(Ym,{className:"w-4 h-4 text-bambu-gray"}),r.jsx("div",{className:"flex flex-wrap gap-1",children:x.tags.split(",").map((Te,Fe)=>r.jsx("span",{className:"px-2 py-0.5 bg-bambu-dark-tertiary text-bambu-gray text-xs rounded",children:Te.trim()},Fe))})]})]}),r.jsx(Tt,{children:r.jsxs(Mt,{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"}),a("projectDetail.notes.title")]}),c?r.jsxs("div",{className:"flex gap-2",children:[r.jsxs(je,{variant:"secondary",size:"sm",onClick:me,disabled:Q.isPending,children:[r.jsx($t,{className:"w-4 h-4 mr-1"}),a("common.cancel")]}),r.jsxs(je,{size:"sm",onClick:de,disabled:Q.isPending,children:[Q.isPending?r.jsx(pt,{className:"w-4 h-4 animate-spin mr-1"}):r.jsx(fs,{className:"w-4 h-4 mr-1"}),a("common.save")]})]}):r.jsxs(je,{variant:"secondary",size:"sm",onClick:le,disabled:!s("projects:update"),title:s("projects:update")?void 0:a("projectDetail.notes.noEditPermission"),children:[r.jsx(Rg,{className:"w-4 h-4 mr-1"}),a("common.edit")]})]}),c?r.jsx(XI,{content:u,onChange:m,placeholder:a("projectDetail.notes.placeholder")}):x.notes?r.jsx("div",{className:"prose prose-invert prose-sm max-w-none",dangerouslySetInnerHTML:{__html:k5.sanitize(x.notes)}}):r.jsx("p",{className:"text-bambu-gray/70 text-sm italic",children:a("projectDetail.notes.empty")})]})}),r.jsx(Tt,{children:r.jsxs(Mt,{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(El,{className:"w-5 h-5"}),a("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:a("projectDetail.files.linkFolders")})," ",a("projectDetail.files.forQuickAccess")]}),q&&q.length>0?r.jsx("div",{className:"space-y-4",children:q.map(Te=>{const Fe=L.get(Te.id)??[],et=O;return r.jsxs("div",{children:[r.jsxs(Is,{to:`/files?folder=${Te.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(El,{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:Te.name}),r.jsx("p",{className:"text-xs text-bambu-gray",children:a("projectDetail.files.fileCount",{count:Te.file_count})})]})]}),r.jsx(Hn,{className:"w-4 h-4 text-bambu-gray shrink-0"})]}),et?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"})}):Fe.length===0?r.jsx("p",{className:"text-bambu-gray/60 text-xs italic px-3",children:a("projectDetail.files.noFiles")}):r.jsx("div",{className:"space-y-1 pl-3",children:Fe.map(We=>{const Pe=Hit(We.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:We.thumbnail_path?r.jsx("img",{src:re.getLibraryFileThumbnailUrl(We.id),alt:We.print_name||We.filename,className:"w-full h-full object-cover"}):r.jsx(Ah,{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:We.print_name||We.filename,children:We.print_name||We.filename}),r.jsx("span",{className:`text-xs px-1.5 py-0.5 rounded font-medium ${We.file_type==="3mf"?"bg-bambu-green/20 text-bambu-green":We.file_type==="gcode"?"bg-blue-500/20 text-blue-400":"bg-bambu-gray/20 text-bambu-gray"}`,children:We.file_type.toUpperCase()})]}),Pe&&r.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[r.jsx("button",{onClick:()=>f(We),title:a("projectDetail.files.print"),className:"p-1.5 rounded hover:bg-bambu-green/20 text-bambu-green transition-colors",children:r.jsx(ys,{className:"w-4 h-4"})}),r.jsx("button",{onClick:()=>w(We),title:a("projectDetail.files.addToQueue"),className:"p-1.5 rounded hover:bg-blue-500/20 text-blue-400 transition-colors",children:r.jsx(uge,{className:"w-4 h-4"})})]})]},We.id)})})]},Te.id)})}):r.jsx("p",{className:"text-bambu-gray/70 text-sm italic",children:a("projectDetail.files.empty")})]})}),r.jsx(Tt,{children:r.jsxs(Mt,{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(mb,{className:"w-5 h-5"}),a("projectDetail.bom.title"),Ne&&Ne.bom_total_items>0&&r.jsxs("span",{className:"text-sm font-normal text-bambu-gray",children:["(",a("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(Te=>Te.is_complete)&&r.jsx("button",{onClick:()=>U(!ie),className:`text-xs px-2 py-1 rounded transition-colors ${ie?"bg-bambu-green/20 text-bambu-green":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:a(ie?"projectDetail.bom.showAll":"projectDetail.bom.hideDone")}),!W&&r.jsxs(je,{variant:"secondary",size:"sm",onClick:()=>z(!0),disabled:!s("projects:update"),title:s("projects:update")?void 0:a("projectDetail.bom.noAddPermission"),children:[r.jsx(er,{className:"w-4 h-4 mr-1"}),a("projectDetail.bom.addPart")]})]})]}),W&&r.jsxs("form",{onSubmit:Be,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:Z,onChange:Te=>ce(Te.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:a("projectDetail.bom.partNamePlaceholder"),autoFocus:!0}),r.jsxs("div",{className:"flex gap-2",children:[r.jsx("input",{type:"number",value:he,onChange:Te=>ue(parseInt(Te.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:a("projectDetail.bom.qty")}),r.jsx("input",{type:"number",step:"0.01",value:xe,onChange:Te=>H(Te.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:a("projectDetail.bom.price",{currency:X})})]})]}),r.jsx("input",{type:"url",value:J,onChange:Te=>A(Te.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:a("projectDetail.bom.sourcingUrlPlaceholder")}),r.jsx("input",{type:"text",value:E,onChange:Te=>B(Te.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:a("projectDetail.bom.remarksPlaceholder")}),r.jsxs("div",{className:"flex justify-end gap-2",children:[r.jsx(je,{type:"button",variant:"secondary",size:"sm",onClick:()=>z(!1),children:a("common.cancel")}),r.jsx(je,{type:"submit",size:"sm",disabled:!Z.trim()||ye.isPending,children:ye.isPending?r.jsx(pt,{className:"w-4 h-4 animate-spin"}):a("projectDetail.bom.addPart")})]})]}),j?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(Te=>!ie||!Te.is_complete).map(Te=>r.jsx("div",{className:`p-3 rounded-lg transition-colors ${Te.is_complete?"bg-status-ok/10":"bg-bambu-dark"}`,children:G?.id===Te.id?r.jsxs("form",{onSubmit:Ke,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:Y,onChange:Fe=>se(Fe.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:a("projectDetail.bom.partName"),autoFocus:!0}),r.jsxs("div",{className:"flex gap-2",children:[r.jsx("input",{type:"number",value:oe,onChange:Fe=>fe(parseInt(Fe.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:a("projectDetail.bom.qty")}),r.jsx("input",{type:"number",step:"0.01",value:ae,onChange:Fe=>pe(Fe.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:a("projectDetail.bom.price",{currency:X})})]})]}),r.jsx("input",{type:"url",value:$,onChange:Fe=>R(Fe.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:a("projectDetail.bom.sourcingUrlPlaceholder")}),r.jsx("input",{type:"text",value:ne,onChange:Fe=>be(Fe.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:a("projectDetail.bom.remarksPlaceholder")}),r.jsxs("div",{className:"flex justify-end gap-2",children:[r.jsx(je,{type:"button",variant:"secondary",size:"sm",onClick:Ue,children:a("common.cancel")}),r.jsx(je,{type:"submit",size:"sm",disabled:!Y.trim()||ge.isPending,children:ge.isPending?r.jsx(pt,{className:"w-4 h-4 animate-spin"}):a("common.save")})]})]}):r.jsxs("div",{className:"flex items-start gap-3",children:[r.jsx("button",{onClick:()=>s("projects:update")&&Le(Te),disabled:ge.isPending||!s("projects:update"),title:s("projects:update")?void 0:a("projectDetail.bom.noUpdatePermission"),className:`w-5 h-5 mt-0.5 rounded border-2 flex items-center justify-center transition-colors shrink-0 ${Te.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:Te.is_complete&&r.jsx(hr,{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 ${Te.is_complete?"text-bambu-gray line-through":"text-white"}`,children:[Te.name,r.jsxs("span",{className:"text-bambu-gray font-normal ml-2",children:["x",Te.quantity_needed]})]}),Te.unit_price!==null&&r.jsxs("span",{className:"text-xs text-bambu-green whitespace-nowrap",children:[X,(Te.unit_price*Te.quantity_needed).toFixed(2)]})]}),r.jsxs("div",{className:"flex items-center gap-1",children:[r.jsx("button",{onClick:()=>s("projects:update")&&Re(Te),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")?a("common.edit"):a("projectDetail.bom.noEditPermission"),children:r.jsx(yi,{className:"w-4 h-4"})}),r.jsx("button",{onClick:()=>s("projects:update")&&Oe(Te.id,Te.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")?a("common.delete"):a("projectDetail.bom.noDeletePermission"),children:r.jsx(ea,{className:"w-4 h-4"})})]})]}),Te.sourcing_url&&r.jsxs("a",{href:Te.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:Fe=>Fe.stopPropagation(),children:[r.jsx(Mr,{className:"w-3 h-3 shrink-0"}),r.jsx("span",{className:"truncate",children:(()=>{try{return new URL(Te.sourcing_url).hostname.replace("www.","")}catch{return Te.sourcing_url}})()})]}),Te.remarks&&r.jsx("p",{className:"mt-1 text-xs text-bambu-gray/80 italic",children:Te.remarks})]})]})},Te.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:a("projectDetail.bom.totalCost")}),r.jsxs("span",{className:"text-white font-medium",children:[X,Ne.bom_cost.toFixed(2)]})]})]}):r.jsx("p",{className:"text-bambu-gray/70 text-sm italic",children:a("projectDetail.bom.empty")})]})}),r.jsx(Tt,{children:r.jsxs(Mt,{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(Wh,{className:"w-5 h-5"}),a("projectDetail.timeline.title")]})}),k?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((Te,Fe)=>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 ${Te.event_type==="print_completed"?"bg-status-ok/20 text-status-ok":Te.event_type==="print_failed"?"bg-status-error/20 text-status-error":Te.event_type==="print_started"?"bg-yellow-500/20 text-yellow-400":"bg-bambu-dark-tertiary text-bambu-gray"}`,children:[Te.event_type==="print_completed"&&r.jsx(hr,{className:"w-4 h-4"}),Te.event_type==="print_failed"&&r.jsx(jr,{className:"w-4 h-4"}),Te.event_type==="print_started"&&r.jsx(gr,{className:"w-4 h-4"}),Te.event_type==="queued"&&r.jsx(tL,{className:"w-4 h-4"}),Te.event_type==="project_created"&&r.jsx(er,{className:"w-4 h-4"})]}),r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsx("p",{className:"text-sm text-white",children:Te.title}),Te.description&&r.jsx("p",{className:"text-xs text-bambu-gray truncate",children:Te.description}),r.jsx("p",{className:"text-xs text-bambu-gray/70",children:st(Te.timestamp)})]})]},Fe))}):r.jsx("p",{className:"text-bambu-gray/70 text-sm italic",children:a("projectDetail.timeline.empty")})]})}),!x.is_template&&r.jsx("div",{className:"flex justify-end",children:r.jsxs(je,{variant:"secondary",size:"sm",onClick:()=>Ee.mutate(),disabled:Ee.isPending||!s("projects:create"),title:s("projects:create")?void 0:a("projectDetail.template.noCreatePermission"),children:[Ee.isPending?r.jsx(pt,{className:"w-4 h-4 animate-spin mr-2"}):r.jsx(xi,{className:"w-4 h-4 mr-2"}),a("projectDetail.template.saveAsTemplate")]})}),Ne&&(Ne.queued_prints>0||Ne.in_progress_prints>0)&&r.jsx(Tt,{children:r.jsxs(Mt,{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(tL,{className:"w-5 h-5"}),a("projectDetail.queue.title")]}),r.jsx(Is,{to:`/queue?project=${b}`,className:"text-sm text-bambu-green hover:underline",children:a("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:a("projectDetail.queue.printing",{count:Ne.in_progress_prints})}),Ne.queued_prints>0&&r.jsx("span",{className:"text-bambu-gray",children:a("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(qr,{className:"w-5 h-5"}),a("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(Git,{archives:C||[],t:a})]}),o&&r.jsx(lde,{t:a,currencySymbol:X,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:Te=>Q.mutate(Te),isLoading:Q.isPending}),ve.isOpen&&r.jsx(wa,{title:ve.title,message:ve.message,confirmText:a("common.delete"),variant:"danger",onConfirm:ve.onConfirm,onCancel:()=>ke(Te=>({...Te,isOpen:!1}))}),p&&r.jsx(wc,{mode:"reprint",libraryFileId:p.id,archiveName:p.print_name||p.filename,projectId:b,onClose:()=>f(null),onSuccess:()=>{f(null),n.invalidateQueries({queryKey:["archives"]})}}),g&&r.jsx(wc,{mode:"add-to-queue",libraryFileId:g.id,archiveName:g.print_name||g.filename,projectId:b,onClose:()=>w(null),onSuccess:()=>{w(null),n.invalidateQueries({queryKey:["queue"]})}})]})}function Qit({archiveId:t,libraryFileId:e,title:a,fileType:n,onClose:i}){const{t:s}=vt(),{data:o}=Qe({queryKey:["settings"],queryFn:re.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),[j,F]=y.useState(!1),[k,M]=y.useState(null),[q,I]=y.useState(!1),[O,L]=y.useState(!1),X=y.useRef(null),ee=y.useRef(null),Q=10,le=160,de=240,me=.35;y.useEffect(()=>{const ae=pe=>{pe.key==="Escape"&&i()};return window.addEventListener("keydown",ae),()=>window.removeEventListener("keydown",ae)},[i]),y.useEffect(()=>{if(g(!0),c){const ae=(n||"").toLowerCase(),pe=ae==="3mf"||ae==="stl",$=ae==="gcode"||ae==="3mf";p({has_model:pe,has_gcode:$,has_source:!1,build_volume:{x:256,y:256,z:256},filament_colors:[]}),u(pe?"3d":$?"gcode":null),g(!1);return}if(!t){p(null),u(null),g(!1);return}re.getArchiveCapabilities(t).then(ae=>{p(ae),ae.has_model?u("3d"):ae.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,n,c]),y.useEffect(()=>{if(S(!0),C(null),T(0),c){const ae=(n||"").toLowerCase();if(!e||ae!=="3mf"){b(null),S(!1);return}re.getLibraryFilePlates(e).then(pe=>b(pe)).catch(()=>b(null)).finally(()=>S(!1));return}if(!t){b(null),S(!1);return}re.getArchivePlates(t).then(ae=>b(ae)).catch(()=>b(null)).finally(()=>S(!1))},[t,n,c,e]);const Z=y.useMemo(()=>w?.plates??[],[w]),ce=(w?.is_multi_plate??!1)&&Z.length>1,he=j&&ce,ue=N==null?null:Z.find(ae=>ae.index===N)??null,xe=ae=>ae.object_count??ae.objects?.length??0,H=Z.reduce((ae,pe)=>ae+xe(pe),0),J=ue?xe(ue):H,A=ue?s("modelViewer.plateNumber",{number:ue.index}):s("modelViewer.allPlates"),E=Z.length>0,B=y.useRef(null),W=y.useRef(null),[z,ie]=y.useState(10),[U,G]=y.useState(3),K=Z.length>z,Y=Math.max(1,Math.ceil(Z.length/z)),se=K?Z.slice(P*z,(P+1)*z):Z;y.useEffect(()=>{if(!he){ie(10),G(3);return}const ae=B.current,pe=W.current;if(!ae||!pe)return;let $=0;const R=()=>{const ve=pe.clientWidth,ye=Math.floor(ve/210),ge=Math.max(3,Math.min(5,ye||3));G(Ee=>Ee===ge?Ee:ge);const Me=window.getComputedStyle(ae),Be=Number.parseFloat(Me.rowGap||"0"),Oe=ae.querySelector("button")?.getBoundingClientRect().height??44,Re=pe.clientHeight,Ue=Math.max(1,Math.floor((Re+Be)/(Oe+Be)))*ge,lt=Math.max(1,Ue-1);ie(Ee=>Ee===lt?Ee:lt)},ne=()=>{$&&cancelAnimationFrame($),$=requestAnimationFrame(R)};ne();const be=new ResizeObserver(ne);return be.observe(pe),be.observe(ae),()=>{$&&cancelAnimationFrame($),be.disconnect()}},[he,Z.length]),y.useEffect(()=>{if(!K){T(0);return}T(ae=>Math.min(ae,Y-1))},[Z.length,K,Y]),y.useEffect(()=>{if(!K||N==null)return;const ae=Z.findIndex($=>$.index===N);if(ae<0)return;const pe=Math.floor(ae/z);T($=>$===pe?$:pe)},[Z,z,N,K]),y.useEffect(()=>{if(!he){M(null),L(!1);return}if(O)return;const ae=X.current,pe=ee.current;if(!ae||!pe)return;const $=ae.clientHeight;if(!$)return;const R=Math.max(de,$*me),ne=Math.max(le,$-Q-R),be=Math.min(pe.scrollHeight,ne);M(Math.max(le,be))},[he,O,Z.length,P,Q,le,de,me]),y.useEffect(()=>{if(!q)return;const ae=$=>{const R=X.current;if(!R)return;const ne=R.getBoundingClientRect(),be=ne.height;if(!be)return;const ve=Math.max(de,be*me),ke=Math.max(le,be-Q-ve),ye=Math.min(ke,Math.max(le,$.clientY-ne.top));M(ye)},pe=()=>{I(!1),L(!0)};return document.addEventListener("mousemove",ae),document.addEventListener("mouseup",pe),document.body.style.cursor="row-resize",document.body.style.userSelect="none",()=>{document.removeEventListener("mousemove",ae),document.removeEventListener("mouseup",pe),document.body.style.cursor="",document.body.style.userSelect=""}},[q,Q,le,de,me]);const oe=c?(n||"").toLowerCase()==="3mf":!0,fe=async()=>{if(!oe)return;const ae=a||"model";try{if(c){const{token:pe}=await re.createLibrarySlicerToken(e),$=re.getLibrarySlicerDownloadUrl(e,pe,ae);Lm(`${window.location.origin}${$}`,l)}else{const{token:pe}=await re.createArchiveSlicerToken(t),$=re.getArchiveSlicerDownloadUrl(t,pe,ae);Lm(`${window.location.origin}${$}`,l)}}catch{if(c){const pe=`${window.location.origin}${re.getLibraryFileDownloadUrl(e)}`;Lm(pe,l)}else{const pe=`${window.location.origin}${re.getArchiveForSlicer(t,ae)}`;Lm(pe,l)}}};return r.jsx("div",{className:`fixed inset-0 bg-black/70 flex items-center justify-center z-50 ${j?"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 ${j?"h-full max-w-none rounded-none":"h-[80vh] max-w-4xl rounded-xl"}`,onClick:ae=>ae.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:a}),E&&r.jsxs("span",{className:"text-xs text-bambu-gray bg-bambu-dark-tertiary/70 px-2 py-1 rounded whitespace-nowrap",children:[A,": ",s("modelViewer.objectCount",{count:J})]})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsxs(je,{variant:"secondary",size:"sm",onClick:fe,disabled:!oe,children:[r.jsx(Mr,{className:"w-4 h-4"}),s("modelViewer.openInSlicer")]}),r.jsx(je,{variant:"secondary",size:"sm",onClick:()=>F(ae=>!ae),title:j?"Exit fullscreen":"Enter fullscreen",children:j?r.jsx(MO,{className:"w-4 h-4"}):r.jsx(MT,{className:"w-4 h-4"})}),r.jsx(je,{variant:"ghost",size:"sm",onClick:i,children:r.jsx($t,{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(Mi,{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:X,className:`w-full h-full flex flex-col ${he?"gap-0 min-h-0":"gap-3"}`,children:[ce&&r.jsxs("div",{ref:ee,style:he&&k!=null?{height:k}:void 0,className:`rounded-lg border border-bambu-dark-tertiary bg-bambu-dark p-3 ${he?"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(cn,{className:"w-4 h-4"}),s("modelViewer.plates"),x&&r.jsx(pt,{className:"w-3 h-3 animate-spin"})]}),r.jsxs("div",{className:he?"flex flex-col min-h-0 flex-1":void 0,children:[r.jsx("div",{ref:W,className:he?"min-h-0 overflow-hidden pr-1 flex-1":void 0,children:r.jsxs("div",{ref:B,className:he?"grid gap-2":"grid grid-cols-2 md:grid-cols-3 gap-2",style:he?{gridTemplateColumns:`repeat(${U}, 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 ${he?"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 ${he?"w-8 h-8":"w-10 h-10"}`,children:r.jsx(cn,{className:`${he?"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:`${he?"text-xs":"text-sm"} text-white font-medium truncate`,children:s("modelViewer.allPlates")}),r.jsx("p",{className:`${he?"text-[10px]":"text-xs"} text-bambu-gray truncate`,children:s("modelViewer.plateCount",{count:Z.length})})]}),N==null&&r.jsx(kr,{className:`${he?"w-3.5 h-3.5":"w-4 h-4"} text-bambu-green flex-shrink-0`})]}),se.map(ae=>r.jsxs("button",{type:"button",onClick:()=>C(ae.index),className:`flex items-center rounded-lg border text-left transition-colors ${he?"gap-1.5 p-1.5 w-full":"gap-2 p-2"} ${N===ae.index?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary bg-bambu-dark-secondary hover:border-bambu-gray"}`,children:[ae.has_thumbnail&&ae.thumbnail_url?r.jsx("img",{src:ae.thumbnail_url,alt:`Plate ${ae.index}`,className:`${he?"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 ${he?"w-8 h-8":"w-10 h-10"}`,children:r.jsx(cn,{className:`${he?"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:`${he?"text-xs":"text-sm"} text-white font-medium truncate`,children:ae.name||s("modelViewer.plateNumber",{number:ae.index})}),r.jsx("p",{className:`${he?"text-[10px]":"text-xs"} text-bambu-gray truncate`,children:s("modelViewer.objectCount",{count:ae.object_count??ae.objects?.length??0})})]}),N===ae.index&&r.jsx(kr,{className:`${he?"w-3.5 h-3.5":"w-4 h-4"} text-bambu-green flex-shrink-0`})]},ae.index))]})}),(ue||K)&&r.jsxs("div",{className:"mt-auto pt-3 flex items-center gap-4 text-xs text-bambu-gray overflow-x-auto",children:[ue&&r.jsxs("div",{className:"flex items-center gap-3 whitespace-nowrap",children:[r.jsx("span",{children:s("modelViewer.plateNumber",{number:ue.index})}),ue.print_time_seconds!=null&&r.jsx("span",{children:s("modelViewer.eta",{minutes:Math.round(ue.print_time_seconds/60)})}),ue.filament_used_grams!=null&&r.jsxs("span",{children:[ue.filament_used_grams.toFixed(1)," g"]}),ue.filaments.length>0&&r.jsx("span",{children:s("modelViewer.filamentCount",{count:ue.filaments.length})})]}),K&&r.jsxs("div",{className:`flex items-center gap-2 whitespace-nowrap ${ue?"ml-auto":""}`,children:[r.jsx("span",{children:s("modelViewer.pagination.pageOf",{current:P+1,total:Y})}),r.jsxs("div",{className:"flex items-center gap-1",children:[r.jsx("button",{type:"button",onClick:()=>T(ae=>Math.max(ae-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 pe=Math.max(0,P-Math.floor(2.5));const $=Math.min(Y,pe+5);$-pe<5&&(pe=Math.max(0,$-5));const R=Array.from({length:$-pe},(ne,be)=>pe+be);return r.jsxs(r.Fragment,{children:[pe>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"}),pe>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)),$T(Y-1),className:`px-2 py-1 rounded border text-xs ${P===Y-1?"border-bambu-green text-bambu-green":"border-bambu-dark-tertiary text-bambu-gray hover:text-white hover:border-bambu-gray"}`,children:Y})]})})(),r.jsx("button",{type:"button",onClick:()=>T(ae=>Math.min(ae+1,Y-1)),disabled:P>=Y-1,className:`px-2 py-1 rounded border text-xs ${P>=Y-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")})]})]})]})]})]}),he&&r.jsx("div",{role:"separator","aria-orientation":"horizontal",onMouseDown:ae=>{ae.preventDefault(),I(!0),L(!0)},className:`h-2 cursor-row-resize flex items-center justify-center ${q?"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 ${he?"min-h-0":""}`,children:r.jsx(oee,{url:c?re.getLibraryFileDownloadUrl(e):m.has_source?re.getSource3mfDownloadUrl(t):re.getArchiveDownload(t),fileType:n,buildVolume:m.build_volume,filamentColors:m.filament_colors,selectedPlateId:N,className:"w-full h-full"})})]}):d==="gcode"&&m?r.jsx(Hee,{gcodeUrl:c?re.getLibraryFileGcodeUrl(e):re.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 Yit=90;function Xit({onClose:t}){const{t:e}=vt(),a=ta(),{showToast:n}=na(),[i,s]=y.useState(Yit),[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=Qe({queryKey:["library-purge-preview",c,o],queryFn:()=>re.previewLibraryPurge(c,o),enabled:c>=1}),m=ot({mutationFn:()=>re.executeLibraryPurge(i,o),onSuccess:b=>{n(e("libraryPurge.toast.success",{count:b.moved_to_trash}),"success"),a.invalidateQueries({queryKey:["library-files"]}),a.invalidateQueries({queryKey:["library-folders"]}),a.invalidateQueries({queryKey:["library-trash"]}),a.invalidateQueries({queryKey:["library-trash-count"]}),t()},onError:b=>n(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(ea,{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($t,{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:ps(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(ba,{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(je,{variant:"secondary",onClick:t,disabled:m.isPending,children:e("common.cancel")}),r.jsx(je,{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 Zit({parentId:t,onClose:e,onSave:a,isLoading:n,t:i}){const[s,o]=y.useState(""),l=c=>{c.preventDefault(),a({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(je,{type:"button",variant:"secondary",onClick:e,children:i("common.cancel")}),r.jsx(je,{type:"submit",disabled:!s.trim()||n,children:n?r.jsx(pt,{className:"w-4 h-4 animate-spin"}):i("common.create")})]})]})]})})}function Jit({onClose:t,onSave:e,isLoading:a,t:n}){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(oC,{className:"w-5 h-5 text-bambu-green"}),n("fileManager.linkExternalFolder")]}),r.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:n("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:n("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:n("fileManager.externalFolderNamePlaceholder"),autoFocus:!0,required:!0})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:n("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:n("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:n("fileManager.readOnly")}),r.jsxs("span",{className:"text-xs text-bambu-gray",children:["(",n("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:n("fileManager.showHiddenFiles")})]})]}),r.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[r.jsx(je,{type:"button",variant:"secondary",onClick:t,children:n("common.cancel")}),r.jsx(je,{type:"submit",disabled:!i.trim()||!o.trim()||a,children:a?r.jsx(pt,{className:"w-4 h-4 animate-spin"}):n("fileManager.linkFolder")})]})]})]})})}function est({type:t,currentName:e,onClose:a,onSave:n,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&&n(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(je,{type:"button",variant:"secondary",onClick:a,children:s("common.cancel")}),r.jsx(je,{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 tst({folders:t,selectedFiles:e,currentFolderId:a,onClose:n,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===a,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===a?"opacity-50 cursor-not-allowed text-bambu-gray":"hover:bg-bambu-dark text-white"}`,style:{paddingLeft:`${12+m.depth*16}px`},children:[r.jsx(El,{className:"w-4 h-4"}),m.name,m.id===a&&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(je,{type:"button",variant:"secondary",onClick:n,children:o("common.cancel")}),r.jsx(je,{onClick:()=>i(l),disabled:s,children:s?r.jsx(pt,{className:"w-4 h-4 animate-spin"}):o("common.move")})]})]})]})})}function ast({folder:t,onClose:e,onLink:a,isLoading:n,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}=Qe({queryKey:["projects"],queryFn:()=>re.getProjects(),select:g=>[...g].sort((w,b)=>w.name.localeCompare(b.name))}),{data:u}=Qe({queryKey:["archives-for-link"],queryFn:()=>re.getArchives(void 0,void 0,100)}),m=()=>{a(s==="project"?{project_id:l,archive_id:0}:{project_id:0,archive_id:l})},p=()=>{a({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(Eh,{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($t,{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($Z,{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(io,{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(Ah,{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(je,{variant:"danger",onClick:p,disabled:n,children:[r.jsx(su,{className:"w-4 h-4 mr-2"}),i("fileManager.unlink")]}),r.jsxs("div",{className:`flex gap-2 ${f?"":"ml-auto"}`,children:[r.jsx(je,{variant:"secondary",onClick:e,children:i("common.cancel")}),r.jsx(je,{onClick:m,disabled:!l||n,children:n?r.jsx(pt,{className:"w-4 h-4 animate-spin"}):i("fileManager.link")})]})]})]})})}function cde({folder:t,selectedFolderId:e,onSelect:a,onDelete:n,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:()=>a(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(Hn,{className:`w-3.5 h-3.5 transition-transform ${m?"rotate-90":""}`})}):r.jsx("div",{className:"w-4.5"}),x?r.jsx(oC,{className:"w-4 h-4 text-purple-400 flex-shrink-0"}):r.jsx(El,{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(Eh,{className:"w-3 h-3"}),t.project_name?r.jsx($Z,{className:"w-3 h-3"}):r.jsx(io,{className:"w-3 h-3"})]}),x&&t.external_readonly&&r.jsx("span",{title:u("fileManager.readOnly"),children:r.jsx(oc,{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(Eh,{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(Nm,{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(yi,{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(Eh,{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")&&(n(t.id),g(!1))},disabled:!d("library:delete_all"),title:d("library:delete_all")?void 0:u("fileManager.noPermissionDeleteFolder"),children:[r.jsx(ea,{className:"w-3.5 h-3.5"}),u("common.delete")]})]})]})]})})]}),w&&m&&r.jsx("div",{children:t.children.map(S=>r.jsx(cde,{folder:S,selectedFolderId:e,onSelect:a,onDelete:n,onLink:i,onRename:s,depth:o+1,wrapNames:l,defaultExpanded:c,hasPermission:d,t:u},S.id))})]})}function Pw(t){const e=t.toLowerCase();return e.endsWith(".gcode")||e.endsWith(".gcode.3mf")}function dde(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 rst({file:t,isSelected:e,isMobile:a,onSelect:n,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:()=>n(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:`${re.getLibraryFileThumbnailUrl(t.id)}${f?(re.getLibraryFileThumbnailUrl(t.id).includes("?")?"&":"?")+`v=${f}`:""}`,alt:t.filename,className:"w-full h-full object-cover"}):r.jsx(Ah,{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:ps(t.file_size)}),t.print_time_seconds&&r.jsxs("span",{className:"flex items-center gap-1",children:[r.jsx(Za,{className:"w-3 h-3"}),hs(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(gr,{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(Xm,{className:"w-3 h-3"}),t.created_by_username]})]}),r.jsxs("div",{className:`absolute bottom-2 right-2 transition-opacity ${a?"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(Nm,{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&&Pw(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(gr,{className:"w-3.5 h-3.5"}),x("common.print")]}),o&&Pw(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(Za,{className:"w-3.5 h-3.5"}),x("fileManager.schedulePrint")]}),c&&d&&dde(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(du,{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(Mi,{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(Ur,{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(yi,{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(uu,{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(ea,{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 ${a?"opacity-100":"opacity-0 group-hover:opacity-100"}`}`,children:e&&r.jsx("div",{className:"w-2 h-2 bg-white rounded-sm"})})]})}function nst(){const{t}=vt(),e=ta(),{showToast:a}=na(),{hasPermission:n,hasAnyPermission:i,canModify:s,authEnabled:o}=dr(),[l]=lb(),c=Oi(),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),[j,F]=y.useState(!1),[k,M]=y.useState(null),[q,I]=y.useState(null),[O,L]=y.useState(null),[X,ee]=y.useState(null),[Q,le]=y.useState(null),[de,me]=y.useState(null),[Z,ce]=y.useState(null),[he,ue]=y.useState({}),[xe,H]=y.useState(null),[J,A]=y.useState(()=>localStorage.getItem("library-view-mode")||"grid"),[E,B]=y.useState(()=>localStorage.getItem("library-wrap-folders")==="true"),[W,z]=y.useState(()=>localStorage.getItem("library-collapse-folders")==="true"),[ie,U]=y.useState(()=>{const Ae=localStorage.getItem("library-sidebar-width");return Ae?parseInt(Ae,10):256}),[G,K]=y.useState(!1),Y=y.useRef(null);y.useEffect(()=>{if(!G)return;document.body.style.userSelect="none",document.body.style.cursor="col-resize";const Ae=Je=>{if(!Y.current)return;const De=Y.current.parentElement?.getBoundingClientRect();if(!De)return;const bt=Je.clientX-De.left,Ce=Math.min(500,Math.max(200,bt));U(Ce)},Ve=()=>{K(!1),document.body.style.userSelect="",document.body.style.cursor="",localStorage.setItem("library-sidebar-width",String(ie))};return document.addEventListener("mousemove",Ae),document.addEventListener("mouseup",Ve),()=>{document.removeEventListener("mousemove",Ae),document.removeEventListener("mouseup",Ve),document.body.style.userSelect="",document.body.style.cursor=""}},[G,ie]);const[se,oe]=y.useState(""),[fe,ae]=y.useState("all"),[pe,$]=y.useState(""),[R,ne]=y.useState(()=>localStorage.getItem("library-sort-field")||"name"),[be,ve]=y.useState(()=>localStorage.getItem("library-sort-direction")||"asc"),ke=vse();y.useEffect(()=>{const Ae=l.get("folder");if(Ae){const Ve=parseInt(Ae,10);p(Ve)}},[l]);const{data:ye}=Qe({queryKey:["settings"],queryFn:()=>re.getSettings()}),{data:ge,isLoading:Me}=Qe({queryKey:["library-folders"],queryFn:()=>re.getLibraryFolders()}),{data:Be}=Qe({queryKey:["library-trash-count"],queryFn:async()=>{try{return(await re.listLibraryTrash(1,0)).total}catch{return 0}},staleTime:3e4}),{data:Le,isLoading:Oe}=Qe({queryKey:["library-files",m],queryFn:()=>re.getLibraryFiles(m,m===null)}),{data:Re}=Qe({queryKey:["library-stats"],queryFn:()=>re.getLibraryStats()}),{data:Ke}=Qe({queryKey:["users"],queryFn:()=>re.getUsers()}),Ue=y.useMemo(()=>{if(!Le)return[];const Ae=new Set(Le.map(Ve=>Ve.file_type));return Array.from(Ae).sort()},[Le]),lt=y.useMemo(()=>{if(!Le)return[];let Ae=[...Le];if(se.trim()){const Ve=se.toLowerCase();Ae=Ae.filter(Je=>Je.filename.toLowerCase().includes(Ve)||Je.print_name&&Je.print_name.toLowerCase().includes(Ve))}if(fe!=="all"&&(Ae=Ae.filter(Ve=>Ve.file_type===fe)),pe.trim()){const Ve=pe.toLowerCase();Ae=Ae.filter(Je=>Je.created_by_username&&Je.created_by_username.toLowerCase().includes(Ve))}return Ae.sort((Ve,Je)=>{let De=0;switch(R){case"name":De=(Ve.print_name||Ve.filename).localeCompare(Je.print_name||Je.filename);break;case"date":De=(Qa(Ve.created_at)?.getTime()??0)-(Qa(Je.created_at)?.getTime()??0);break;case"size":De=Ve.file_size-Je.file_size;break;case"type":De=Ve.file_type.localeCompare(Je.file_type);break;case"prints":De=Ve.print_count-Je.print_count;break}return be==="asc"?De:-De}),Ae},[Le,se,fe,pe,R,be]),Ee=y.useMemo(()=>{if(!Re||!ye)return!1;const Ae=(ye.library_disk_warning_gb||5)*1024*1024*1024;return Re.disk_free_bytesre.createLibraryFolder(Ae),onSuccess:()=>{e.invalidateQueries({queryKey:["library-folders"]}),b(!1),a(t("fileManager.toast.folderCreated"),"success")},onError:Ae=>a(Ae.message,"error")}),Ne=ot({mutationFn:async Ae=>{const Ve=await re.createExternalFolder(Ae);return await re.scanExternalFolder(Ve.id),Ve},onSuccess:Ae=>{e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-stats"]}),S(!1),p(Ae.id),a(t("fileManager.toast.externalFolderLinked"),"success")},onError:Ae=>a(Ae.message,"error")}),Ze=ot({mutationFn:Ae=>re.scanExternalFolder(Ae),onSuccess:Ae=>{e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-stats"]}),a(t("fileManager.toast.folderScanned",{added:Ae.added,removed:Ae.removed}),"success")},onError:Ae=>a(Ae.message,"error")}),Ye=ot({mutationFn:Ae=>re.deleteLibraryFolder(Ae),onSuccess:()=>{e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-stats"]}),m===q?.id&&p(null),I(null),a(t("fileManager.toast.folderDeleted"),"success")},onError:Ae=>{I(null),a(Ae.message,"error")}}),Te=ot({mutationFn:Ae=>re.deleteLibraryFile(Ae),onSuccess:()=>{e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-stats"]}),e.invalidateQueries({queryKey:["library-trash-count"]}),g(Ae=>Ae.filter(Ve=>Ve!==q?.id)),I(null),a(t("fileManager.toast.fileDeleted"),"success")},onError:Ae=>{I(null),a(Ae.message,"error")}}),Fe=ot({mutationFn:Ae=>re.bulkDeleteLibrary(Ae,[]),onSuccess:(Ae,Ve)=>{e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-stats"]}),e.invalidateQueries({queryKey:["library-trash-count"]}),a(t("fileManager.toast.filesDeleted",{count:Ve.length}),"success"),g([]),I(null)},onError:Ae=>{I(null),a(Ae.message,"error")}}),et=ot({mutationFn:({fileIds:Ae,folderId:Ve})=>re.moveLibraryFiles(Ae,Ve),onSuccess:()=>{e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-folders"]}),g([]),C(!1),a(t("fileManager.toast.filesMoved"),"success")},onError:Ae=>a(Ae.message,"error")}),We=ot({mutationFn:({id:Ae,data:Ve})=>re.updateLibraryFolder(Ae,Ve),onSuccess:(Ae,Ve)=>{e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["project-folders"]}),e.invalidateQueries({queryKey:["archive-folders"]}),M(null);const Je=Ve.data.project_id===0&&Ve.data.archive_id===0;a(t(Je?"fileManager.toast.folderUnlinked":"fileManager.toast.folderLinked"),"success")},onError:Ae=>a(Ae.message,"error")}),Pe=ot({mutationFn:({id:Ae,filename:Ve})=>re.updateLibraryFile(Ae,{filename:Ve}),onSuccess:()=>{e.invalidateQueries({queryKey:["library-files"]}),ce(null),a(t("fileManager.toast.fileRenamed"),"success")},onError:Ae=>{ce(null),a(Ae.message,"error")}}),at=ot({mutationFn:({id:Ae,name:Ve})=>re.updateLibraryFolder(Ae,{name:Ve}),onSuccess:()=>{e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-files"]}),ce(null),a(t("fileManager.toast.folderRenamed"),"success")},onError:Ae=>{ce(null),a(Ae.message,"error")}}),nt=ot({mutationFn:()=>re.batchGenerateStlThumbnails({all_missing:!0}),onSuccess:Ae=>{if(e.invalidateQueries({queryKey:["library-files"]}),Ae.succeeded>0){const Ve=Date.now(),Je={};Ae.results.forEach(De=>{De.success&&(Je[De.file_id]=Ve)}),ue(De=>({...De,...Je}))}Ae.succeeded>0&&Ae.failed===0?a(t("fileManager.toast.thumbnailsGenerated",{count:Ae.succeeded}),"success"):Ae.succeeded>0&&Ae.failed>0?a(t("fileManager.toast.thumbnailsGeneratedPartial",{succeeded:Ae.succeeded,failed:Ae.failed}),"success"):Ae.processed===0?a(t("fileManager.toast.noStlMissingThumbnails"),"info"):a(t("fileManager.toast.failedToGenerateThumbnails",{error:Ae.results[0]?.error||"Unknown error"}),"error")},onError:Ae=>a(Ae.message,"error")}),At=ot({mutationFn:Ae=>re.batchGenerateStlThumbnails({file_ids:[Ae]}),onSuccess:Ae=>{if(e.invalidateQueries({queryKey:["library-files"]}),Ae.succeeded>0){const Ve=Ae.results[0]?.file_id;Ve&&ue(Je=>({...Je,[Ve]:Date.now()})),a(t("fileManager.toast.thumbnailGenerated"),"success")}else a(t("fileManager.toast.failedToGenerateThumbnail",{error:Ae.results[0]?.error||"Unknown error"}),"error")},onError:Ae=>a(Ae.message,"error")}),Bt=y.useCallback(Ae=>{const Ve=Ae.toLowerCase();return Ve.endsWith(".gcode")||Ve.includes(".gcode.")},[]),gt=y.useMemo(()=>Le?Le.filter(Ae=>f.includes(Ae.id)&&Bt(Ae.filename)):[],[Le,f,Bt]),Qt=y.useCallback(Ae=>{g(Ve=>Ve.includes(Ae)?Ve.filter(Je=>Je!==Ae):[...Ve,Ae])},[]),Xt=y.useCallback(()=>{lt.length>0&&g(lt.map(Ae=>Ae.id))},[lt]),ia=y.useCallback(()=>{g([])},[]),da=()=>{e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-stats"]})},ut=Ae=>{re.downloadLibraryFile(Ae).catch(Ve=>{console.error("Library file download failed:",Ve)})},_t=()=>{q&&(q.type==="file"?Te.mutate(q.id):q.type==="folder"?Ye.mutate(q.id):q.type==="bulk"&&Fe.mutate(f))},Ct=Ye.isPending||Te.isPending||Fe.isPending,dt=Ae=>{A(Ae),localStorage.setItem("library-view-mode",Ae)},Nt=Me||Oe,Ie=y.useMemo(()=>{if(!m||!ge)return null;const Ae=Ve=>{for(const Je of Ve){if(Je.id===m)return Je;const De=Ae(Je.children);if(De)return De}return null};return Ae(ge)},[m,ge]);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(El,{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:()=>dt("grid"),className:`p-1.5 rounded transition-colors ${J==="grid"?"bg-bambu-dark-secondary text-white":"text-bambu-gray hover:text-white"}`,title:t("fileManager.gridView"),children:r.jsx(DS,{className:"w-4 h-4"})}),r.jsx("button",{onClick:()=>dt("list"),className:`p-1.5 rounded transition-colors ${J==="list"?"bg-bambu-dark-secondary text-white":"text-bambu-gray hover:text-white"}`,title:t("fileManager.listView"),children:r.jsx(FS,{className:"w-4 h-4"})})]}),r.jsxs(je,{variant:"secondary",onClick:()=>nt.mutate(),disabled:nt.isPending||!i("library:update_own","library:update_all"),title:i("library:update_own","library:update_all")?t("fileManager.generateThumbnailsForMissing"):t("fileManager.noPermissionGenerateThumbnail"),children:[nt.isPending?r.jsx(pt,{className:"w-4 h-4 mr-2 animate-spin"}):r.jsx(uu,{className:"w-4 h-4 mr-2"}),t("fileManager.generateThumbnails")]}),r.jsxs(je,{variant:"secondary",onClick:()=>S(!0),disabled:!n("library:upload"),title:n("library:upload")?t("fileManager.linkExternalFolder"):t("fileManager.noPermissionCreateFolder"),children:[r.jsx(oC,{className:"w-4 h-4 mr-2"}),t("fileManager.linkExternal")]}),r.jsxs(je,{variant:"secondary",onClick:()=>b(!0),disabled:!n("library:upload"),title:n("library:upload")?void 0:t("fileManager.noPermissionCreateFolder"),children:[r.jsx(Ube,{className:"w-4 h-4 mr-2"}),t("fileManager.newFolder")]}),n("library:purge")&&r.jsxs(je,{variant:"secondary",onClick:()=>F(!0),title:t("libraryPurge.headerTooltip"),children:[r.jsx(ea,{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(ea,{className:"w-4 h-4 mr-2"}),t("libraryTrash.headerButton"),typeof Be=="number"&&Be>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:Be})]}),r.jsxs(je,{onClick:()=>T(!0),disabled:!n("library:upload"),title:n("library:upload")?void 0:t("fileManager.noPermissionUpload"),children:[r.jsx(Sn,{className:"w-4 h-4 mr-2"}),t("common.upload")]})]})]}),Ee&&Re&&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(ba,{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:ps(Re.disk_free_bytes),total:ps(Re.disk_total_bytes),threshold:ye.library_disk_warning_gb})})]})]}),Re&&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(jT,{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:Re.total_files})]}),r.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[r.jsx(El,{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:Re.total_folders})]}),r.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[r.jsx(ub,{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:ps(Re.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 ${Ee?"text-amber-500":"text-white"}`,children:ps(Re.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:Ae=>p(Ae.target.value?parseInt(Ae.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")]}),ge&&(()=>{const Ae=(Ve,Je=0)=>{const De=[];for(const bt of Ve)De.push({id:bt.id,name:bt.name,fileCount:bt.file_count,depth:Je}),bt.children.length>0&&De.push(...Ae(bt.children,Je+1));return De};return Ae(ge).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:Y,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:`${ie}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:Ae=>{Ae.preventDefault(),K(!0)},onDoubleClick:()=>{U(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 Ae=!W;z(Ae),localStorage.setItem("library-collapse-folders",String(Ae))},className:`text-xs px-1.5 py-0.5 rounded transition-colors ${W?"bg-bambu-green/20 text-bambu-green":"text-bambu-gray hover:text-white hover:bg-bambu-dark"}`,title:t(W?"fileManager.expandFoldersByDefault":"fileManager.collapseFoldersByDefault"),children:t("fileManager.collapse")}),r.jsx("button",{onClick:()=>{const Ae=!E;B(Ae),localStorage.setItem("library-wrap-folders",String(Ae))},className:`text-xs px-1.5 py-0.5 rounded transition-colors ${E?"bg-bambu-green/20 text-bambu-green":"text-bambu-gray hover:text-white hover:bg-bambu-dark"}`,title:t(E?"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(Ah,{className:"w-4 h-4"}),r.jsx("span",{className:"text-sm",children:t("fileManager.allFiles")})]}),ge?.map(Ae=>r.jsx(cde,{folder:Ae,selectedFolderId:m,onSelect:p,onDelete:Ve=>I({type:"folder",id:Ve}),onLink:M,onRename:Ve=>ce({type:"folder",id:Ve.id,name:Ve.name}),wrapNames:E,defaultExpanded:!W,hasPermission:n,t},`${Ae.id}-${W?"c":"e"}`))]})]}),r.jsxs("div",{className:"flex-1 flex flex-col min-w-0 min-h-0",children:[Ie?.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(oC,{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")}),Ie.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(oc,{className:"w-3 h-3"}),t("fileManager.readOnly")]})]}),r.jsx("p",{className:"text-xs text-bambu-gray truncate font-mono",title:Ie.external_path||"",children:Ie.external_path})]}),r.jsxs(je,{variant:"secondary",size:"sm",onClick:()=>m&&Ze.mutate(m),disabled:Ze.isPending,title:t("fileManager.scanFolder"),children:[Ze.isPending?r.jsx(pt,{className:"w-4 h-4 animate-spin"}):r.jsx(Xa,{className:"w-4 h-4"}),r.jsx("span",{className:"ml-1.5",children:t("fileManager.scanFolder")})]})]}),Le&&Le.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(fr,{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:se,onChange:Ae=>oe(Ae.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(jS,{className:"w-4 h-4 text-bambu-gray hidden sm:block"}),r.jsxs("select",{value:fe,onChange:Ae=>ae(Ae.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")}),Ue.map(Ae=>r.jsx("option",{value:Ae,children:Ae.toUpperCase()},Ae))]})]}),o&&r.jsxs("div",{className:"relative",children:[r.jsx("input",{type:"text",placeholder:t("fileManager.filterByUser",{defaultValue:"Filter by user"}),value:pe,onChange:Ae=>$(Ae.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 ${pe?"pr-7":""}`,style:pe?{WebkitAppearance:"none",MozAppearance:"textfield"}:void 0}),pe&&r.jsx("button",{onClick:()=>$(""),className:"absolute right-2 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white z-10",children:r.jsx($t,{className:"w-3 h-3"})}),r.jsx("datalist",{id:"usernames-list",children:Ke?.map(Ae=>r.jsx("option",{value:Ae.username},Ae.id))})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsxs("select",{value:R,onChange:Ae=>{const Ve=Ae.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(Ae=>{const Ve=Ae==="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(be==="asc"?"fileManager.ascending":"fileManager.descending"),children:be==="asc"?r.jsx($fe,{className:"w-4 h-4 text-white"}):r.jsx(Ife,{className:"w-4 h-4 text-white"})})]}),(se||fe!=="all"||pe)&&r.jsx("span",{className:"text-sm text-bambu-gray hidden sm:inline",children:t("fileManager.resultsCount",{showing:lt.length,total:Le.length})})]}),lt.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===lt.length&&f.length>0?r.jsxs(je,{variant:"secondary",size:"sm",onClick:ia,children:[r.jsx(lo,{className:"w-4 h-4 sm:mr-1"}),r.jsx("span",{className:"hidden sm:inline",children:t("fileManager.deselectAll")})]}):r.jsxs(je,{variant:"secondary",size:"sm",onClick:Xt,children:[r.jsx(ws,{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:[gt.length===1&&r.jsxs(je,{variant:"primary",size:"sm",onClick:()=>ee(gt[0]),disabled:!n("printers:control"),title:n("printers:control")?void 0:t("fileManager.noPermissionPrint"),children:[r.jsx(ys,{className:"w-4 h-4 sm:mr-1"}),r.jsx("span",{className:"hidden sm:inline",children:t("common.print")})]}),gt.length===1&&r.jsxs(je,{variant:"secondary",size:"sm",onClick:()=>le(gt[0]),disabled:!n("queue:create"),title:n("queue:create")?void 0:t("fileManager.noPermissionAddToQueue"),children:[r.jsx(Za,{className:"w-4 h-4 sm:mr-1"}),r.jsx("span",{className:"hidden sm:inline",children:t("fileManager.schedulePrint")})]}),r.jsxs(je,{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(aye,{className:"w-4 h-4 sm:mr-1"}),r.jsx("span",{className:"hidden sm:inline",children:t("common.move")})]}),r.jsxs(je,{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(ea,{className:"w-4 h-4 sm:mr-1"}),r.jsx("span",{className:"hidden sm:inline",children:t("common.delete")})]}),r.jsxs(je,{variant:"secondary",size:"sm",onClick:ia,children:[r.jsx($t,{className:"w-4 h-4 sm:mr-1"}),r.jsx("span",{className:"hidden sm:inline",children:t("common.clear")})]})]})]})]}),Nt?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")})]})}):Le?.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(Ah,{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(je,{onClick:()=>T(!0),disabled:!n("library:upload"),title:n("library:upload")?void 0:t("fileManager.noPermissionUpload"),children:[r.jsx(er,{className:"w-4 h-4 mr-2"}),t("fileManager.uploadFiles")]})]}):lt.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(fr,{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(je,{variant:"secondary",onClick:()=>{oe(""),ae("all")},children:t("fileManager.clearFilters")})]}):J==="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:lt.map(Ae=>r.jsx(rst,{file:Ae,isSelected:f.includes(Ae.id),isMobile:ke,t,onSelect:Qt,onDelete:Ve=>I({type:"file",id:Ve}),onDownload:ut,onAddToQueue:Ve=>{const Je=Le?.find(De=>De.id===Ve);Je&&le(Je)},onPrint:L,onSlice:me,useSlicerApi:ye?.use_slicer_api??!1,onPreview3d:Ve=>{Pw(Ve.filename)?c(`/gcode-viewer?library_file=${Ve.id}`):H(Ve)},onRename:Ve=>ce({type:"file",id:Ve.id,name:Ve.filename}),onGenerateThumbnail:Ve=>At.mutate(Ve.id),thumbnailVersion:he[Ae.id],hasPermission:n,canModify:s,authEnabled:o},Ae.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",{})]}),lt.map(Ae=>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(Ae.id)?"bg-bambu-green/10":""}`,onClick:()=>Qt(Ae.id),children:[r.jsx("div",{className:`w-5 h-5 rounded border-2 flex items-center justify-center ${f.includes(Ae.id)?"bg-bambu-green border-bambu-green":"border-bambu-gray/50"}`,children:f.includes(Ae.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:Ae.thumbnail_path?r.jsx("img",{src:`${re.getLibraryFileThumbnailUrl(Ae.id)}${he[Ae.id]?(re.getLibraryFileThumbnailUrl(Ae.id).includes("?")?"&":"?")+`v=${he[Ae.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(Ah,{className:"w-5 h-5 text-bambu-gray/50"})})}),Ae.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:`${re.getLibraryFileThumbnailUrl(Ae.id)}${he[Ae.id]?(re.getLibraryFileThumbnailUrl(Ae.id).includes("?")?"&":"?")+`v=${he[Ae.id]}`:""}`,alt:Ae.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:Ae.print_name||Ae.filename})})]}),o&&r.jsx("div",{className:"text-sm text-bambu-gray flex items-center gap-1",children:Ae.created_by_username?r.jsxs(r.Fragment,{children:[r.jsx(Xm,{className:"w-3 h-3"}),r.jsx("span",{className:"truncate",children:Ae.created_by_username})]}):"-"}),r.jsx("div",{children:r.jsx("span",{className:`text-xs px-1.5 py-0.5 rounded font-medium ${Ae.file_type==="3mf"?"bg-bambu-green/20 text-bambu-green":Ae.file_type==="gcode"?"bg-blue-500/20 text-blue-400":Ae.file_type==="stl"?"bg-purple-500/20 text-purple-400":"bg-bambu-gray/20 text-bambu-gray"}`,children:Ae.file_type.toUpperCase()})}),r.jsx("div",{className:"text-sm text-bambu-gray",children:ps(Ae.file_size)}),r.jsx("div",{className:"text-sm text-bambu-gray",children:Ae.print_count>0?`${Ae.print_count}x`:"-"}),r.jsxs("div",{className:"flex items-center gap-1",onClick:Ve=>Ve.stopPropagation(),children:[Pw(Ae.filename)&&r.jsxs(r.Fragment,{children:[r.jsx("button",{onClick:()=>n("printers:control")&&L(Ae),className:`p-1.5 rounded transition-colors ${n("printers:control")?"hover:bg-bambu-dark text-bambu-gray hover:text-bambu-green":"text-bambu-gray/50 cursor-not-allowed"}`,title:n("printers:control")?t("common.print"):t("fileManager.noPermissionPrint"),disabled:!n("printers:control"),children:r.jsx(gr,{className:"w-4 h-4"})}),r.jsx("button",{onClick:()=>{n("queue:create")&&le(Ae)},className:`p-1.5 rounded transition-colors ${n("queue:create")?"hover:bg-bambu-dark text-bambu-gray hover:text-white":"text-bambu-gray/50 cursor-not-allowed"}`,title:n("queue:create")?t("fileManager.schedulePrint"):t("fileManager.noPermissionAddToQueue"),disabled:!n("queue:create"),children:r.jsx(Za,{className:"w-4 h-4"})})]}),(ye?.use_slicer_api??!1)&&dde(Ae.filename)&&r.jsx("button",{onClick:()=>n("library:upload")&&me(Ae),className:`p-1.5 rounded transition-colors ${n("library:upload")?"hover:bg-bambu-dark text-bambu-gray hover:text-bambu-green":"text-bambu-gray/50 cursor-not-allowed"}`,title:n("library:upload")?t("slice.action"):t("fileManager.noPermissionSlice"),disabled:!n("library:upload"),children:r.jsx(du,{className:"w-4 h-4"})}),(Ae.file_type==="3mf"||Ae.file_type==="gcode"||Ae.file_type==="stl")&&r.jsx("button",{onClick:()=>{n("library:read")&&(Pw(Ae.filename)?c(`/gcode-viewer?library_file=${Ae.id}`):H(Ae))},className:`p-1.5 rounded transition-colors ${n("library:read")?"hover:bg-bambu-dark text-bambu-gray hover:text-bambu-green":"text-bambu-gray/50 cursor-not-allowed"}`,title:n("library:read")?"3D Preview":"You do not have permission to preview files",disabled:!n("library:read"),children:r.jsx(Mi,{className:"w-4 h-4"})}),r.jsx("button",{onClick:()=>n("library:read")&&ut(Ae.id),className:`p-1.5 rounded transition-colors ${n("library:read")?"hover:bg-bambu-dark text-bambu-gray hover:text-white":"text-bambu-gray/50 cursor-not-allowed"}`,title:n("library:read")?t("common.download"):t("fileManager.noPermissionDownload"),disabled:!n("library:read"),children:r.jsx(Ur,{className:"w-4 h-4"})}),r.jsx("button",{onClick:()=>s("library","update",Ae.created_by_id)&&ce({type:"file",id:Ae.id,name:Ae.filename}),className:`p-1.5 rounded transition-colors ${s("library","update",Ae.created_by_id)?"hover:bg-bambu-dark text-bambu-gray hover:text-white":"text-bambu-gray/50 cursor-not-allowed"}`,title:s("library","update",Ae.created_by_id)?t("common.rename"):t("fileManager.noPermissionRenameFile"),disabled:!s("library","update",Ae.created_by_id),children:r.jsx(yi,{className:"w-4 h-4"})}),Ae.file_type==="stl"&&r.jsx("button",{onClick:()=>s("library","update",Ae.created_by_id)&&At.mutate(Ae.id),className:`p-1.5 rounded transition-colors ${s("library","update",Ae.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",Ae.created_by_id)?t("fileManager.generateThumbnail"):t("fileManager.noPermissionGenerateThumbnail"),disabled:At.isPending||!s("library","update",Ae.created_by_id),children:r.jsx(uu,{className:"w-4 h-4"})}),r.jsx("button",{onClick:()=>s("library","delete",Ae.created_by_id)&&I({type:"file",id:Ae.id}),className:`p-1.5 rounded transition-colors ${s("library","delete",Ae.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",Ae.created_by_id)?t("common.delete"):t("fileManager.noPermissionDeleteFile"),disabled:!s("library","delete",Ae.created_by_id),children:r.jsx(ea,{className:"w-4 h-4"})})]})]},Ae.id))]})})]})]}),w&&r.jsx(Zit,{parentId:m,onClose:()=>b(!1),onSave:Ae=>st.mutate(Ae),isLoading:st.isPending,t}),x&&r.jsx(Jit,{onClose:()=>S(!1),onSave:Ae=>Ne.mutate(Ae),isLoading:Ne.isPending,t}),N&&ge&&r.jsx(tst,{folders:ge,selectedFiles:f,currentFolderId:m,onClose:()=>C(!1),onMove:Ae=>et.mutate({fileIds:f,folderId:Ae}),isLoading:et.isPending,t}),P&&r.jsx(lse,{folderId:m,onClose:()=>T(!1),onUploadComplete:da}),j&&r.jsx(Xit,{onClose:()=>F(!1)}),k&&r.jsx(ast,{folder:k,onClose:()=>M(null),onLink:Ae=>We.mutate({id:k.id,data:Ae}),isLoading:We.isPending,t}),q&&r.jsx(wa,{title:q.type==="folder"?t("fileManager.deleteFolder"):q.type==="bulk"?t("fileManager.deleteFilesCount",{count:q.count}):t("fileManager.deleteFile"),message:q.type==="folder"?t("fileManager.deleteFolderConfirm"):q.type==="bulk"?t("fileManager.deleteFilesConfirm",{count:q.count}):t("fileManager.deleteFileConfirm"),confirmText:t("common.delete"),variant:"danger",isLoading:Ct,loadingText:t("fileManager.deleting"),onConfirm:_t,onCancel:()=>I(null)}),O&&r.jsx(wc,{mode:"reprint",libraryFileId:O.id,archiveName:O.print_name||O.filename,onClose:()=>L(null),onSuccess:()=>{L(null),e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["archives"]})}}),X&&r.jsx(wc,{mode:"reprint",libraryFileId:X.id,archiveName:X.print_name||X.filename,onClose:()=>ee(null),onSuccess:()=>{ee(null),g([]),e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["archives"]})}}),Q&&r.jsx(wc,{mode:"add-to-queue",libraryFileId:Q.id,archiveName:Q.print_name||Q.filename,onClose:()=>le(null),onSuccess:()=>{le(null),g([]),e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["queue"]}),e.invalidateQueries({queryKey:["archives"]})}}),de&&r.jsx($A,{source:{kind:"libraryFile",id:de.id,filename:de.filename},onClose:()=>me(null)}),xe&&r.jsx(Qit,{libraryFileId:xe.id,title:xe.print_name||xe.filename,fileType:xe.file_type,onClose:()=>H(null)}),Z&&r.jsx(est,{type:Z.type,currentName:Z.name,onClose:()=>ce(null),onSave:Ae=>{Z.type==="file"?Pe.mutate({id:Z.id,filename:Ae}):at.mutate({id:Z.id,name:Ae})},isLoading:Pe.isPending||at.isPending,t})]})}function ist(t){const e=Qa(t);if(!e)return"";const a=Math.ceil((e.getTime()-Date.now())/(1e3*60*60*24));return a<=0?"any moment":a===1?"1 day":`${a} days`}function MX(t){const e=Qa(t);return e?e.toLocaleString():t}function sst(){const{t}=vt(),e=Oi(),a=ta(),{showToast:n}=na(),{hasPermission:i,authEnabled:s}=dr(),[o,l]=y.useState(null),[c,d]=y.useState(new Set),u=!s||i("library:purge"),m=Qe({queryKey:["library-trash"],queryFn:()=>re.listLibraryTrash(200,0)}),p=Qe({queryKey:["library-trash-settings"],queryFn:()=>re.getLibraryTrashSettings(),enabled:u}),[f,g]=y.useState(null);y.useEffect(()=>{p.data&&f===null&&g(p.data.retention_days)},[p.data,f]);const w=ot({mutationFn:O=>{const L=p.data;return re.updateLibraryTrashSettings({retention_days:O,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:O=>{n(t("libraryTrash.toast.retentionSaved",{days:O.retention_days}),"success"),a.invalidateQueries({queryKey:["library-trash-settings"]}),a.invalidateQueries({queryKey:["library-trash"]})},onError:O=>n(O.message||t("libraryTrash.toast.retentionFailed"),"error")}),b=ot({mutationFn:O=>re.restoreLibraryTrash(O),onSuccess:()=>{n(t("libraryTrash.toast.restored"),"success"),a.invalidateQueries({queryKey:["library-trash"]}),a.invalidateQueries({queryKey:["library-trash-count"]}),a.invalidateQueries({queryKey:["library-files"]}),a.invalidateQueries({queryKey:["library-folders"]})},onError:O=>n(O.message||t("libraryTrash.toast.restoreFailed"),"error")}),x=ot({mutationFn:O=>re.hardDeleteLibraryTrash(O),onSuccess:()=>{n(t("libraryTrash.toast.purged"),"success"),a.invalidateQueries({queryKey:["library-trash"]}),a.invalidateQueries({queryKey:["library-trash-count"]})},onError:O=>n(O.message||t("libraryTrash.toast.purgeFailed"),"error")}),S=ot({mutationFn:()=>re.emptyLibraryTrash(),onSuccess:O=>{n(t("libraryTrash.toast.emptied",{count:O.deleted}),"success"),a.invalidateQueries({queryKey:["library-trash"]}),a.invalidateQueries({queryKey:["library-trash-count"]})},onError:O=>n(O.message||t("libraryTrash.toast.emptyFailed"),"error")}),N=ot({mutationFn:O=>Promise.all(O.map(L=>re.restoreLibraryTrash(L))),onSuccess:(O,L)=>{n(t("libraryTrash.toast.bulkRestored",{count:L.length}),"success"),d(new Set),a.invalidateQueries({queryKey:["library-trash"]}),a.invalidateQueries({queryKey:["library-trash-count"]}),a.invalidateQueries({queryKey:["library-files"]}),a.invalidateQueries({queryKey:["library-folders"]})},onError:O=>n(O.message||t("libraryTrash.toast.restoreFailed"),"error")}),C=ot({mutationFn:O=>Promise.all(O.map(L=>re.hardDeleteLibraryTrash(L))),onSuccess:(O,L)=>{n(t("libraryTrash.toast.bulkPurged",{count:L.length}),"success"),d(new Set),a.invalidateQueries({queryKey:["library-trash"]}),a.invalidateQueries({queryKey:["library-trash-count"]})},onError:O=>n(O.message||t("libraryTrash.toast.purgeFailed"),"error")}),P=y.useMemo(()=>m.data?.items??[],[m.data?.items]),T=m.data?.retention_days??30,j=y.useMemo(()=>P.reduce((O,L)=>O+L.file_size,0),[P]),F=P.length>0&&P.every(O=>c.has(O.id)),k=c.size>0&&!F,M=O=>{d(L=>{const X=new Set(L);return X.has(O)?X.delete(O):X.add(O),X})},q=()=>{d(O=>O.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(PT,{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(je,{variant:"secondary",onClick:()=>l({type:"empty"}),className:"text-red-600 dark:text-red-400",children:[r.jsx(ea,{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:O=>g(Math.max(1,Math.min(365,parseInt(O.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(je,{variant:"secondary",onClick:()=>f!=null&&w.mutate(f),disabled:w.isPending||f==null||f===p.data.retention_days,className:"ml-auto",children:[r.jsx(fs,{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:ps(j)})}),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(je,{variant:"secondary",onClick:()=>N.mutate(Array.from(c)),disabled:N.isPending,children:[r.jsx(vs,{className:"w-4 h-4 mr-1"}),t("libraryTrash.bulkRestore")]}),r.jsxs(je,{variant:"secondary",onClick:()=>l({type:"bulkDelete",count:c.size}),disabled:C.isPending,className:"text-red-600 dark:text-red-400",children:[r.jsx(ea,{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:O=>{O&&(O.indeterminate=k)},onChange:q,"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(O=>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(O.id),onChange:()=>M(O.id),"aria-label":t("libraryTrash.selectOne",{filename:O.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:O.filename,children:O.filename}),r.jsx("td",{className:"px-3 py-2 text-gray-600 dark:text-gray-400",children:O.folder_name??"—"}),r.jsx("td",{className:"px-3 py-2 text-right text-gray-600 dark:text-gray-400 tabular-nums whitespace-nowrap",children:ps(O.file_size)}),r.jsx("td",{className:"px-3 py-2 text-gray-600 dark:text-gray-400 whitespace-nowrap",children:MX(O.deleted_at)}),r.jsx("td",{className:"px-3 py-2 text-gray-600 dark:text-gray-400 whitespace-nowrap",children:r.jsx("span",{title:MX(O.auto_purge_at),children:t("libraryTrash.autoPurgeIn",{when:ist(O.auto_purge_at)})})}),u&&r.jsx("td",{className:"px-3 py-2 text-gray-600 dark:text-gray-400",children:O.created_by_username??"—"}),r.jsxs("td",{className:"px-3 py-2 text-right whitespace-nowrap",children:[r.jsxs("button",{onClick:()=>b.mutate(O.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(vs,{className:"w-3.5 h-3.5"}),t("libraryTrash.restore")]}),r.jsxs("button",{onClick:()=>l({type:"delete",id:O.id,filename:O.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(ea,{className:"w-3.5 h-3.5"}),t("libraryTrash.purgeNow")]})]})]},O.id))})]})})]}),o&&r.jsx(wa,{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(je,{variant:"secondary",onClick:()=>e("/files"),className:"ml-3",children:t("libraryTrash.backToFiles")})]})]})}function ost(t,e){const a=`token=${encodeURIComponent(e)}`;let n=0;return t.querySelectorAll('img[src*="/api/v1/"], video[src*="/api/v1/"]').forEach(i=>{const s=i.getAttribute("src")||"";if(s.includes(a))return;const o=s.replace(/([?&])token=[^&]*(&|$)/,(c,d,u)=>u==="&"?d:""),l=o.includes("?")?"&":"?";i.src=`${o}${l}${a}`,n+=1}),n}function ude(){const{authEnabled:t,user:e}=dr(),a=ta(),n=y.useRef(!1),{data:i}=Qe({queryKey:["camera-stream-token",e?.id??null],queryFn:()=>re.getCameraStreamToken(),enabled:t?!!e:!0,staleTime:3e3*1e3,refetchInterval:3e3*1e3});y.useEffect(()=>{const s=i?.token??null;return _8(s),s&&ost(document,s),()=>_8(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=oJ();!d||!c.includes(`token=${encodeURIComponent(d)}`)||n.current||(n.current=!0,a.invalidateQueries({queryKey:["camera-stream-token"]}),setTimeout(()=>{n.current=!1},5e3))};return document.addEventListener("error",s,!0),()=>document.removeEventListener("error",s,!0)},[t,a])}const bN=5,lst=2e3,cst=3e4,dst=5e3;function ust(){const{t}=vt(),e=ta(),{showToast:a}=na(),{hasPermission:n,authEnabled:i,user:s}=dr(),{printerId:o}=TS(),l=parseInt(o||"0",10),[c]=lb(),d=parseInt(c.get("fps")||"15",10),u=Math.min(Math.max(isNaN(d)?15:d,1),30);ude();const{data:m}=Qe({queryKey:["camera-stream-token",s?.id??null],queryFn:()=>re.getCameraStreamToken(),enabled:i?!!s:!0,staleTime:3e3*1e3}),p=m?.token??oJ(),[f,g]=y.useState("stream"),[w,b]=y.useState(!1),[x,S]=y.useState(!1),[N,C]=y.useState(!1),[P,T]=y.useState(!0),[j,F]=y.useState(Date.now()),[k,M]=y.useState(!1),[q,I]=y.useState(!1),[O,L]=y.useState(0),[X,ee]=y.useState(!1),[Q,le]=y.useState(0),[de,me]=y.useState(1),[Z,ce]=y.useState({x:0,y:0}),[he,ue]=y.useState(!1),[xe,H]=y.useState({x:0,y:0}),[J,A]=y.useState(null),[E,B]=y.useState(null),W=y.useRef(null),z=y.useRef(null),ie=y.useRef(null),U=y.useRef(null),G=y.useRef(null),{data:K}=Qe({queryKey:["printer",l],queryFn:()=>re.getPrinter(l),enabled:l>0}),{data:Y}=Qe({queryKey:["printerStatus",l],queryFn:()=>re.getPrinterStatus(l),refetchInterval:3e4,enabled:l>0}),se=ot({mutationFn:Fe=>re.setChamberLight(l,Fe),onMutate:async Fe=>{await e.cancelQueries({queryKey:["printerStatus",l]});const et=e.getQueryData(["printerStatus",l]);return e.setQueryData(["printerStatus",l],We=>({...We,chamber_light:Fe})),{previousStatus:et}},onSuccess:(Fe,et)=>{a(`Chamber light ${et?"on":"off"}`)},onError:(Fe,et,We)=>{We?.previousStatus&&e.setQueryData(["printerStatus",l],We.previousStatus),a(Fe.message||t("printers.toast.failedToControlChamberLight"),"error")}}),oe=(Y?.state==="RUNNING"||Y?.state==="PAUSE")&&(Y?.printable_objects_count??0)>=2;y.useEffect(()=>(K&&(document.title=`${K.name} - Camera`),()=>{document.title="Bambuddy"}),[K]);const fe=y.useRef(!1);y.useEffect(()=>{const Fe=`/api/v1/printers/${l}/camera/stop`;fe.current=!1;const et=()=>{if(l>0&&!fe.current){fe.current=!0;const at={},nt=Jm();nt&&(at.Authorization=`Bearer ${nt}`),fetch(Fe,{method:"POST",keepalive:!0,headers:at}).catch(()=>{})}},We=()=>{et()};window.addEventListener("beforeunload",We);const Pe=W.current;return()=>{window.removeEventListener("beforeunload",We),Pe&&(Pe.src=""),et()}},[l]),y.useEffect(()=>{if(P&&!k){const et=setTimeout(()=>{T(!1)},f==="stream"?3e3:2e4);return()=>clearTimeout(et)}},[f,P,j,k]),y.useEffect(()=>{const Fe=()=>{const et=!!document.fullscreenElement;I(et),me(1),ce({x:0,y:0}),f==="stream"&&!k&&(W.current&&(W.current.src=""),setTimeout(()=>{T(!0),F(Date.now())},200))};return document.addEventListener("fullscreenchange",Fe),()=>document.removeEventListener("fullscreenchange",Fe)},[f,k]),y.useEffect(()=>{let Fe;const et=()=>{clearTimeout(Fe),Fe=setTimeout(()=>{localStorage.setItem("cameraWindowState",JSON.stringify({width:window.outerWidth,height:window.outerHeight,left:window.screenX,top:window.screenY}))},500)};return window.addEventListener("resize",et),()=>{clearTimeout(Fe),window.removeEventListener("resize",et)}},[]),y.useEffect(()=>()=>{ie.current&&clearTimeout(ie.current),U.current&&clearInterval(U.current),G.current&&clearInterval(G.current)},[]);const ae=y.useCallback(()=>{if(O>=bN){ee(!1),C(!0);return}const Fe=Math.min(lst*Math.pow(2,O),cst);ee(!0),le(Math.ceil(Fe/1e3)),U.current=setInterval(()=>{le(et=>et<=1?(U.current&&clearInterval(U.current),0):et-1)},1e3),ie.current=setTimeout(()=>{L(et=>et+1),ee(!1),T(!0),C(!1),W.current&&(W.current.src=""),F(Date.now())},Fe)},[O]);y.useEffect(()=>{if(f!=="stream"||P||X||k){G.current&&(clearInterval(G.current),G.current=null);return}return G.current=setInterval(async()=>{try{const Fe=await re.getCameraStatus(l);(Fe.stalled||!Fe.active&&!N)&&(console.log(`Stream issue detected: stalled=${Fe.stalled}, active=${Fe.active}, reconnecting...`),G.current&&(clearInterval(G.current),G.current=null),T(!1),ae())}catch{}},dst),()=>{G.current&&(clearInterval(G.current),G.current=null)}},[f,P,N,X,k,l,ae]);const pe=()=>{T(!1),f==="stream"&&O{if(T(!1),C(!1),L(0),ee(!1),ie.current&&clearTimeout(ie.current),U.current&&clearInterval(U.current),W.current&&!localStorage.getItem("cameraWindowState")){const Fe=W.current,et=Fe.naturalWidth,We=Fe.naturalHeight;if(et>0&&We>0){const nt=window.outerWidth-window.innerWidth,At=window.outerHeight-window.innerHeight,Bt=et+16+nt,gt=We+45+16+At;try{window.resizeTo(Bt,gt)}catch{}}}},R=()=>{if(l>0){const Fe={},et=Jm();et&&(Fe.Authorization=`Bearer ${et}`),fetch(`/api/v1/printers/${l}/camera/stop`,{method:"POST",headers:Fe}).catch(()=>{})}},ne=Fe=>{f===Fe||k||(M(!0),T(!0),C(!1),L(0),ee(!1),me(1),ce({x:0,y:0}),ie.current&&clearTimeout(ie.current),U.current&&clearInterval(U.current),W.current&&(W.current.src=""),f==="stream"&&R(),setTimeout(()=>{g(Fe),F(Date.now()),M(!1)},100))},be=()=>{k||(M(!0),T(!0),C(!1),L(0),ee(!1),ie.current&&clearTimeout(ie.current),U.current&&clearInterval(U.current),W.current&&(W.current.src=""),f==="stream"&&R(),setTimeout(()=>{F(Date.now()),M(!1)},100))},ve=()=>{z.current&&(document.fullscreenElement?document.exitFullscreen():z.current.requestFullscreen())},ke=()=>{me(Fe=>Math.min(Fe+.5,4))},ye=()=>{me(Fe=>{const et=Math.max(Fe-.5,1);return et===1&&ce({x:0,y:0}),et})},ge=Fe=>{Fe.preventDefault(),Fe.deltaY<0?ke():ye()},Me=Fe=>{de>1&&(Fe.preventDefault(),ue(!0),H({x:Fe.clientX-Z.x,y:Fe.clientY-Z.y}))},Be=y.useCallback(()=>{if(!z.current)return{x:300,y:200};const Fe=z.current.getBoundingClientRect(),et=Fe.width*(de-1)/2,We=Fe.height*(de-1)/2;return{x:Math.max(50,et),y:Math.max(50,We)}},[de]),Le=Fe=>{if(he&&de>1){const et=Fe.clientX-xe.x,We=Fe.clientY-xe.y,Pe=Be();ce({x:Math.max(-Pe.x,Math.min(Pe.x,et)),y:Math.max(-Pe.y,Math.min(Pe.y,We))})}},Oe=()=>{ue(!1)},Re=Fe=>{if(Fe.length<2)return 0;const et=Fe[0].clientX-Fe[1].clientX,We=Fe[0].clientY-Fe[1].clientY;return Math.sqrt(et*et+We*We)},Ke=Fe=>Fe.length<2?{x:Fe[0].clientX,y:Fe[0].clientY}:{x:(Fe[0].clientX+Fe[1].clientX)/2,y:(Fe[0].clientY+Fe[1].clientY)/2},Ue=Fe=>{Fe.touches.length===2?(Fe.preventDefault(),A(Re(Fe.touches)),B(Ke(Fe.touches))):Fe.touches.length===1&&de>1&&(Fe.preventDefault(),ue(!0),H({x:Fe.touches[0].clientX-Z.x,y:Fe.touches[0].clientY-Z.y}))},lt=Fe=>{if(Fe.touches.length===2&&J!==null){Fe.preventDefault();const et=Re(Fe.touches),We=et/J;me(at=>{const nt=Math.max(1,Math.min(4,at*We));return nt===1&&ce({x:0,y:0}),nt}),A(et);const Pe=Ke(Fe.touches);if(E){const at=Be();ce(nt=>({x:Math.max(-at.x,Math.min(at.x,nt.x+(Pe.x-E.x))),y:Math.max(-at.y,Math.min(at.y,nt.y+(Pe.y-E.y)))}))}B(Pe)}else if(Fe.touches.length===1&&he&&de>1){Fe.preventDefault();const et=Fe.touches[0].clientX-xe.x,We=Fe.touches[0].clientY-xe.y,Pe=Be();ce({x:Math.max(-Pe.x,Math.min(Pe.x,et)),y:Math.max(-Pe.y,Math.min(Pe.y,We))})}},Ee=Fe=>{Fe.touches.length<2&&(A(null),B(null)),Fe.touches.length===0&&ue(!1)},st=()=>{me(1),ce({x:0,y:0})},Ne=i&&!p,Ze=Fe=>p?`${Fe}&token=${encodeURIComponent(p)}`:Fn(Fe),Ye=k||Ne?"":Ze(f==="stream"?`/api/v1/printers/${l}/camera/stream?fps=${u}&t=${j}`:`/api/v1/printers/${l}/camera/snapshot?t=${j}`),Te=P||k||X;return l?r.jsxs("div",{ref:z,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(yy,{className:"w-4 h-4"}),K?.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:()=>ne("stream"),disabled:Te,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:()=>ne("snapshot"),disabled:Te,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:()=>se.mutate(!Y?.chamber_light),disabled:!Y?.connected||se.isPending||!n("printers:control"),className:`p-1.5 rounded disabled:opacity-50 ${Y?.chamber_light?"bg-yellow-500/20 hover:bg-yellow-500/30":"hover:bg-bambu-dark-tertiary"}`,title:n("printers:control")?t("camera.chamberLight"):t("printers.permission.noControl"),children:r.jsx(f4,{on:Y?.chamber_light??!1,className:"w-4 h-4"})}),r.jsx("button",{onClick:()=>b(!0),disabled:!oe||!n("printers:control"),className:`p-1.5 rounded disabled:opacity-50 ${oe&&n("printers:control")?"hover:bg-bambu-dark-tertiary":""}`,title:n("printers:control")?t(oe?"printers.skipObjects.tooltip":"printers.skipObjects.onlyWhilePrinting"):t("printers.permission.noControl"),children:r.jsx(WT,{className:"w-4 h-4 text-bambu-gray"})}),r.jsx("button",{onClick:be,disabled:Te,className:"p-1.5 hover:bg-bambu-dark-tertiary rounded disabled:opacity-50",title:t(f==="stream"?"camera.restartStream":"camera.refreshSnapshot"),children:r.jsx(Xa,{className:`w-4 h-4 text-bambu-gray ${Te?"animate-spin":""}`})}),r.jsx("button",{onClick:()=>S(!0),className:"p-1.5 hover:bg-bambu-dark-tertiary rounded",title:t("camera.diagnose.button"),children:r.jsx(Dl,{className:"w-4 h-4 text-bambu-gray"})}),r.jsx("button",{onClick:ve,className:"p-1.5 hover:bg-bambu-dark-tertiary rounded",title:t(q?"camera.exitFullscreen":"camera.fullscreen"),children:q?r.jsx(YZ,{className:"w-4 h-4 text-bambu-gray"}):r.jsx(Vxe,{className:"w-4 h-4 text-bambu-gray"})})]})]}),r.jsx("div",{className:"flex-1 flex items-center justify-center p-2 overflow-hidden",onWheel:ge,onMouseMove:Le,onMouseUp:Oe,onMouseLeave:Oe,onTouchStart:Ue,onTouchMove:lt,onTouchEnd:Ee,style:{touchAction:"none"},children:r.jsxs("div",{className:"relative w-full h-full flex items-center justify-center",children:[(P||k)&&!X&&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(Xa,{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")})]})}),X&&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(pu,{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(O+1,bN),max:bN})}),r.jsx("button",{onClick:be,className:"px-4 py-2 bg-bambu-green text-white text-sm rounded hover:bg-bambu-green/80 transition-colors",children:t("camera.reconnectNow")})]})}),N&&!X&&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(ba,{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.jsxs("div",{className:"flex gap-2 justify-center",children:[r.jsx("button",{onClick:be,className:"px-4 py-2 bg-bambu-green text-white rounded hover:bg-bambu-green/80 transition-colors",children:t("camera.retry")}),r.jsx("button",{onClick:()=>S(!0),className:"px-4 py-2 bg-bambu-dark border border-bambu-dark-tertiary text-bambu-gray hover:text-white rounded transition-colors",children:t("camera.diagnose.button")})]})]})}),r.jsx("img",{ref:W,src:Ye,alt:t("camera.cameraStream"),className:"max-w-full max-h-full object-contain select-none",style:{transform:`scale(${de}) translate(${Z.x/de}px, ${Z.y/de}px) rotate(${K?.camera_rotation||0}deg)`,...K?.camera_rotation===90||K?.camera_rotation===270?{maxWidth:"100vh",maxHeight:"100vw"}:{},cursor:de>1?he?"grabbing":"grab":"default"},onError:Ye?pe:void 0,onLoad:Ye?$:void 0,onMouseDown:Me,draggable:!1},j),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:ye,disabled:de<=1,className:"p-1.5 hover:bg-white/10 rounded disabled:opacity-30",title:t("camera.zoomOut"),children:r.jsx(LO,{className:"w-4 h-4 text-white"})}),r.jsxs("button",{onClick:st,className:"px-2 py-1 text-sm text-white hover:bg-white/10 rounded min-w-[48px]",title:t("camera.resetZoom"),children:[Math.round(de*100),"%"]}),r.jsx("button",{onClick:ke,disabled:de>=4,className:"p-1.5 hover:bg-white/10 rounded disabled:opacity-30",title:t("camera.zoomIn"),children:r.jsx(FO,{className:"w-4 h-4 text-white"})})]})]})}),r.jsx(g4,{printerId:l,isOpen:w,onClose:()=>b(!1)}),x&&r.jsx($ee,{printerId:l,printerName:K?.name||null,onClose:()=>S(!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 mst(t,e,a){if(!t)return"";if(!e)return t;const n=e.match(/plate_(\d+)\.gcode/);return n&&parseInt(n[1],10)>1?`${t} — ${a("printers.plateNumber","Plate {{number}}",{number:n[1]})}`:t}function pst(t){const e=t.get("show")?.split(",")||["progress","layers","eta","filename","status"],a=parseInt(t.get("fps")||"15",10),n=Math.min(Math.max(isNaN(a)?15:a,1),30),i=t.get("camera"),s=i!=="false"&&i!=="0";return{size:t.get("size")||"medium",fps:n,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 hst(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 fst(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 gst(){const{printerId:t}=TS(),[e]=lb(),{t:a}=vt(),n=ta(),i=parseInt(t||"0",10),[s,o]=y.useState(Date.now()),l=y.useMemo(()=>pst(e),[e]),c=fst(l.size),{data:d}=Qe({queryKey:["printer",i],queryFn:()=>re.getPrinter(i),enabled:i>0}),{data:u}=Qe({queryKey:["printerStatus",i],queryFn:()=>re.getPrinterStatus(i),enabled:i>0,refetchInterval:2e3}),{data:m}=Qe({queryKey:["settings"],queryFn:re.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&&n.setQueryData(["printerStatus",i],P.status)}catch{}},N.onerror=()=>{},()=>{N.close()}},[i,n]),y.useEffect(()=>(document.title=d?`${d.name} - ${a("streamOverlay.title")}`:a("streamOverlay.title"),()=>{document.title="Bambuddy"}),[d,a]);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:a("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:a("common.loading")})});const g=u.state==="RUNNING"||u.state==="PAUSE",w=u.progress||0,b=Fn(`/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:a("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(gr,{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:mst(u.current_print.replace(/\.gcode\.3mf$|\.3mf$|\.gcode$/i,""),u.gcode_file,a)}),l.showStatus&&r.jsx("div",{className:`${c.text} text-white/70 mb-2`,children:hst(u,a)}),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:a("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(cn,{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:hs(u.remaining_time*60)})]}),r.jsxs("div",{className:`flex items-center ${c.gap} text-white/70`,children:[r.jsx(Za,{className:c.icon}),r.jsxs("span",{className:`${c.text} text-white`,children:[a("streamOverlay.eta")," ",zO(u.remaining_time,p,a)]})]})]})]}),!g&&r.jsx("div",{className:`${c.text} text-white/70 py-2`,children:u.connected?a("streamOverlay.printerIdle"):a("streamOverlay.printerOffline")})]})})]})}function bst(){const{t}=vt(),{id:e}=TS(),{mode:a}=pb(),{data:n,isLoading:i,error:s}=Qe({queryKey:["external-link",e],queryFn:()=>re.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||!n?r.jsxs("div",{className:"flex flex-col items-center justify-center h-full gap-4 text-bambu-gray",children:[r.jsx(ba,{className:"w-12 h-12"}),r.jsx("p",{children:t("common.linkNotFound")})]}):r.jsx("iframe",{src:n.url,className:"h-full w-full border-0",style:{colorScheme:a},title:n.name,sandbox:"allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox"})}function EX(){const{id:t}=TS(),e=Oi(),a=ta(),{t:n}=vt(),{showToast:i}=na(),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}=Qe({queryKey:["group",t],queryFn:()=>re.getGroup(Number(t)),enabled:s}),{data:S,isLoading:N}=Qe({queryKey:["permissions"],queryFn:()=>re.getPermissions()});s&&b&&!g&&(l(b.name),d(b.description||""),m(b.permissions),w(!0));const C=ot({mutationFn:Q=>re.createGroup(Q),onSuccess:()=>{a.invalidateQueries({queryKey:["groups"]}),a.invalidateQueries({queryKey:["group"]}),i(n("groups.toast.created")),e("/settings?tab=users")},onError:Q=>{i(Q.message,"error")}}),P=ot({mutationFn:Q=>re.updateGroup(Number(t),Q),onSuccess:Q=>{a.invalidateQueries({queryKey:["groups"]}),Q&&a.setQueryData(["group",t],Q),i(n("groups.toast.updated")),e("/settings?tab=users")},onError:Q=>{i(Q.message,"error")}}),T=C.isPending||P.isPending,j=()=>{if(!o.trim()){i(n("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=Q=>{m(le=>le.includes(Q)?le.filter(de=>de!==Q):[...le,Q])},k=(Q,le)=>{const de=Q.permissions.map(me=>me.value);m(me=>{const Z=me.filter(ce=>!de.includes(ce));return le?[...Z,...de]:Z})},M=Q=>Q.permissions.every(le=>u.includes(le.value)),q=Q=>{const le=Q.permissions.filter(de=>u.includes(de.value)).length;return le>0&&le{S&&m(S.all_permissions)},O=()=>{m([])},L=p.toLowerCase(),X=y.useMemo(()=>S?L?S.categories.map(Q=>({...Q,permissions:Q.permissions.filter(le=>le.label.toLowerCase().includes(L))})).filter(Q=>Q.permissions.length>0):S.categories:[],[S,L]),ee=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(PT,{className:"w-5 h-5"})}),r.jsx("h1",{className:"text-xl font-bold text-white",children:n(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(ba,{className:"w-4 h-4 shrink-0"}),n("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:n("groups.form.groupName")}),r.jsx("input",{type:"text",value:o,onChange:Q=>l(Q.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:n("groups.form.groupNamePlaceholder")})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:n("groups.form.description")}),r.jsx("input",{type:"text",value:c,onChange:Q=>d(Q.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:n("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:[n("groups.editor.permissionsSelected",{count:u.length})," / ",ee]}),r.jsx(je,{size:"sm",variant:"ghost",onClick:I,children:n("groups.editor.selectAll")}),r.jsx(je,{size:"sm",variant:"ghost",onClick:O,children:n("groups.editor.clearAll")})]}),r.jsxs("div",{className:"relative",children:[r.jsx(fr,{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:Q=>f(Q.target.value),placeholder:n("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"})]})]}),X.length===0?r.jsx("div",{className:"text-center py-12 text-bambu-gray",children:n("groups.editor.noResults")}):r.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:X.map(Q=>{const le=S.categories.find(he=>he.name===Q.name),de=le.permissions.filter(he=>u.includes(he.value)).length,me=le.permissions.length,Z=M(le),ce=q(le);return r.jsxs(Tt,{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:()=>k(le,!Z),className:`w-5 h-5 rounded border flex items-center justify-center transition-colors shrink-0 ${Z?"bg-bambu-green border-bambu-green":ce?"bg-bambu-green/50 border-bambu-green":"border-bambu-gray hover:border-white"}`,children:[Z&&r.jsx(kr,{className:"w-3 h-3 text-white"}),ce&&!Z&&r.jsx(lC,{className:"w-3 h-3 text-white"})]}),r.jsx(vl,{className:"w-4 h-4 text-bambu-gray shrink-0"}),r.jsx("span",{className:"text-white font-medium text-sm",children:Q.name})]}),r.jsxs("span",{className:"text-xs text-bambu-gray tabular-nums",children:[de,"/",me]})]}),r.jsx("div",{className:"p-3 space-y-1",children:Q.permissions.map(he=>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(he.value),onChange:()=>F(he.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:he.label})]},he.value))})]},Q.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(je,{variant:"secondary",onClick:()=>e("/settings?tab=users"),children:n("common.cancel")}),r.jsx(je,{onClick:j,disabled:T||!o.trim(),children:T?r.jsxs(r.Fragment,{children:[r.jsx(pt,{className:"w-4 h-4 animate-spin"}),n("common.saving")]}):r.jsxs(r.Fragment,{children:[r.jsx(fs,{className:"w-4 h-4"}),n("common.save")]})})]})]})}const xst=1.65,DX=["#1DB954","#3B82F6","#F59E0B","#EF4444","#8B5CF6"];function Tw(t,e,a){return`${t}||${e??""}||${a??""}`}function Gm(t,e){const a=new Date(t);return a.setDate(a.getDate()+Math.round(e)),a}function CS(t){return t.toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})}function Aw(t){return t.toLocaleDateString(void 0,{month:"short",day:"numeric"})}function yst(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()),a=Date.now(),n=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 vst(t){const e=t.reduce((s,o)=>s+Math.max(0,o.weight_used-(o.weight_used_baseline??0)),0);if(e===0)return null;const a=Date.now(),n=t.reduce((s,o)=>{const l=new Date(o.created_at).getTime();return lre.getAllUsageHistory(5e3),staleTime:6e4,enabled:o}),{data:j=[]}=Qe({queryKey:["shopping-list"],queryFn:re.getShoppingList,staleTime:3e4,enabled:o}),F=C?.forecast_global_lead_time_days??0,k=y.useMemo(()=>{const le=new Map;for(const de of P)le.set(Tw(de.material,de.subtype,de.brand),de);return le},[P]),M=y.useMemo(()=>{const le=new Map;for(const de of T){const me=le.get(de.spool_id)??[];me.push(de),le.set(de.spool_id,me)}return le},[T]),q=y.useMemo(()=>{const le=new Map;for(const de of t){if(de.archived_at)continue;const me=Tw(de.material,de.subtype,de.brand),Z=le.get(me)??{key:me,material:de.material,subtype:de.subtype,brand:de.brand,spools:[]};Z.spools.push(de),le.set(me,Z)}return[...le.values()]},[t]),I=y.useMemo(()=>{const le=new Date;return le.setHours(0,0,0,0),q.map(de=>{const me=k.get(de.key)??null,Z=me?.lead_time_days??0,ce=Math.max(F,Z),he=me?.safety_margin_value??14,ue=me?.safety_margin_unit??"days",xe=de.spools.reduce((R,ne)=>R+Math.max(0,ne.label_weight-ne.weight_used),0),H=de.spools.reduce((R,ne)=>R+ne.label_weight,0),J=de.spools.reduce((R,ne)=>R+Math.max(0,ne.weight_used-(ne.weight_used_baseline??0)),0),A=[];for(const R of de.spools)A.push(...M.get(R.id)??[]);let E=null,B=null,W="none";const z=yst(A);if(z!==null)E=z.rate,B=z.stdDev,W="history";else{const R=vst(de.spools);R!==null&&(E=R,W="delta")}const ie=B??(E!==null?E*.2:0),U=xst*ie*Math.sqrt(ce),G=ue==="g"?he:E!==null?E*he:he*5,K=U+G,Y=E!==null?E*ce+K:0,se=E&&E>0?Math.floor(xe/E):null,oe=se!==null?Gm(le,se):null,fe=E&&E>0?Math.floor((xe-Y)/E):null,ae=fe!==null?Gm(le,Math.max(0,fe)):null,pe=se!==null&&ce>0&&se<=ce,$=!pe&&fe!==null&&fe<=0;return{group:de,settings:me,totalRemainingG:xe,totalLabelG:H,totalSpools:de.spools.length,totalUsedG:J,dailyRateG:E,dailyRateStdDev:B,rateTier:W,effectiveLeadTimeDays:ce,safetyStockG:K,reorderPointG:Y,daysRemaining:se,daysUntilROP:fe,projectedEmptyDate:oe,reorderTriggerDate:ae,reorderAlert:$,stockBreakAlert:pe}})},[q,k,M,F]),O=y.useMemo(()=>{const le=[...I];return le.sort((de,me)=>{let Z=0,ce=0;switch(u){case"material":Z=[de.group.material,de.group.subtype??"",de.group.brand??""].join(" ").toLowerCase(),ce=[me.group.material,me.group.subtype??"",me.group.brand??""].join(" ").toLowerCase();break;case"used":Z=de.totalUsedG,ce=me.totalUsedG;break;case"days_left":Z=de.daysRemaining??999999,ce=me.daysRemaining??999999;break;case"stock":Z=de.totalRemainingG,ce=me.totalRemainingG;break}const he=Zce?1:0;return p==="asc"?he:-he}),le},[I,u,p]),L=y.useMemo(()=>I.filter(le=>!le.settings?.alerts_snoozed&&(le.stockBreakAlert||le.reorderAlert)),[I]),X=y.useMemo(()=>[...I].filter(le=>le.dailyRateG!==null).sort((le,de)=>de.totalUsedG-le.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(oc,{className:"w-8 h-8 opacity-40"}),r.jsx("p",{className:"text-sm",children:n("forecast.noReadAccess")})]});function ee(le){u===le?f(de=>de==="asc"?"desc":"asc"):(m(le),f(le==="days_left"?"asc":"desc"))}const Q=j.length>0?j.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(le=>!le),className:`flex items-center gap-2 px-3 py-1.5 rounded-lg border text-sm font-medium transition-colors ${L.some(le=>le.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(ba,{className:"w-4 h-4"}),n("forecast.alertCount",{count:L.length}),c?r.jsx(al,{className:"w-3.5 h-3.5"}):r.jsx(Da,{className:"w-3.5 h-3.5"})]}),l&&r.jsx(Cst,{value:F,onSave:le=>{re.updateSettings({forecast_global_lead_time_days:le}).then(()=>{e.invalidateQueries({queryKey:["settings"]}),a(n("forecast.globalLeadTimeSaved"),"success")})}}),r.jsxs("button",{onClick:()=>x(le=>!le),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(mb,{className:"w-4 h-4"}),r.jsx("span",{className:"hidden sm:inline",children:n("forecast.shoppingList")}),Q&&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:Q})]})]}),c&&L.length>0&&r.jsx("div",{className:"space-y-2",children:L.map(le=>r.jsx(kst,{forecast:le,onCart:()=>w(le)},le.group.key))}),b&&r.jsx(jst,{items:j,forecasts:I,globalLeadTime:F,canWrite:l,onClose:()=>x(!1),onRemove:le=>{re.removeFromShoppingList(le).then(()=>e.invalidateQueries({queryKey:["shopping-list"]})).catch(()=>a(n("forecast.failedSaveSettings"),"error"))},onClear:()=>{re.clearShoppingList().then(()=>e.invalidateQueries({queryKey:["shopping-list"]})).catch(()=>a(n("forecast.failedSaveSettings"),"error"))}}),X.length>0&&r.jsx(Nst,{forecasts:X,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(US,{className:"w-10 h-10 mb-3 opacity-40"}),r.jsx("p",{className:"text-sm",children:n("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(xN,{col:"material",active:u,dir:p,onSort:ee,children:n("forecast.sku")}),r.jsx(xN,{col:"stock",active:u,dir:p,onSort:ee,children:n("forecast.stock")}),r.jsx(xN,{col:"used",active:u,dir:p,onSort:ee,children:n("forecast.dailyRate")}),r.jsx(xN,{col:"days_left",active:u,dir:p,onSort:ee,children:n("forecast.daysLeft")}),r.jsx("th",{className:"px-4 py-3 text-left text-xs font-medium text-bambu-gray uppercase tracking-wide",children:n("forecast.emptyBy")}),r.jsx("th",{className:"px-4 py-3 text-left text-xs font-medium text-bambu-gray uppercase tracking-wide",children:n("forecast.reorderBy")}),r.jsx("th",{className:"w-24 px-4 py-3"})]})}),r.jsx("tbody",{className:"divide-y divide-bambu-dark-tertiary",children:O.map(le=>r.jsx(Pst,{forecast:le,globalLeadTime:F,canWrite:l,onSaved:()=>e.invalidateQueries({queryKey:["sku-settings"]}),onCart:()=>w(le),showToast:a},le.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"}),n("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"}),n("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"}),n("forecast.noDataLegend")]})]})]}),g&&r.jsx(Est,{forecast:g,onClose:()=>w(null),onAdd:le=>{re.addToShoppingList(le).then(()=>{e.invalidateQueries({queryKey:["shopping-list"]}),a(n("forecast.addedToCart"),"success"),w(null),x(!0)}).catch(()=>a(n("forecast.failedAddItem"),"error"))}})]})}function xN({col:t,active:e,dir:a,onSort:n,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:()=>n(t),children:r.jsxs("span",{className:"inline-flex items-center",children:[i,s?a==="asc"?r.jsx(Km,{className:"w-3 h-3 ml-1 text-bambu-green"}):r.jsx(Vh,{className:"w-3 h-3 ml-1 text-bambu-green"}):r.jsx(TT,{className:"w-3 h-3 ml-1 opacity-40"})]})})}function kst({forecast:t,onCart:e}){const{t:a}=vt(),n=[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(ba,{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:n}),i?r.jsxs("span",{className:"ml-2 text-xs opacity-80",children:[a("forecast.stockBreakRisk")," — ",a("forecast.stockBreakDetail",{days:t.daysRemaining,lt:t.effectiveLeadTimeDays})]}):r.jsxs("span",{className:"ml-2 text-xs opacity-80",children:[a("forecast.reorderNow")," — ",a("forecast.reorderTriggerPassed",{date:t.reorderTriggerDate?CS(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(mb,{className:"w-3 h-3"})," ",a("forecast.order")]})]})}const _st=[{label:"1W",value:7},{label:"1M",value:30},{label:"6M",value:180}];function Nst({forecasts:t,days:e,onDaysChange:a}){const{t:n}=vt(),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:DX[m%DX.length],rop:u.reorderPointG,points:wst(u,e)})),o=i.map(u=>{const m={day:u,label:Aw(Gm(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(US,{className:"w-4 h-4 text-bambu-green"}),r.jsx("h3",{className:"text-sm font-semibold text-white",children:n("forecast.chartTitle")}),r.jsx("span",{className:"text-xs text-bambu-gray ml-1 hidden sm:inline",children:n("forecast.dashedLinesROP")}),r.jsx("div",{className:"ml-auto flex items-center bg-bambu-dark-tertiary rounded-lg p-0.5",children:_st.map(u=>r.jsx("button",{onClick:()=>a(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(tu,{width:"100%",height:220,children:r.jsxs(v5,{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(Em,{strokeDasharray:"3 3",stroke:"#374151",strokeOpacity:.5}),r.jsx(Dm,{dataKey:"label",tick:{fill:"#6B7280",fontSize:10},interval:Math.max(0,Math.ceil(l/8)-1),axisLine:!1,tickLine:!1}),r.jsx(Fm,{tick:{fill:"#6B7280",fontSize:10},axisLine:!1,tickLine:!1,tickFormatter:u=>u>=1e3?`${(u/1e3).toFixed(1)}kg`:`${u}g`,width:48}),r.jsx(ru,{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($4,{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(qA,{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(nu,{y:u.rop,stroke:u.color,strokeDasharray:"4 3",strokeOpacity:.6},`rop-${u.key}`))]})})]})}function Cst({value:t,onSave:e}){const{t:a}=vt(),[n,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(Ei,{className:"w-3.5 h-3.5 flex-shrink-0","aria-label":a("forecast.globalLeadTimeHint")}),r.jsxs("span",{className:"hidden sm:inline",children:[a("forecast.globalLeadTime"),":"]}),n?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:a("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(fc,{className:"w-3 h-3"})})]})]})}function Pst({forecast:t,globalLeadTime:e,canWrite:a,onSaved:n,onCart:i,showToast:s}){const{t:o}=vt(),[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=ot({mutationFn:re.upsertSkuSettings,onSuccess:()=>{n(),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",j=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 k(O,L,X,ee=C){N.mutate({material:t.group.material,subtype:t.group.subtype,brand:t.group.brand,lead_time_days:O,safety_margin_value:L,safety_margin_unit:X,alerts_snoozed:ee})}function M(O){O.stopPropagation(),k(t.settings?.lead_time_days??0,t.settings?.safety_margin_value??14,t.settings?.safety_margin_unit??"days",!C)}const q=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(O=>!O),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 ${j>50?"bg-bambu-green":j>20?"bg-yellow-500":"bg-red-500"}`,style:{width:`${Math.min(j,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:q})]}),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?CS(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?CS(t.reorderTriggerDate):"—"})}),r.jsx("td",{className:"px-4 py-3",onClick:O=>O.stopPropagation(),children:r.jsxs("div",{className:"flex items-center justify-end gap-1",children:[a&&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(mb,{className:"w-4 h-4"})}),!C&&(t.stockBreakAlert?r.jsx(ba,{className:"w-4 h-4 text-red-400","aria-label":o("forecast.stockBreakRisk")}):t.reorderAlert?r.jsx(ba,{className:"w-4 h-4 text-yellow-400","aria-label":o("forecast.reorderNow")}):t.daysRemaining!==null?r.jsx(kr,{className:"w-4 h-4 text-bambu-green/50"}):null),a&&r.jsx("button",{onClick:M,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(HZ,{className:"w-3.5 h-3.5"})}),r.jsx("button",{onClick:O=>{O.stopPropagation(),c(L=>!L)},className:"p-1.5 text-bambu-gray hover:text-white rounded transition-colors",children:l?r.jsx(al,{className:"w-4 h-4"}):r.jsx(Da,{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(C3,{label:o("forecast.effectiveLeadTime"),value:`${t.effectiveLeadTimeDays}d`,hint:o("forecast.effectiveLeadTimeHint",{global:e,sku:t.settings?.lead_time_days??0})}),r.jsx(C3,{label:o("forecast.safetyMarginLabel"),value:`${Math.round(t.safetyStockG)}g`,hint:o("forecast.safetyMarginHint")}),r.jsx(C3,{label:o("forecast.reorderPoint"),value:`${Math.round(t.reorderPointG)}g`,hint:o("forecast.reorderPointHint")})]}),a&&r.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[r.jsx(Tst,{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 O=parseInt(f,10);!isNaN(O)&&O>=0&&(k(O,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(Ast,{value:t.settings?.safety_margin_value??14,unit:x,editing:m,inputValue:w,dailyRateG:t.dailyRateG,onInputChange:b,onUnitChange:O=>S(O),onEdit:()=>{b(String(t.settings?.safety_margin_value??14)),S(t.settings?.safety_margin_unit??"days"),p(!0)},onSave:()=>{const O=parseInt(w,10);!isNaN(O)&&O>=0&&(k(t.settings?.lead_time_days??0,O,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(O=>{const L=Math.max(0,O.label_weight-O.weight_used),X=O.label_weight>0?L/O.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:["#",O.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 ${X>50?"bg-bambu-green":X>20?"bg-yellow-500":"bg-red-500"}`,style:{width:`${Math.min(X,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(Math.max(0,O.weight_used-(O.weight_used_baseline??0))),"g"]})}),r.jsx("td",{className:"px-4 py-2",children:r.jsxs("span",{className:"text-sm text-bambu-gray",children:[O.label_weight,"g"]})})]},O.id)})})]})})]})]})})})]})}function C3({label:t,value:e,hint:a}){return r.jsxs("div",{className:"bg-bambu-dark-tertiary/40 rounded-lg p-3",title:a,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 Tst({label:t,hint:e,unit:a,editing:n,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(Ei,{className:"w-3 h-3 text-bambu-gray/50"})})]}),n?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:a}),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:a}),r.jsx("button",{onClick:l,className:"p-1 text-bambu-gray hover:text-white rounded transition-colors",children:r.jsx(fc,{className:"w-3 h-3"})})]})]})}function Ast({value:t,unit:e,editing:a,inputValue:n,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}=vt(),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(Ei,{className:"w-3 h-3 text-bambu-gray/50"})})]}),a?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:n,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(fc,{className:"w-3 h-3"})})]})]})}function jst({items:t,forecasts:e,globalLeadTime:a,canWrite:n,onClose:i,onRemove:s,onClear:o}){const{t:l}=vt(),c=ta(),[d,u]=y.useState("list"),m=ot({mutationFn:async({id:b,status:x,item:S,avgSpoolG:N})=>{if(await re.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 re.bulkCreateSpools(P,S.quantity_spools),await re.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(Tw(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 j=p.get(Tw(T.material,T.subtype,T.brand))??null,F=j&&j.totalSpools>0?j.totalLabelG/j.totalSpools:1e3,k=Math.round(T.quantity_spools*F),M=j?.effectiveLeadTimeDays??a??0,q=M>0?CS(Gm(new Date,M)):"";return[T.quantity_spools,T.material,T.brand??"",T.subtype??"",k,M||"",q,T.status,T.note??""].map(I=>`"${String(I).replace(/"/g,'""')}"`).join(",")}),S=[b.join(","),...x].join(` +`+a+"}"}return String(t)}function jit({setting:t,onClose:e,onDeleted:a,onDuplicate:n,onEdit:i,hasPermission:s,t:o}){const{showToast:l}=na(),c=ta(),[d,u]=y.useState(!1),{data:m,isLoading:p}=Qe({queryKey:["cloudSettingDetail",t.setting_id],queryFn:()=>re.getCloudSettingDetail(t.setting_id)}),f=ot({mutationFn:()=>re.deleteCloudSetting(t.setting_id),onSuccess:()=>{l(o("profiles.presets.toast.deleted")),c.invalidateQueries({queryKey:["cloudSettings"]}),a()},onError:b=>l(b.message,"error")}),g=NS(t.setting_id),w=xU(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(Tt,{className:"w-full max-w-3xl max-h-[90vh] flex flex-col overflow-hidden",children:r.jsxs(Mt,{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($t,{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:iO(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(ba,{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(je,{variant:"secondary",onClick:()=>u(!1),disabled:f.isPending,className:"flex-1",children:o("common.cancel")}),r.jsxs(je,{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(ea,{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(je,{variant:"secondary",onClick:e,className:"flex-1",children:o("common.close")}),r.jsxs(je,{variant:"secondary",onClick:n,disabled:!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.presets.noDuplicatePermission"),children:[r.jsx(xi,{className:"w-4 h-4"}),o("profiles.presets.duplicate")]}),g&&r.jsxs(r.Fragment,{children:[r.jsxs(je,{variant:"secondary",onClick:i,disabled:p||!m||!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.presets.noEditPermission"),children:[r.jsx(yi,{className:"w-4 h-4"}),o("common.edit")]}),r.jsx(je,{variant:"danger",onClick:()=>u(!0),disabled:!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.presets.noDeletePermission"),children:r.jsx(ea,{className:"w-4 h-4"})})]})]})})]})})})}function ide(){try{const t=localStorage.getItem("bambusy_preset_templates");return t?JSON.parse(t):[]}catch{return[]}}function sde(t){localStorage.setItem("bambusy_preset_templates",JSON.stringify(t))}function Mit({onClose:t,onApply:e,t:a}){const{showToast:n}=na(),[i,s]=y.useState(ide),[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(O=>O.type===o),P=O=>{s(O),sde(O)},T=O=>{const L=i.filter(X=>X.id!==O);P(L),N(null),n(a("profiles.templates.toast.deleted"))},j=O=>{d(O.id),m(O.name),f(O.description),w(JSON.stringify(O.settings,null,2)),x(null)},F=()=>{if(!(!c||!u.trim()))try{const O=JSON.parse(g),L=i.map(X=>X.id===c?{...X,name:u.trim(),description:p.trim(),settings:O}:X);P(L),d(null),n(a("profiles.templates.toast.updated"))}catch(O){x(O.message)}},k=()=>{d(null),m(""),f(""),w("{}"),x(null)},M=O=>{const L=i.map(X=>X.id===O?{...X,showInModal:!X.showInModal}:X);P(L)},q={filament:{label:a("profiles.presets.types.filament"),icon:AT,color:"text-amber-400"},print:{label:a("profiles.presets.types.process"),icon:mu,color:"text-blue-400"},printer:{label:a("profiles.presets.types.printer"),icon:gr,color:"text-purple-400"}},I=S?i.find(O=>O.id===S):null;return y.useEffect(()=>{const O=L=>{L.key==="Escape"&&(S?N(null):c?k():t())};return window.addEventListener("keydown",O),()=>window.removeEventListener("keydown",O)},[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(Tt,{className:"w-full max-w-md",children:r.jsxs(Mt,{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(ba,{className:"w-6 h-6 text-red-400"})}),r.jsxs("div",{children:[r.jsx("h3",{className:"text-lg font-semibold text-white",children:a("profiles.templates.deleteTitle")}),r.jsx("p",{className:"text-sm text-bambu-gray",children:a("profiles.templates.deleteWarning")})]})]}),r.jsx("p",{className:"text-white mb-6",children:a("profiles.templates.deleteConfirm",{name:I.name})}),r.jsxs("div",{className:"flex gap-2",children:[r.jsx(je,{variant:"secondary",onClick:()=>N(null),className:"flex-1",children:a("common.cancel")}),r.jsxs(je,{onClick:()=>T(S),className:"flex-1 bg-red-500 hover:bg-red-600",children:[r.jsx(ea,{className:"w-4 h-4"}),a("common.delete")]})]})]})})}),r.jsx(Tt,{className:"w-full max-w-2xl max-h-[80vh] flex flex-col",children:r.jsxs(Mt,{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(Ig,{className:"w-5 h-5 text-amber-400"}),a("profiles.templates.title")]}),r.jsx("button",{onClick:t,className:"text-bambu-gray hover:text-white",children:r.jsx($t,{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:a("profiles.templates.typeFilter")}),["all","filament","print","printer"].map(O=>r.jsx("button",{onClick:()=>l(O),className:`px-3 py-1 text-sm rounded-lg transition-colors ${o===O?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:O==="all"?a("common.all"):q[O].label},O))]}),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(Ig,{className:"w-12 h-12 mx-auto mb-4 opacity-30"}),r.jsx("p",{children:a("profiles.templates.noTemplates")}),r.jsx("p",{className:"text-sm mt-1",children:a("profiles.templates.createFirst")})]}):r.jsx("div",{className:"space-y-2",children:C.map(O=>{const L=q[O.type],X=L.icon;return c===O.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:ee=>m(ee.target.value),placeholder:a("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:ee=>f(ee.target.value),placeholder:a("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:a("profiles.templates.settingsJson")}),r.jsx("textarea",{value:g,onChange:ee=>{w(ee.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(je,{size:"sm",onClick:F,disabled:!u.trim(),children:[r.jsx(fs,{className:"w-4 h-4"}),"Save"]}),r.jsx(je,{size:"sm",variant:"secondary",onClick:k,children:"Cancel"})]})]},O.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(X,{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:O.name}),r.jsx("p",{className:"text-xs text-bambu-gray truncate",children:O.description})]}),r.jsx("span",{className:"text-xs text-bambu-gray-dark px-2 py-1 bg-bambu-dark-secondary rounded",children:a("profiles.templates.fieldsCount",{count:Object.keys(O.settings).length})}),r.jsx("button",{onClick:()=>M(O.id),className:`p-1 transition-colors ${O.showInModal?"text-bambu-green hover:text-bambu-green/70":"text-bambu-gray hover:text-white"}`,title:O.showInModal?a("profiles.templates.shownInModals"):a("profiles.templates.hiddenInModals"),children:O.showInModal?r.jsx(Ml,{className:"w-4 h-4"}):r.jsx(db,{className:"w-4 h-4"})}),r.jsx("button",{onClick:()=>e(O),className:"px-3 py-1 text-xs bg-bambu-green/20 text-bambu-green rounded hover:bg-bambu-green/30 transition-colors",children:a("profiles.templates.apply")}),r.jsx("button",{onClick:()=>j(O),className:"p-1 text-bambu-gray hover:text-white",title:a("common.edit"),children:r.jsx(yi,{className:"w-4 h-4"})}),r.jsx("button",{onClick:()=>N(O.id),className:"p-1 text-bambu-gray hover:text-red-400",title:a("common.delete"),children:r.jsx(ea,{className:"w-4 h-4"})})]},O.id)})})})]})})]})}function ode({onClose:t,leftPreset:e,rightPreset:a,leftLabel:n,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(a)]),w=[];for(const b of g){if(b==="inherits"||b==="version")continue;const x=e[b],S=a[b],N=b in e,C=b in a;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,a]),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(Tt,{className:"w-full max-w-4xl max-h-[85vh] flex flex-col overflow-hidden",children:r.jsxs(Mt,{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(ry,{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($t,{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:n})]}),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(er,{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(lC,{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(rC,{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(gE,{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(fr,{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(gE,{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:n}),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(er,{className:"w-3.5 h-3.5 text-green-400"}),removed:r.jsx(lC,{className:"w-3.5 h-3.5 text-red-400"}),changed:r.jsx(rC,{className:"w-3.5 h-3.5 text-amber-400"}),same:r.jsx(gE,{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 Eit({onClose:t,initialData:e,allPresets:a,t:n}){const{showToast:i}=na(),s=ta(),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),[j,F]=y.useState(""),[k,M]=y.useState(!1),[q,I]=y.useState(""),[O,L]=y.useState(!1),[X,ee]=y.useState(ide),[Q,le]=y.useState(!1),[de,me]=y.useState(""),[Z,ce]=y.useState(""),[he,ue]=y.useState(!0),[xe,H]=y.useState(null),[J,A]=y.useState(!1),E=y.useMemo(()=>({filament:a.filament,print:a.process,printer:a.printer})[d]||[],[a,d]),B=y.useMemo(()=>E.filter(Re=>NS(Re.setting_id)),[E]),{data:W}=Qe({queryKey:["cloudFields",d],queryFn:()=>re.getCloudFields(d==="print"?"process":d),staleTime:1e3*60*60}),{data:z}=Qe({queryKey:["allPresetDetails",d,B.map(Re=>Re.setting_id).join(",")],queryFn:async()=>{const Re={};for(let Ue=0;Ue{try{const Ne=await re.getCloudSettingDetail(st.setting_id);return{id:st.setting_id,detail:Ne}}catch{return null}}))).forEach(st=>{st&&(Re[st.id]=st.detail)})}return Re},enabled:B.length>0,staleTime:1e3*60*10}),{data:ie,isLoading:U}=Qe({queryKey:["cloudSettingDetail",f],queryFn:()=>re.getCloudSettingDetail(f),enabled:!!f});y.useEffect(()=>{l!=="json"&&C(JSON.stringify(x,null,2))},[x,l]);const G=y.useMemo(()=>({filament:a.filament,print:a.process,printer:a.printer}[d]||[]).filter(Ke=>!NS(Ke.setting_id)).sort((Ke,Ue)=>Ke.name.localeCompare(Ue.name)),[a,d]);y.useEffect(()=>{if(!f)return;const Re=G.find(Ke=>Ke.setting_id===f);Re&&(b(Re.name),o||(S({inherits:Re.name}),C(JSON.stringify({inherits:Re.name},null,2))))},[f,G,o]);const K=y.useMemo(()=>{const Re=W?.fields||[],Ke=new Set(Re.map(st=>st.key)),Ue=new Set,lt=new Set(["inherits","updated_time","compatible_printers","compatible_prints"]);z&&Object.values(z).forEach(st=>{st?.setting&&Object.keys(st.setting).forEach(Ne=>{!Ke.has(Ne)&&!lt.has(Ne)&&Ue.add(Ne)})}),Object.keys(x).forEach(st=>{!Ke.has(st)&&!lt.has(st)&&Ue.add(st)});const Ee=Array.from(Ue).sort().map(st=>({key:st,label:st.replace(/_/g," ").replace(/\b\w/g,Ne=>Ne.toUpperCase()),type:"text",category:"discovered",description:n("profiles.presets.discoveredFromPresets")}));return[...Re,...Ee]},[W,z,x,n]),Y=K.filter(Re=>Re.label.toLowerCase().includes(j.toLowerCase())||Re.key.toLowerCase().includes(j.toLowerCase())),se=()=>{if(q.trim()){const Re=q.trim().toLowerCase().replace(/\s+/g,"_");oe(Re,""),I(""),L(!1),i(n("profiles.presets.toast.fieldAdded",{key:Re}))}},oe=(Re,Ke)=>{S(Ue=>{const lt={...Ue};return Ke===""||Ke===void 0?delete lt[Re]:lt[Re]=Ke,lt})},fe=Re=>{S(Ke=>({...Ke,...Re.settings})),H(Re.name),i(n("profiles.templates.toast.applied"))},ae=()=>{if(!de.trim())return;const Re={...x};if(delete Re.inherits,Object.keys(Re).length===0){i(n("profiles.presets.noOverridesToSave"),"error");return}const Ke={id:Date.now().toString(),name:de.trim(),description:Z.trim()||n("profiles.presets.customTemplate"),type:d,settings:Re,showInModal:he},Ue=[...X,Ke];ee(Ue),sde(Ue),le(!1),me(""),ce(""),ue(!0),i(n("profiles.templates.toast.created"))},pe=y.useMemo(()=>X.filter(Re=>Re.type===d&&Re.showInModal),[d,X]),$=Re=>{C(Re);try{const Ke=JSON.parse(Re);S(Ke),T(null)}catch(Ke){T(Ke.message)}},R=Re=>{Re.preventDefault(),M(!1);const Ke=Re.dataTransfer.files[0];if(Ke&&Ke.name.endsWith(".json")){const Ue=new FileReader;Ue.onload=lt=>{try{const Ee=lt.target?.result,st=JSON.parse(Ee),Ne=st.setting||st;S(Ze=>({...Ze,...Ne})),C(JSON.stringify({...x,...Ne},null,2)),i(n("profiles.presets.fileImported"))}catch{i(n("profiles.presets.invalidJsonFile"),"error")}},Ue.readAsText(Ke)}},ne=ot({mutationFn:()=>{const Re={...x},Ke=d==="filament"?"filament_settings_id":d==="print"?"print_settings_id":"printer_settings_id";Re[Ke]=`"${m}"`;const Ue={type:d,name:m,base_id:f,setting:Re};return re.createCloudSetting(Ue)},onSuccess:async()=>{i(n("profiles.presets.toast.created")),await s.refetchQueries({queryKey:["cloudSettings"]}),t()},onError:Re=>i(Re.message,"error")}),be=ot({mutationFn:()=>{if(!e?.setting_id)throw new Error(n("profiles.presets.noSettingId"));return re.updateCloudSetting(e.setting_id,{name:m,setting:x})},onSuccess:async()=>{i(n("profiles.presets.toast.updated")),s.removeQueries({queryKey:["cloudSettingDetail"]}),await s.refetchQueries({queryKey:["cloudSettings"]}),t()},onError:Re=>i(Re.message,"error")}),ve=o?be:ne,ke=ie?.setting?.inherits,ye=ke?G.find(Re=>Re.name===ke):void 0,{data:ge}=Qe({queryKey:["cloudSettingDetail",ye?.setting_id],queryFn:()=>re.getCloudSettingDetail(ye.setting_id),enabled:!!ye?.setting_id}),Me=y.useMemo(()=>{const Re=ge?.setting||{},Ke=ie?.setting||{},Ue=f&&z?.[f]?.setting?z[f].setting:{};return{...Re,...Ke,...Ue}},[f,ie,ge,z]),Be=Re=>{if(Re==null)return"";if(Array.isArray(Re)){const Ke=[...new Set(Re.map(Ue=>String(Ue)))];return Ke.length===1?Ke[0]:Re.join(", ")}return String(Re)},Le=Re=>{const Ke=x[Re.key],Ue=Me[Re.key],lt=Be(Ue),Ee=U?n("common.loading"):lt||"",st="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(Re.type==="boolean"){const Ne=Ke==="1"||Ke===void 0&&Ue==="1";return r.jsx("button",{type:"button",onClick:()=>oe(Re.key,Ke==="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 Re.type==="select"?r.jsxs("select",{value:Ke||"",onChange:Ne=>oe(Re.key,Ne.target.value),className:st,children:[r.jsx("option",{value:"",children:Ee}),Re.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:Re.type==="number"?"number":"text",value:Ke!==void 0?String(Ke):"",onChange:Ne=>oe(Re.key,Ne.target.value),step:Re.step,min:Re.min,max:Re.max,placeholder:Ee,className:st}),Re.unit&&r.jsx("span",{className:"text-xs text-bambu-gray whitespace-nowrap",children:Re.unit})]})},Oe=y.useMemo(()=>ie?.setting?ie.setting:{},[ie]);return r.jsxs("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",onDragOver:Re=>{Re.preventDefault(),M(!0)},onDragLeave:()=>M(!1),onDrop:R,children:[J&&f&&r.jsx(ode,{onClose:()=>A(!1),leftPreset:Oe,rightPreset:x,leftLabel:n("profiles.presets.baseLabel",{name:w||f}),rightLabel:n("profiles.presets.currentLabel",{name:m||n("profiles.presets.newPreset")}),t:n}),r.jsx(Tt,{className:"w-full max-w-6xl max-h-[90vh] flex flex-col overflow-y-auto",children:r.jsxs(Mt,{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:n(o?"profiles.presets.editPreset":e?"profiles.presets.duplicatePreset":"profiles.presets.createNewPreset")}),r.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:n("profiles.presets.customizeSettings")})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[f&&r.jsxs("button",{onClick:()=>A(!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:n("profiles.presets.compareWithBase"),children:[r.jsx(ry,{className:"w-4 h-4"}),n("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($t,{className:"w-5 h-5"})})]})]}),k&&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(Sn,{className:"w-12 h-12 text-bambu-green mx-auto mb-2"}),r.jsx("p",{className:"text-bambu-green font-medium",children:n("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:n("common.type")}),r.jsxs("select",{value:d,onChange:Re=>{u(Re.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:n("profiles.presets.types.filament")}),r.jsx("option",{value:"print",children:n("profiles.presets.types.process")}),r.jsx("option",{value:"printer",children:n("profiles.presets.types.printer")})]})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("profiles.presets.basePreset")}),r.jsxs("select",{value:f,onChange:Re=>g(Re.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:n("profiles.presets.selectBasePreset")}),G.map(Re=>r.jsx("option",{value:Re.setting_id,children:Re.name},Re.setting_id))]})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("profiles.presets.presetName")}),r.jsx("input",{type:"text",value:m,onChange:Re=>p(Re.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",placeholder:n("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(kr,{className:"w-3 h-3 text-bambu-green"}),n("profiles.presets.inheritsFrom")," ",r.jsx("span",{className:"text-white",children:w}),U&&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(w8,{className:"w-4 h-4"}),n("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(FS,{className:"w-4 h-4"}),n("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(Zy,{className:"w-4 h-4"}),"JSON",P&&r.jsx(qn,{className:"w-3 h-3 text-red-400"})]}),r.jsx("div",{className:"flex-1 max-[640px]:hidden"}),r.jsxs("button",{onClick:()=>{const Re={name:m,type:d,base_id:f,setting:x},Ke=new Blob([JSON.stringify(Re,null,2)],{type:"application/json"}),Ue=URL.createObjectURL(Ke),lt=document.createElement("a");lt.href=Ue,lt.download=`${m||"preset"}.json`,document.body.appendChild(lt),lt.click(),document.body.removeChild(lt),URL.revokeObjectURL(Ue),i(n("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:n("profiles.presets.exportToJson"),children:[r.jsx(Ur,{className:"w-4 h-4"}),n("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:n("profiles.presets.importFromJson"),children:[r.jsx(Sn,{className:"w-4 h-4"}),n("common.upload")]}),r.jsx("input",{id:"file-import",type:"file",accept:".json",className:"hidden",onChange:Re=>{const Ke=Re.target.files?.[0];if(Ke){const Ue=new FileReader;Ue.onload=lt=>{try{const Ee=JSON.parse(lt.target?.result),st=Ee.setting||Ee;S(Ne=>({...Ne,...st})),i(n("profiles.presets.fileImported"))}catch{i(n("profiles.presets.invalidJson"),"error")}},Ue.readAsText(Ke)}}})]}),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(Ig,{className:"w-4 h-4 text-amber-400"}),n("profiles.templates.title")]}),Object.keys(x).filter(Re=>Re!=="inherits").length>0&&r.jsxs("button",{onClick:()=>le(!Q),className:"text-xs text-bambu-gray hover:text-white flex items-center gap-1 transition-colors",children:[r.jsx(fs,{className:"w-3 h-3"}),n("profiles.presets.saveAsTemplate")]})]}),Q&&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:de,onChange:Re=>me(Re.target.value),placeholder:n("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:Z,onChange:Re=>ce(Re.target.value),placeholder:n("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(je,{size:"sm",onClick:ae,disabled:!de.trim(),children:[r.jsx(fs,{className:"w-3 h-3"}),n("common.save")]}),r.jsx(je,{size:"sm",variant:"secondary",onClick:()=>le(!1),children:n("common.cancel")})]}),r.jsxs("button",{onClick:()=>ue(!he),className:`flex items-center gap-1.5 text-xs transition-colors ${he?"text-bambu-green":"text-bambu-gray hover:text-white"}`,children:[he?r.jsx(Ml,{className:"w-3.5 h-3.5"}):r.jsx(db,{className:"w-3.5 h-3.5"}),n(he?"profiles.templates.shownInModals":"profiles.templates.hiddenInModals")]})]})]}),xe&&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(kr,{className:"w-4 h-4 text-bambu-green"}),r.jsxs("span",{className:"text-sm text-bambu-green",children:[n("profiles.presets.templateApplied")," ",r.jsx("span",{className:"font-medium",children:xe})]}),r.jsx("button",{onClick:()=>H(null),className:"ml-auto text-bambu-green/70 hover:text-bambu-green",children:r.jsx($t,{className:"w-4 h-4"})})]}),r.jsxs("div",{className:"grid grid-cols-3 gap-2",children:[pe.map(Re=>r.jsxs("button",{onClick:()=>fe(Re),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:Re.name}),r.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:Re.description})]},Re.id)),pe.length===0&&r.jsx("p",{className:"col-span-3 text-center text-bambu-gray text-sm py-4",children:n("profiles.presets.noTemplatesSelected")})]}),r.jsx("p",{className:"text-xs text-bambu-gray-dark mt-2 text-center",children:n("profiles.presets.manageTemplatesHint")})]}),r.jsxs("div",{children:[r.jsx("h3",{className:"text-sm font-medium text-white mb-3",children:n("profiles.presets.commonSettings")}),r.jsx("div",{className:"grid grid-cols-2 gap-x-6 gap-y-3",children:K.slice(0,10).map(Re=>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:Re.label}),r.jsx("div",{className:"w-48 max-[640px]:w-full",children:Le(Re)})]},Re.key))})]}),Object.keys(x).length>1&&r.jsxs("div",{children:[r.jsx("h3",{className:"text-sm font-medium text-white mb-3",children:n("profiles.presets.currentOverrides")}),r.jsx("div",{className:"flex flex-wrap gap-2",children:Object.entries(x).filter(([Re])=>Re!=="inherits").map(([Re,Ke])=>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:[Re,": ",String(Ke).slice(0,20),r.jsx("button",{onClick:()=>oe(Re,void 0),className:"hover:text-white",children:r.jsx($t,{className:"w-3 h-3"})})]},Re))})]})]}),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:n("profiles.presets.availableFields")}),r.jsx("span",{className:"text-xs text-bambu-gray",children:z?n("profiles.templates.fieldsCount",{count:K.length}):n("common.loading")})]}),r.jsxs("div",{className:"relative mb-3 flex-shrink-0",children:[r.jsx(fr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),r.jsx("input",{type:"text",value:j,onChange:Re=>F(Re.target.value),placeholder:n("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:[Y.filter(Re=>!(Re.key in x)).map(Re=>{const Ke=Me[Re.key],Ue=Be(Ke);return r.jsxs("div",{onClick:()=>{S(lt=>({...lt,[Re.key]:Ue||""}))},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:Re.label}),r.jsx("p",{className:"text-xs text-bambu-gray-dark truncate",children:Re.key})]}),r.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[Ue&&r.jsxs("span",{className:"text-xs text-bambu-gray bg-bambu-dark px-2 py-0.5 rounded max-w-32 truncate",title:Ue,children:[Ue.slice(0,20),Ue.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(er,{className:"w-4 h-4 text-bambu-gray group-hover:text-bambu-green transition-colors"})})]})]},Re.key)}),Y.filter(Re=>!(Re.key in x)).length===0&&r.jsx("p",{className:"text-center text-bambu-gray py-4 text-sm",children:n(j?"profiles.presets.noMatchingFields":"profiles.presets.allFieldsAdded")})]}),r.jsx("div",{className:"pt-3 mt-3 border-t border-bambu-dark-tertiary flex-shrink-0",children:O?r.jsxs("div",{className:"flex gap-2",children:[r.jsx("input",{type:"text",value:q,onChange:Re=>I(Re.target.value),onKeyDown:Re=>Re.key==="Enter"&&se(),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(je,{size:"sm",onClick:se,disabled:!q.trim(),children:r.jsx(er,{className:"w-4 h-4"})}),r.jsx(je,{size:"sm",variant:"secondary",onClick:()=>{L(!1),I("")},children:r.jsx($t,{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(er,{className:"w-4 h-4"}),n("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:n("profiles.presets.yourOverrides")}),r.jsx("span",{className:"text-xs text-bambu-gray",children:n("profiles.templates.fieldsCount",{count:Object.keys(x).filter(Re=>Re!=="inherits").length})})]}),r.jsxs("div",{className:"flex-1 overflow-y-auto space-y-2 pr-2 min-h-0",children:[Object.entries(x).filter(([Re])=>Re!=="inherits").map(([Re,Ke])=>{const Ue=K.find(lt=>lt.key===Re);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:Ue?.label||Re}),r.jsx("p",{className:"text-xs text-bambu-gray-dark",children:Re})]}),r.jsx("button",{onClick:()=>oe(Re,void 0),className:"p-1 text-bambu-gray hover:text-red-400 transition-colors",children:r.jsx($t,{className:"w-4 h-4"})})]}),Ue?Le(Ue):r.jsx("input",{type:"text",value:String(Ke),onChange:lt=>oe(Re,lt.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"})]},Re)}),Object.keys(x).filter(Re=>Re!=="inherits").length===0&&r.jsxs("div",{className:"text-center py-8 text-bambu-gray",children:[r.jsx(w8,{className:"w-8 h-8 mx-auto mb-2 opacity-50"}),r.jsx("p",{className:"text-sm",children:n("profiles.presets.noOverridesYet")}),r.jsx("p",{className:"text-xs mt-1",children:n("profiles.presets.clickFieldsToAdd")})]})]}),Object.keys(x).filter(Re=>Re!=="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:()=>{le(!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(fs,{className:"w-4 h-4"}),n("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(qn,{className:"w-4 h-4"}),P]}),r.jsx("textarea",{value:N,onChange:Re=>$(Re.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:n("profiles.presets.jsonTip")})]})]}),r.jsxs("div",{className:"p-4 border-t border-bambu-dark-tertiary flex gap-2",children:[r.jsx(je,{variant:"secondary",onClick:t,className:"flex-1",children:n("common.cancel")}),r.jsxs(je,{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(fs,{className:"w-4 h-4"}):r.jsx(er,{className:"w-4 h-4"}),n(o?"common.save":e?"common.duplicate":"common.create")]})]})]})})]})}function Dit({settings:t,lastSyncTime:e,onRefresh:a,isRefreshing:n,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),[j,F]=y.useState(!1),[k,M]=y.useState(!1),[q,I]=y.useState(null),[O,L]=y.useState(null),[X,ee]=y.useState(null),[Q,le]=y.useState(!1),[de,me]=y.useState([null,null]),[Z,ce]=y.useState(!1),[he,ue]=y.useState(null),xe=ta(),H=y.useMemo(()=>[...t.filament.map(se=>({...se,type:"filament"})),...t.printer.map(se=>({...se,type:"printer"})),...t.process.map(se=>({...se,type:"process"}))].map(se=>({...se,meta:xU(se.name)})),[t]),J=y.useMemo(()=>{const Y=new Set,se=new Set,oe=new Set;return H.forEach(fe=>{fe.meta.nozzle&&Y.add(fe.meta.nozzle),fe.meta.filamentType&&se.add(fe.meta.filamentType),fe.meta.layerHeight&&oe.add(fe.meta.layerHeight)}),{printers:i.map(fe=>({id:fe.id.toString(),name:fe.name})),nozzles:Array.from(Y).sort((fe,ae)=>parseFloat(fe)-parseFloat(ae)),filaments:Array.from(se).sort(),layerHeights:Array.from(oe).sort((fe,ae)=>parseFloat(fe)-parseFloat(ae))}},[H,i]),A=y.useMemo(()=>f==="all"?null:i.find(se=>se.id.toString()===f)?.model||null,[f,i]),E=y.useMemo(()=>H.filter(Y=>d==="all"||Y.type===d).filter(Y=>{if(m==="all")return!0;const se=NS(Y.setting_id);return m==="custom"?se:!se}).filter(Y=>{if(f==="all"||!A)return!0;const se=Y.meta.printer?.toLowerCase()||"",oe=A.toLowerCase();return se.includes(oe)||oe.includes(se)}).filter(Y=>w==="all"||Y.meta.nozzle===w).filter(Y=>x==="all"||Y.meta.filamentType===x).filter(Y=>N==="all"||Y.meta.layerHeight===N).filter(Y=>l===""||Y.name.toLowerCase().includes(l.toLowerCase())).sort((Y,se)=>Y.name.localeCompare(se.name)),[H,d,m,f,A,w,x,N,l]),B=Y=>{if(Q){const se=de[0]?.setting_id===Y.setting_id,oe=de[1]?.setting_id===Y.setting_id;if(se)me([de[1],null]);else if(oe)me([de[0],null]);else if(!de[0])me([Y,null]);else if(de[1]){if(de[0].type!==Y.type)return;me([de[0],Y])}else{if(de[0].type!==Y.type)return;me([de[0],Y])}}else T(Y)},W=Y=>{if(de[0]?.setting_id===Y.setting_id)return 0;if(de[1]?.setting_id===Y.setting_id)return 1},z=async Y=>{try{const se=await re.getCloudSettingDetail(Y.setting_id),oe=Y.type==="process"?"print":Y.type;I({type:oe,name:Y.name,base_id:se.base_id||"GFSA00",setting:se.setting||{}}),T(null)}catch(se){console.error("Failed to fetch preset details for duplication:",se)}},ie=async Y=>{try{xe.removeQueries({queryKey:["cloudSettingDetail",Y.setting_id]});const se=await re.getCloudSettingDetail(Y.setting_id),oe=Y.type==="process"?"print":Y.type;L({type:oe,name:Y.name,base_id:se.base_id||"GFSA00",setting:se.setting||{},setting_id:Y.setting_id}),T(null)}catch(se){console.error("Failed to fetch preset details for editing:",se)}},U=()=>{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(fr,{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:Y=>c(Y.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(je,{variant:Q?"primary":"secondary",onClick:()=>{Q?(le(!1),me([null,null])):le(!0)},children:[r.jsx(ry,{className:"w-4 h-4"}),o(Q?"common.cancel":"profiles.presets.compare")]}),r.jsxs(je,{variant:"secondary",onClick:()=>M(!0),disabled:!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.cloudView.noTemplatesPermission"),children:[r.jsx(Ig,{className:"w-4 h-4"}),o("profiles.cloudView.templates")]}),r.jsxs(je,{variant:"secondary",onClick:a,disabled:n||!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.cloudView.noRefreshPermission"),children:[r.jsx(Xa,{className:`w-4 h-4 ${n?"animate-spin":""}`}),o("profiles.cloudView.refresh")]}),r.jsxs(je,{onClick:()=>F(!0),disabled:!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.cloudView.noCreatePermission"),children:[r.jsx(er,{className:"w-4 h-4"}),o("profiles.cloudView.newPreset")]})]})]}),r.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[r.jsx(jS,{className:"w-4 h-4 text-bambu-gray"}),r.jsx(zx,{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:Y=>u(Y)}),r.jsx(zx,{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:Y=>p(Y)}),J.printers.length>0&&r.jsx(zx,{label:o("profiles.cloudView.filters.printer"),value:f,options:[{value:"all",label:o("profiles.cloudView.filters.all")},...J.printers.map(Y=>({value:Y.id,label:Y.name}))],onChange:g}),J.nozzles.length>0&&r.jsx(zx,{label:o("profiles.cloudView.filters.nozzle"),value:w,options:[{value:"all",label:o("profiles.cloudView.filters.all")},...J.nozzles.map(Y=>({value:Y,label:Y}))],onChange:b}),J.filaments.length>0&&(d==="all"||d==="filament")&&r.jsx(zx,{label:o("profiles.cloudView.filters.filament"),value:x,options:[{value:"all",label:o("profiles.cloudView.filters.all")},...J.filaments.map(Y=>({value:Y,label:Y}))],onChange:S}),J.layerHeights.length>0&&(d==="all"||d==="process")&&r.jsx(zx,{label:o("profiles.cloudView.filters.layer"),value:N,options:[{value:"all",label:o("profiles.cloudView.filters.all")},...J.layerHeights.map(Y=>({value:Y,label:Y}))],onChange:C}),G&&r.jsx("button",{onClick:U,className:"px-3 py-2 text-sm text-bambu-gray hover:text-white transition-colors",children:o("profiles.cloudView.clearFilters")})]})]}),Q&&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(ry,{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:de[0]?o("profiles.cloudView.selectAnotherPreset",{type:de[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] ${de[0]?"bg-blue-500/30 text-blue-700 dark:text-blue-300":"bg-bambu-dark text-bambu-gray"}`,children:de[0]?de[0].name:o("profiles.cloudView.selectFirst")}),r.jsx(rC,{className:"w-4 h-4 text-bambu-gray"}),r.jsx("span",{className:`px-2 py-1 text-sm rounded truncate max-w-[200px] ${de[1]?"bg-blue-500/30 text-blue-700 dark:text-blue-300":"bg-bambu-dark text-bambu-gray"}`,children:de[1]?de[1].name:o("profiles.cloudView.selectSecond")})]}),de[0]&&de[1]&&r.jsxs(je,{size:"sm",onClick:async()=>{try{const[Y,se]=await Promise.all([re.getCloudSettingDetail(de[0].setting_id),re.getCloudSettingDetail(de[1].setting_id)]);ue([Y.setting||{},se.setting||{}]),ce(!0)}catch{}},children:[r.jsx(ry,{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(Za,{className:"w-3 h-3"}),o("profiles.cloudView.lastSynced")," ",Fh(e.toISOString(),"system",o)]}),r.jsx("span",{children:o("profiles.cloudView.showingCount",{showing:E.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")]})]})]}),E.length===0?r.jsxs("div",{className:"text-center py-16",children:[r.jsx(cn,{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:U,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(AT,{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:["(",E.filter(Y=>Y.type==="filament").length,")"]})]}),r.jsxs("div",{className:"space-y-1 max-h-[calc(100vh-320px)] overflow-y-auto pr-1",children:[E.filter(Y=>Y.type==="filament").map(Y=>r.jsx(k3,{setting:Y,onClick:()=>B(Y),onDuplicate:()=>z(Y),compareMode:Q,isCompareSelected:W(Y)!==void 0,compareIndex:W(Y),compareDisabled:Q&&!!de[0]&&de[0].type!==Y.type,t:o},Y.setting_id)),E.filter(Y=>Y.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(mu,{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:["(",E.filter(Y=>Y.type==="process").length,")"]})]}),r.jsxs("div",{className:"space-y-1 max-h-[calc(100vh-320px)] overflow-y-auto pr-1",children:[E.filter(Y=>Y.type==="process").map(Y=>r.jsx(k3,{setting:Y,onClick:()=>B(Y),onDuplicate:()=>z(Y),compareMode:Q,isCompareSelected:W(Y)!==void 0,compareIndex:W(Y),compareDisabled:Q&&!!de[0]&&de[0].type!==Y.type,t:o},Y.setting_id)),E.filter(Y=>Y.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(gr,{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:["(",E.filter(Y=>Y.type==="printer").length,")"]})]}),r.jsxs("div",{className:"space-y-1 max-h-[calc(100vh-320px)] overflow-y-auto pr-1",children:[E.filter(Y=>Y.type==="printer").map(Y=>r.jsx(k3,{setting:Y,onClick:()=>B(Y),onDuplicate:()=>z(Y),compareMode:Q,isCompareSelected:W(Y)!==void 0,compareIndex:W(Y),compareDisabled:Q&&!!de[0]&&de[0].type!==Y.type,t:o},Y.setting_id)),E.filter(Y=>Y.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(jit,{setting:P,onClose:()=>T(null),onDeleted:()=>T(null),onDuplicate:()=>z(P),onEdit:()=>ie(P),hasPermission:s,t:o}),(j||q||O||X)&&r.jsx(Eit,{onClose:()=>{F(!1),I(null),L(null),ee(null)},initialData:O||q||(X?{type:X.type,name:"",base_id:"",setting:X.setting}:void 0),allPresets:t,t:o}),k&&r.jsx(Mit,{onClose:()=>M(!1),onApply:Y=>{ee({type:Y.type,setting:Y.settings}),M(!1)},t:o}),Z&&he&&de[0]&&de[1]&&r.jsx(ode,{onClose:()=>{ce(!1),ue(null)},leftPreset:he[0],rightPreset:he[1],leftLabel:de[0].name,rightLabel:de[1].name,t:o})]})}function Fit(){const{t}=vt(),e=ta(),{showToast:a}=na(),{hasPermission:n}=dr(),[i,s]=y.useState("cloud"),[o,l]=y.useState(),{data:c,isLoading:d}=Qe({queryKey:["cloudStatus"],queryFn:re.getCloudStatus}),{data:u=[]}=Qe({queryKey:["printers"],queryFn:re.getPrinters}),{data:m,isLoading:p,refetch:f,dataUpdatedAt:g}=Qe({queryKey:["cloudSettings"],queryFn:()=>re.getCloudSettings(),enabled:!!c?.is_authenticated,retry:!1,staleTime:1e3*60*5});y.useEffect(()=>{g&&l(new Date(g))},[g]);const w=ot({mutationFn:re.cloudLogout,onSuccess:()=>{e.invalidateQueries({queryKey:["cloudStatus"]}),e.removeQueries({queryKey:["cloudSettings"]}),a(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(Gh,{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(Gh,{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(ub,{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(MS,{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(je,{variant:"secondary",size:"sm",onClick:()=>w.mutate(),disabled:w.isPending||!n("cloud:auth"),title:n("cloud:auth")?void 0:t("profiles.noLogoutPermission"),children:[r.jsx(ny,{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(Dit,{settings:m,lastSyncTime:o,onRefresh:()=>f(),isRefreshing:p,printers:u,hasPermission:n,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(je,{onClick:()=>f(),children:t("profiles.retry")})]}):r.jsx(Tit,{onSuccess:b,t})]}),i==="local"&&r.jsx(Pit,{}),i==="kprofiles"&&r.jsx(kit,{}),r.jsx(Ait,{})]})}function Lit(t,e){const a=(e||"").toUpperCase().replace(/[- ]/g,""),n=a.includes("X1"),i=a.includes("P1"),s=a.includes("A1MINI"),o=a.includes("A1")&&!s,l=a.includes("H2D"),c=a.includes("H2C"),d=a.includes("H2S"),u=l||c||d,m=a.includes("P2S"),p=a.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 n||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 n?"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 n||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 n||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 J0={Droplet:AT,Flame:xm,Ruler:Tye,Sparkles:Ig,Square:lo,Cable:NO,Wrench:Zm,Calendar:vn,Timer:Xd,Cog:du,Fan:GZ,Zap:Nc,Wind:sJ,Thermometer:zS,Layers:cn,Box:Mi,Target:aJ,RefreshCw:Xa,Settings:vy,Filter:jS,CircleDot:Mge};function Cw(t){return t&&J0[t]||Zm}function Ux(t,e,a){if(e==="days"){if(t<1)return a?a("common.today"):"Today";if(t===1)return a?a("maintenance.day"):"1 day";if(t<7){const i=Math.round(t);return a?a("maintenance.days",{count:i}):`${i} days`}if(t<180){const i=Math.round(t/7);return i===1?a?a("maintenance.week"):"1 week":a?a("maintenance.weeks",{count:i}):`${i} weeks`}const n=Math.round(t/30);return n===1?a?a("maintenance.month"):"1 month":a?a("maintenance.months",{count:n}):`${n} 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 n=t/24;if(n<7)return`${n<2?n.toFixed(1):Math.round(n)}d`;const i=n/7;return i<12?`${i<2?i.toFixed(1):Math.round(i)}w`:`${Math.round(i/4)}mo`}}function _3(t,e,a){return e==="days"?t===1?a?a("maintenance.day"):"1 day":t===7?a?a("maintenance.week"):"1 week":t===14?a?a("maintenance.weeks",{count:2}):"2 weeks":t===30?a?a("maintenance.month"):"1 month":t===60?a?a("maintenance.months",{count:2}):"2 months":t===90?a?a("maintenance.months",{count:3}):"3 months":t===180?a?a("maintenance.months",{count:6}):"6 months":t===365?a?a("maintenance.year"):"1 year":a?a("maintenance.days",{count:t}):`${t} days`:`${t}h`}function Rit({item:t,onPerform:e,onToggle:a,hasPermission:n,t:i}){const s=Cw(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:Ux(Math.abs(f),"days",i)}):t.is_warning?i("maintenance.dueIn",{duration:Ux(f,"days",i)}):i("maintenance.timeLeft",{duration:Ux(f,"days",i)})}else return t.is_due?i("maintenance.overdueBy",{duration:Ux(Math.abs(t.hours_until_due),"hours",i)}):t.is_warning?i("maintenance.dueIn",{duration:Ux(t.hours_until_due,"hours",i)}):i("maintenance.timeLeft",{duration:Ux(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(vn,{className:"w-3.5 h-3.5 text-bambu-gray shrink-0"})}),(()=>{const f=t.maintenance_type_wiki_url||Lit(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(Mr,{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(ba,{className:"w-3 h-3"}),t.is_warning&&!t.is_due&&r.jsx(Za,{className:"w-3 h-3"}),!t.is_due&&!t.is_warning&&t.enabled&&r.jsx(kr,{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:n("maintenance:update")?void 0:i("maintenance.noPermissionUpdate"),children:r.jsx(ja,{checked:t.enabled,onChange:f=>a(t.id,f),disabled:!n("maintenance:update")})}),r.jsxs(je,{size:"sm",variant:t.is_due?"primary":"secondary",onClick:()=>e(t.id),disabled:!t.enabled||!n("maintenance:update"),title:n("maintenance:update")?void 0:i("maintenance.noPermissionPerform"),className:"!px-3",children:[r.jsx(vs,{className:"w-3.5 h-3.5"}),i("common.reset")]})]})]})})}function Iit({overview:t,onPerform:e,onToggle:a,onSetHours:n,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&&(n(t.printer_id,w),d(!1))};return r.jsxs(Tt,{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(ba,{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(Za,{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(kr,{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(al,{className:"w-4 h-4"}):r.jsx(Da,{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(je,{size:"sm",onClick:g,children:s("common.save")}),r.jsx(je,{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(Rg,{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=Cw(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(Mt,{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(Rit,{item:w,onPerform:e,onToggle:a,hasPermission:i,t:s},w.id))})})]})}function Oit({overview:t,types:e,onUpdateInterval:a,onAddType:n,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,j]=y.useState("100"),[F,k]=y.useState("hours"),[M,q]=y.useState("Wrench"),[I,O]=y.useState(""),[L,X]=y.useState(new Set),[ee,Q]=y.useState(null),[le,de]=y.useState(null),me=y.useMemo(()=>t?t.map($=>({id:$.printer_id,name:$.printer_name})):[],[t]),Z=$=>t?t.filter(R=>R.maintenance_items.some(ne=>ne.maintenance_type_id===$)).map(R=>({printerId:R.printer_id,printerName:R.printer_name,itemId:R.maintenance_items.find(ne=>ne.maintenance_type_id===$)?.id})):[],ce=$=>{if(!t)return[];const R=new Set(Z($).map(ne=>ne.printerId));return me.filter(ne=>!R.has(ne.id))},[he,ue]=y.useState(null),[xe,H]=y.useState(""),[J,A]=y.useState(""),[E,B]=y.useState("hours"),[W,z]=y.useState("Wrench"),[ie,U]=y.useState(""),G=$=>{ue($),H($.name),A($.default_interval_hours.toString()),B($.interval_type||"hours"),z($.icon||"Wrench"),U($.wiki_url||"")},K=()=>{he&&xe.trim()&&parseFloat(J)>0&&(i(he.id,{name:xe.trim(),default_interval_hours:parseFloat(J),interval_type:E,icon:W,wiki_url:ie.trim()||null}),ue(null))},Y=($,R,ne)=>{const be=parseFloat(g);if(!isNaN(be)&&be>0){const ve=Math.abs(be-R)<.01?null:be;a($,{custom_interval_hours:ve,custom_interval_type:b!==ne?b:null})}f(null)},se=$=>{$.preventDefault(),C.trim()&&parseFloat(T)>0&&L.size>0&&(n({name:C.trim(),default_interval_hours:parseFloat(T),interval_type:F,icon:M,wiki_url:I.trim()||null},Array.from(L)),P(""),j("100"),k("hours"),O(""),X(new Set),N(!1))},oe=$=>{X(R=>{const ne=new Set(R);return ne.has($)?ne.delete($):ne.add($),ne})},fe=t?.map($=>({printerId:$.printer_id,printerName:$.printer_name,items:$.maintenance_items.sort((R,ne)=>R.maintenance_type_id-ne.maintenance_type_id)})).sort(($,R)=>$.printerName.localeCompare(R.printerName))||[],ae=e.filter($=>$.is_system),pe=e.filter($=>!$.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(je,{variant:"secondary",onClick:o,disabled:!u("maintenance:delete")||l,title:u("maintenance:delete")?void 0:m("maintenance.noPermissionDeleteTypes"),children:m("maintenance.restoreDefaults")}),r.jsxs(je,{onClick:()=>N(!S),disabled:!u("maintenance:create"),title:u("maintenance:create")?void 0:m("maintenance.noPermissionEditTypes"),children:[r.jsx(er,{className:"w-4 h-4"}),m("maintenance.addCustomType")]})]})]}),S&&r.jsx(Tt,{className:"mb-6",children:r.jsx(Mt,{className:"py-4",children:r.jsxs("form",{onSubmit:se,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:$=>P($.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:$=>{k($.target.value),$.target.value==="days"?j("30"):j("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:$=>j($.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(J0).map($=>{const R=J0[$];return r.jsx("button",{type:"button",onClick:()=>q($),className:`p-2 rounded-lg transition-colors ${M===$?"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"})},$)})})]})}),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:$=>O($.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:me.map($=>r.jsx("button",{type:"button",onClick:()=>oe($.id),className:`px-3 py-1.5 rounded-lg text-sm transition-colors ${L.has($.id)?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary"}`,children:$.name},$.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(je,{type:"button",variant:"secondary",onClick:()=>{N(!1),X(new Set)},children:m("common.cancel")}),r.jsx(je,{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:[ae.map($=>{const R=Cw($.icon),ne=$.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:$.name}),r.jsxs("div",{className:"text-xs text-bambu-gray mt-0.5 flex items-center gap-1",children:[ne==="days"?r.jsx(vn,{className:"w-3 h-3"}):r.jsx(Xd,{className:"w-3 h-3"}),_3($.default_interval_hours,ne,m)]})]}),r.jsx("button",{onClick:()=>{u("maintenance:delete")&&de($)},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(ea,{className:"w-4 h-4"})})]})},$.id)}),pe.map($=>{const R=Cw($.icon),ne=$.interval_type||"hours";if(he?.id===$.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:xe,onChange:ge=>H(ge.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:E,onChange:ge=>B(ge.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:J,onChange:ge=>A(ge.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(J0).map(ge=>{const Me=J0[ge];return r.jsx("button",{type:"button",onClick:()=>z(ge),className:`p-1.5 rounded transition-colors ${W===ge?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:r.jsx(Me,{className:"w-3.5 h-3.5"})},ge)})}),r.jsx("input",{type:"url",value:ie,onChange:ge=>U(ge.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(je,{size:"sm",onClick:K,disabled:!xe.trim(),children:m("common.save")}),r.jsx(je,{size:"sm",variant:"secondary",onClick:()=>ue(null),children:m("common.cancel")})]})]})},$.id);const ve=Z($.id),ke=ce($.id),ye=ee===$.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:$.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(vn,{className:"w-3 h-3"}):r.jsx(Xd,{className:"w-3 h-3"}),_3($.default_interval_hours,ne,m)]})]}),r.jsxs("button",{onClick:()=>Q(ye?null:$.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(gr,{className:"w-3 h-3"}),r.jsx("span",{className:"text-xs font-medium",children:ve.length}),r.jsx(Da,{className:`w-3 h-3 transition-transform ${ye?"rotate-180":""}`})]}),r.jsx("button",{onClick:()=>G($),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(Rg,{className:"w-4 h-4"})}),r.jsx("button",{onClick:()=>{confirm(m("maintenance.deleteTypeConfirm",{name:$.name}))&&s($.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(ea,{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(ge=>r.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-1 bg-bambu-dark rounded text-xs text-white",children:[ge.printerName,r.jsx("button",{onClick:()=>ge.itemId&&d(ge.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:"×"})]},ge.printerId))}),ke.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")}),ke.map(ge=>r.jsxs("button",{onClick:()=>c(ge.id,$.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:["+ ",ge.name]},ge.id))]})]})]},$.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($=>r.jsx(Tt,{children:r.jsxs(Mt,{className:"py-4",children:[r.jsx("h3",{className:"text-sm font-medium text-white mb-3",children:$.printerName}),r.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-2",children:$.items.map(R=>{const ne=Cw(R.maintenance_type_icon),be=e.find(Me=>Me.id===R.maintenance_type_id),ve=be?.default_interval_hours||R.interval_hours,ke=be?.interval_type||"hours",ye=R.interval_type||"hours",ge=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}),ge?r.jsxs("div",{className:"flex items-center gap-1",children:[b==="days"?r.jsx(vn,{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:Me=>x(Me.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:Me=>w(Me.target.value),onKeyDown:Me=>{Me.key==="Enter"&&Y(R.id,ve,ke),Me.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(je,{size:"sm",onClick:()=>Y(R.id,ve,ke),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(vn,{className:"w-3 h-3"}):r.jsx(Xd,{className:"w-3 h-3"}),_3(R.interval_hours,ye,m),r.jsx(Rg,{className:"w-3 h-3 text-bambu-gray"})]})]},R.id)})})]})},$.printerId))})]}),fe.length===0&&r.jsx(Tt,{children:r.jsxs(Mt,{className:"text-center py-12",children:[r.jsx(Za,{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")})]})}),le&&r.jsx(wa,{title:m("maintenance.deleteSystemTypeTitle"),message:m("maintenance.deleteSystemTypeMessage",{name:le.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(le.id),de(null)},onCancel:()=>de(null)})]})}function zit(){const{t}=vt(),e=ta(),{showToast:a}=na(),{hasPermission:n}=dr(),[i,s]=y.useState("status"),{data:o,isLoading:l}=Qe({queryKey:["maintenanceOverview"],queryFn:re.getMaintenanceOverview}),{data:c}=Qe({queryKey:["maintenanceTypes"],queryFn:re.getMaintenanceTypes}),d=ot({mutationFn:({id:T,notes:j})=>re.performMaintenance(T,j),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]}),e.invalidateQueries({queryKey:["maintenanceSummary"]}),a(t("maintenance.maintenanceComplete"))},onError:T=>{a(T.message,"error")}}),u=ot({mutationFn:({id:T,data:j})=>re.updateMaintenanceItem(T,j),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]})},onError:T=>{a(T.message,"error")}}),m=ot({mutationFn:({id:T,data:j})=>re.updateMaintenanceType(T,j),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceTypes"]}),e.invalidateQueries({queryKey:["maintenanceOverview"]}),a(t("maintenance.typeUpdated"))},onError:T=>{a(T.message,"error")}}),p=ot({mutationFn:re.deleteMaintenanceType,onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceTypes"]}),e.invalidateQueries({queryKey:["maintenanceOverview"]}),a(t("maintenance.typeDeleted"))},onError:T=>{a(T.message,"error")}}),f=ot({mutationFn:re.restoreDefaultMaintenanceTypes,onSuccess:T=>{e.invalidateQueries({queryKey:["maintenanceTypes"]}),e.invalidateQueries({queryKey:["maintenanceOverview"]}),a(t("maintenance.defaultsRestored",{count:T.restored}))},onError:T=>{a(T.message,"error")}}),g=ot({mutationFn:({printerId:T,hours:j})=>re.setPrinterHours(T,j),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]}),e.invalidateQueries({queryKey:["maintenanceSummary"]}),a(t("maintenance.printHoursUpdated"))},onError:T=>{a(T.message,"error")}}),w=ot({mutationFn:({printerId:T,typeId:j})=>re.assignMaintenanceType(T,j),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]}),a(t("maintenance.printerAssigned"))},onError:T=>{a(T.message,"error")}}),b=ot({mutationFn:re.removeMaintenanceItem,onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]}),a(t("maintenance.printerRemoved"))},onError:T=>{a(T.message,"error")}}),x=T=>{d.mutate({id:T})},S=(T,j)=>{u.mutate({id:T,data:{enabled:j}})},N=(T,j)=>{g.mutate({printerId:T,hours:j})};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,j)=>T+j.due_count,0)||0,P=o?.reduce((T,j)=>T+j.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(Zm,{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,j)=>{const F=T.due_count*10+T.warning_count,k=j.due_count*10+j.warning_count;return F!==k?k-F:T.printer_name.localeCompare(j.printer_name)}).map(T=>r.jsx(Iit,{overview:T,onPerform:x,onToggle:S,onSetHours:N,hasPermission:n,t},T.printer_id)):r.jsx(Tt,{children:r.jsxs(Mt,{className:"text-center py-16",children:[r.jsx(Zm,{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(Oit,{overview:o,types:c||[],onUpdateInterval:(T,j)=>u.mutate({id:T,data:j}),onAddType:async(T,j)=>{const F=await re.createMaintenanceType(T);for(const k of j)await re.assignMaintenanceType(k,F.id);e.invalidateQueries({queryKey:["maintenanceTypes"]}),e.invalidateQueries({queryKey:["maintenanceOverview"]}),a(t("maintenance.typeUpdated"))},onUpdateType:(T,j)=>m.mutate({id:T,data:j}),onDeleteType:T=>p.mutate(T),onRestoreDefaults:()=>f.mutate(),isRestoringDefaults:f.isPending,onAssignType:(T,j)=>w.mutate({printerId:T,typeId:j}),onRemoveItem:T=>b.mutate(T),hasPermission:n,t})]})}const AX=["#ef4444","#f97316","#eab308","#22c55e","#06b6d4","#3b82f6","#8b5cf6","#ec4899","#6b7280"];function lde({project:t,onClose:e,onSave:a,isLoading:n,currencySymbol:i,t:s}){const[o,l]=y.useState(t?.name||""),[c,d]=y.useState(t?.description||""),[u,m]=y.useState(t?.color||AX[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,j]=y.useState(t?.priority||"normal"),[F,k]=y.useState(t?.budget?.toString()||""),[M,q]=y.useState(t?.url||""),[I,O]=y.useState(null),L=ta(),[X,ee]=y.useState(t?.cover_image_filename||null),Q=y.useRef(null),[le,de]=y.useState(!1),[me,Z]=y.useState(0),ce=async xe=>{const H=xe.target.files?.[0];if(!(!H||!t)){de(!0);try{const J=await re.uploadProjectCoverImage(t.id,H);ee(J.filename),Z(A=>A+1),L.invalidateQueries({queryKey:["projects"]})}catch{}finally{de(!1),Q.current&&(Q.current.value="")}}},he=async()=>{if(t){de(!0);try{await re.deleteProjectCoverImage(t.id),ee(null),Z(xe=>xe+1),L.invalidateQueries({queryKey:["projects"]})}finally{de(!1)}}},ue=xe=>{xe.preventDefault();const H=M.trim();if(H&&!/^https?:\/\//i.test(H)){O(s("projects.urlInvalid"));return}O(null),a({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?H||null:H||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:ue,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:xe=>l(xe.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:xe=>d(xe.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:M,onChange:xe=>{q(xe.target.value),I&&O(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:X?r.jsx("img",{src:`${re.getProjectCoverImageUrl(t.id)}?v=${me}`,alt:s("projects.coverImageAlt"),className:"w-full h-full object-cover"}):r.jsx(uu,{className:"w-6 h-6 text-bambu-gray"})}),r.jsxs("div",{className:"flex flex-col gap-2",children:[r.jsx("input",{ref:Q,type:"file",accept:"image/jpeg,image/png,image/gif,image/webp",onChange:ce,className:"hidden"}),r.jsxs(je,{type:"button",variant:"secondary",onClick:()=>Q.current?.click(),disabled:le,children:[le?r.jsx(pt,{className:"w-4 h-4 animate-spin"}):r.jsx(Sn,{className:"w-4 h-4 mr-1"}),s(X?"projects.coverImageReplace":"projects.coverImageUpload")]}),X&&r.jsxs(je,{type:"button",variant:"secondary",onClick:he,disabled:le,children:[r.jsx($t,{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:AX.map(xe=>r.jsx("button",{type:"button",onClick:()=>m(xe),className:`w-8 h-8 rounded-full transition-transform ${u===xe?"ring-2 ring-white ring-offset-2 ring-offset-bambu-dark-secondary scale-110":""}`,style:{backgroundColor:xe}},xe))})]}),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:xe=>f(xe.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:xe=>w(xe.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:xe=>N(xe.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:xe=>P(xe.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:xe=>j(xe.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:xe=>k(xe.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:xe=>x(xe.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(je,{type:"button",variant:"secondary",onClick:e,children:s("common.cancel")}),r.jsx(je,{type:"submit",disabled:!o.trim()||n,children:n?r.jsx(pt,{className:"w-4 h-4 animate-spin"}):s(t?"common.save":"projects.create")})]})]})]})})}function Uit({projectId:t,altText:e}){const a=y.useRef(null),[n,i]=y.useState(!1),[s,o]=y.useState(null),l=()=>{if(!a.current)return;const d=a.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:a,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:re.getProjectCoverImageUrl(t),alt:e,className:"w-full h-full object-cover",loading:"lazy"})}),n&&s&&pc.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:re.getProjectCoverImageUrl(t),alt:"",className:"w-full h-full object-contain",loading:"lazy"})}),document.body)]})}function Bit({project:t,onClick:e,onEdit:a,onDelete:n,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:ro,color:"text-bambu-green",bg:"bg-bambu-green/10"}:d?{icon:io,color:"text-bambu-gray",bg:"bg-bambu-gray/10"}:t.queue_count>0?{icon:Za,color:"text-blue-400",bg:"bg-blue-400/10"}:{icon:so,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(Uit,{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(Mr,{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(Nm,{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")&&(a(),m(!1))},disabled:!i("projects:update"),title:i("projects:update")?void 0:s("projects.noEditPermission"),children:[r.jsx(Rg,{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")&&(n(),m(!1))},disabled:!i("projects:delete"),title:i("projects:delete")?void 0:s("projects.noDeletePermission"),children:[r.jsx(ea,{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(io,{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(ba,{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(Za,{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:re.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(qr,{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(ba,{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(cn,{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(qr,{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(ba,{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(tL,{className:"w-3.5 h-3.5"}),r.jsx("span",{children:t.queue_count})]})]}),r.jsx(Hn,{className:"w-4 h-4 text-bambu-gray/50 group-hover:text-bambu-gray transition-colors"})]})]})]})}function qit(){const{t}=vt(),e=Oi(),a=ta(),{showToast:n}=na(),{hasPermission:i}=dr(),[s,o]=y.useState(!1),[l,c]=y.useState(),[d,u]=y.useState("active"),[m,p]=y.useState(null),{data:f}=Qe({queryKey:["settings"],queryFn:re.getSettings}),g=Go(f?.currency||"USD"),{data:w,isLoading:b}=Qe({queryKey:["projects",d==="all"?void 0:d],queryFn:()=>re.getProjects(d==="all"?void 0:d)}),x=ot({mutationFn:X=>re.createProject(X),onSuccess:()=>{a.invalidateQueries({queryKey:["projects"]}),o(!1),n(t("projects.toast.created"),"success")},onError:X=>{n(X.message,"error")}}),S=ot({mutationFn:({id:X,data:ee})=>re.updateProject(X,ee),onSuccess:()=>{a.invalidateQueries({queryKey:["projects"]}),o(!1),c(void 0),n(t("projects.toast.updated"),"success")},onError:X=>{n(X.message,"error")}}),N=ot({mutationFn:X=>re.deleteProject(X),onSuccess:()=>{p(null),n(t("projects.toast.deleted"),"success"),setTimeout(()=>window.location.reload(),100)},onError:X=>{p(null),n(X.message,"error")}}),C=ot({mutationFn:X=>re.importProject(X),onSuccess:()=>{a.invalidateQueries({queryKey:["projects"]}),n(t("projects.toast.imported"),"success")},onError:X=>{n(X.message,"error")}}),P=y.useRef(null),T=async()=>{try{const X=await re.getProjects(),ee=await Promise.all(X.map(async me=>await re.exportProjectJson(me.id))),Q=new Blob([JSON.stringify(ee,null,2)],{type:"application/json"}),le=URL.createObjectURL(Q),de=document.createElement("a");de.href=le,de.download=`bambuddy_projects_${new Date().toISOString().split("T")[0]}.json`,de.click(),URL.revokeObjectURL(le),n(t("projects.toast.exported"),"success")}catch(X){n(X.message,"error")}},j=()=>{P.current?.click()},F=async X=>{const ee=X.target.files?.[0];if(ee){try{if(ee.name.toLowerCase().endsWith(".zip"))await re.importProjectFile(ee),a.invalidateQueries({queryKey:["projects"]}),n(t("projects.toast.imported"),"success");else{const le=await ee.text(),de=JSON.parse(le),me=Array.isArray(de)?de:[de];for(const Z of me)await C.mutateAsync(Z);me.length>1&&n(t("projects.toast.multipleImported",{count:me.length}),"success")}}catch(Q){n(`${t("projects.toast.importFailed")}: ${Q.message}`,"error")}X.target.value=""}},k=X=>{l?S.mutate({id:l.id,data:X}):x.mutate(X)},M=X=>{c(X),o(!0)},q=X=>{e(`/projects/${X.id}`)},I=X=>{p(X)},O=()=>{m!==null&&N.mutate(m)},L=w?.reduce((X,ee)=>(X[ee.status]=(X[ee.status]||0)+1,X.all=(X.all||0)+1,X),{})||{};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(so,{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(je,{variant:"secondary",onClick:j,disabled:!i("projects:create"),title:i("projects:create")?t("projects.importProject"):t("projects.noImportPermission"),children:[r.jsx(Sn,{className:"w-4 h-4 mr-2"}),t("projects.import")]}),r.jsxs(je,{variant:"secondary",onClick:T,disabled:!i("projects:read"),title:i("projects:read")?t("projects.exportAll"):t("projects.noExportPermission"),children:[r.jsx(Ur,{className:"w-4 h-4 mr-2"}),t("projects.export")]}),r.jsxs(je,{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(er,{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:Za},{key:"completed",label:t("projects.statusCompleted"),icon:ro},{key:"archived",label:t("projects.statusArchived"),icon:io},{key:"all",label:t("common.all"),icon:so}].map(({key:X,label:ee,icon:Q})=>r.jsxs("button",{onClick:()=>u(X),className:`flex items-center gap-2 px-4 py-2 text-sm rounded-lg transition-all ${d===X?"bg-bambu-card text-white shadow-sm":"text-bambu-gray hover:text-white"}`,children:[r.jsx(Q,{className:"w-4 h-4"}),r.jsx("span",{children:ee}),L[X]>0&&r.jsx("span",{className:`text-xs px-1.5 py-0.5 rounded-full ${d===X?"bg-bambu-green/20 text-bambu-green":"bg-bambu-dark-tertiary"}`,children:L[X]})]},X))}),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(so,{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(je,{onClick:()=>o(!0),disabled:!i("projects:create"),title:i("projects:create")?void 0:t("projects.noCreatePermission"),children:[r.jsx(er,{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(X=>r.jsx(Bit,{project:X,onClick:()=>q(X),onEdit:()=>M(X),onDelete:()=>I(X.id),hasPermission:i,t},X.id))}),m!==null&&r.jsx(wa,{title:t("projects.deleteProject"),message:t("projects.deleteConfirm"),confirmText:t("projects.deleteProject"),variant:"danger",onConfirm:O,onCancel:()=>p(null)}),s&&r.jsx(lde,{project:l,onClose:()=>{o(!1),c(void 0)},onSave:k,isLoading:x.isPending||S.isPending,currencySymbol:g,t})]})}function Hit(t){const e=t.toLowerCase();return e.endsWith(".gcode")||e.endsWith(".gcode.3mf")}function $it(t){return t>=1e3?`${(t/1e3).toFixed(2)}kg`:`${Math.round(t)}g`}function Vit({status:t,t:e}){const a={active:"bg-bambu-green/20 text-bambu-green",completed:"bg-blue-500/20 text-blue-400",archived:"bg-bambu-gray/20 text-bambu-gray"},n=a[t]||a.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 ${n}`,children:i[t]||t.charAt(0).toUpperCase()+t.slice(1)})}function jX({icon:t,label:e,value:a,subValue:n,hint:i,color:s="text-bambu-gray"}){return r.jsx(Tt,{children:r.jsx(Mt,{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:a}),n&&r.jsx("p",{className:"text-xs text-bambu-gray/70",children:n})]})]})})})}function Git({archives:t,t:e}){return t.length===0?r.jsxs("div",{className:"text-center py-8 text-bambu-gray",children:[r.jsx(qr,{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(a=>r.jsxs(Is,{to:`/archives?search=${encodeURIComponent(a.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:[a.thumbnail_path?r.jsx("img",{src:re.getArchiveThumbnail(a.id),alt:a.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(qr,{className:"w-8 h-8"})}),a.status==="failed"&&r.jsx("div",{className:"absolute inset-0 bg-red-500/30 flex items-center justify-center",children:r.jsx(jr,{className:"w-8 h-8 text-white"})}),a.status==="completed"&&r.jsx("div",{className:"absolute top-1 right-1",children:r.jsx(hr,{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:a.print_name||"Unknown"})})]},a.id))})}function Wit({priority:t,t:e}){const a={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:n,label:i}=a[t]||a.normal;return r.jsxs("span",{className:`px-2 py-1 rounded text-xs font-medium flex items-center gap-1 ${n}`,children:[t==="urgent"&&r.jsx(ba,{className:"w-3 h-3"}),i]})}function N3(t,e){if(!t)return null;const a=Qa(t);if(!a)return null;const n=new Date,i=Math.ceil((a.getTime()-n.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 Kit(){const{id:t}=TS(),e=Oi(),{t:a}=vt(),n=ta(),{showToast:i}=na(),{hasPermission:s}=dr(),[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}=Qe({queryKey:["project",b],queryFn:()=>re.getProject(b),enabled:b>0}),{data:C,isLoading:P}=Qe({queryKey:["project-archives",b],queryFn:()=>re.getProjectArchives(b),enabled:b>0}),{data:T,isLoading:j}=Qe({queryKey:["project-bom",b],queryFn:()=>re.getProjectBOM(b),enabled:b>0}),{data:F,isLoading:k}=Qe({queryKey:["project-timeline",b],queryFn:()=>re.getProjectTimeline(b,20),enabled:b>0}),{data:M}=Qe({queryKey:["settings"],queryFn:re.getSettings}),{data:q}=Qe({queryKey:["project-folders",b],queryFn:()=>re.getLibraryFoldersByProject(b),enabled:b>0}),{data:I,isLoading:O}=Qe({queryKey:["project-files",b],queryFn:()=>re.getLibraryFiles(null,!1,b),enabled:b>0}),L=y.useMemo(()=>{const Te=new Map;for(const Fe of I??[])if(Fe.folder_id!=null){const et=Te.get(Fe.folder_id)??[];et.push(Fe),Te.set(Fe.folder_id,et)}return Te},[I]),X=Go(M?.currency||"USD"),ee=M?.time_format||"system",Q=ot({mutationFn:Te=>re.updateProject(b,Te),onSuccess:()=>{n.invalidateQueries({queryKey:["project",b]}),n.invalidateQueries({queryKey:["projects"]}),l(!1),d(!1),i(a("projectDetail.toast.projectUpdated"),"success")},onError:Te=>{i(Te.message,"error")}}),le=()=>{m(x?.notes||""),d(!0)},de=()=>{Q.mutate({notes:u})},me=()=>{d(!1),m("")},[Z,ce]=y.useState(""),[he,ue]=y.useState(1),[xe,H]=y.useState(""),[J,A]=y.useState(""),[E,B]=y.useState(""),[W,z]=y.useState(!1),[ie,U]=y.useState(!1),[G,K]=y.useState(null),[Y,se]=y.useState(""),[oe,fe]=y.useState(1),[ae,pe]=y.useState(""),[$,R]=y.useState(""),[ne,be]=y.useState(""),[ve,ke]=y.useState({isOpen:!1,title:"",message:"",onConfirm:()=>{}}),ye=ot({mutationFn:Te=>re.createBOMItem(b,Te),onSuccess:()=>{n.invalidateQueries({queryKey:["project-bom",b]}),n.invalidateQueries({queryKey:["project",b]}),ce(""),ue(1),H(""),A(""),B(""),z(!1),i(a("projectDetail.toast.partAdded"),"success")},onError:Te=>i(Te.message,"error")}),ge=ot({mutationFn:({itemId:Te,data:Fe})=>re.updateBOMItem(b,Te,Fe),onSuccess:()=>{n.invalidateQueries({queryKey:["project-bom",b]}),n.invalidateQueries({queryKey:["project",b]}),K(null)},onError:Te=>i(Te.message,"error")}),Me=ot({mutationFn:Te=>re.deleteBOMItem(b,Te),onSuccess:()=>{n.invalidateQueries({queryKey:["project-bom",b]}),n.invalidateQueries({queryKey:["project",b]}),i(a("projectDetail.toast.partRemoved"),"success")},onError:Te=>i(Te.message,"error")}),Be=Te=>{Te.preventDefault(),Z.trim()&&ye.mutate({name:Z.trim(),quantity_needed:he,unit_price:xe?parseFloat(xe):void 0,sourcing_url:J.trim()||void 0,remarks:E.trim()||void 0})},Le=Te=>{const Fe=Te.is_complete?0:Te.quantity_needed;ge.mutate({itemId:Te.id,data:{quantity_acquired:Fe}})},Oe=(Te,Fe)=>{ke({isOpen:!0,title:a("projectDetail.bom.deletePart"),message:a("projectDetail.bom.deleteConfirm",{name:Fe}),onConfirm:()=>{ke(et=>({...et,isOpen:!1})),Me.mutate(Te)}})},Re=Te=>{K(Te),se(Te.name),fe(Te.quantity_needed),pe(Te.unit_price?.toString()||""),R(Te.sourcing_url||""),be(Te.remarks||"")},Ke=Te=>{Te.preventDefault(),!(!G||!Y.trim())&&ge.mutate({itemId:G.id,data:{name:Y.trim(),quantity_needed:oe,unit_price:ae?parseFloat(ae):void 0,sourcing_url:$.trim()||void 0,remarks:ne.trim()||void 0}})},Ue=()=>{K(null)},lt=async()=>{try{const{blob:Te,filename:Fe}=await re.exportProjectZip(Number(b)),et=URL.createObjectURL(Te),We=document.createElement("a");We.href=et,We.download=Fe||`${x?.name||"project"}_${new Date().toISOString().split("T")[0]}.zip`,We.click(),URL.revokeObjectURL(et),i(a("projectDetail.toast.projectExported"),"success")}catch(Te){i(Te.message,"error")}},Ee=ot({mutationFn:()=>re.createTemplateFromProject(b),onSuccess:()=>{n.invalidateQueries({queryKey:["projects"]}),i(a("projectDetail.toast.templateCreated"),"success")},onError:Te=>i(Te.message,"error")}),st=Te=>Ug(Te,ee,{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?`${a("common.error")}: ${N.message}`:a("projectDetail.notFound")}),r.jsx(je,{variant:"secondary",className:"mt-4",onClick:()=>e("/projects"),children:a("projectDetail.backToProjects")})]});const Ne=x.stats,Ze=Ne?.progress_percent??0,Ye=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:a("nav.projects")}),r.jsx(Hn,{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(PT,{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(Vit,{status:x.status,t:a})]}),r.jsxs("div",{className:"flex gap-2",children:[r.jsxs(je,{variant:"secondary",onClick:lt,disabled:!s("projects:read"),title:s("projects:read")?a("projectDetail.exportProject"):a("projectDetail.noExportPermission"),children:[r.jsx(Ur,{className:"w-4 h-4 mr-2"}),a("projectDetail.export")]}),r.jsxs(je,{onClick:()=>l(!0),disabled:!s("projects:update"),title:s("projects:update")?void 0:a("projectDetail.noEditPermission"),children:[r.jsx(Rg,{className:"w-4 h-4 mr-2"}),a("common.edit")]})]})]}),(x.target_count||x.target_parts_count)&&r.jsx(Tt,{children:r.jsxs(Mt,{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:a("projectDetail.progress.platesProgress")}),r.jsxs("span",{className:"text-sm font-medium text-white",children:[Ne?.total_archives||0," / ",x.target_count," ",a("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(Ze,100)}%`,backgroundColor:Ze>=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:a("projectDetail.progress.percentComplete",{percent:Ze.toFixed(0)})}),Ne?.remaining_prints!=null&&Ne.remaining_prints>0&&r.jsx("span",{className:"text-xs text-bambu-gray/70",children:a("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:a("projectDetail.progress.partsProgress")}),r.jsxs("span",{className:"text-sm font-medium text-white",children:[Ne?.completed_prints||0," / ",x.target_parts_count," ",a("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(Ye,100)}%`,backgroundColor:Ye>=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:a("projectDetail.progress.percentComplete",{percent:Ye.toFixed(0)})}),Ne?.remaining_parts!=null&&Ne.remaining_parts>0&&r.jsx("span",{className:"text-xs text-bambu-gray/70",children:a("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(Tt,{children:r.jsx(Mt,{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(qr,{className:"w-5 h-5"})}),r.jsxs("div",{children:[r.jsx("p",{className:"text-sm text-bambu-gray",children:a("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:a("projectDetail.stats.total")})]}),Ne.failed_prints>0&&r.jsx("p",{className:"text-sm text-status-error",children:a("projectDetail.stats.failed",{count:Ne.failed_prints})}),r.jsx("p",{className:"text-sm text-bambu-gray",children:a("projectDetail.stats.partsPrinted",{count:Ne.completed_prints})})]})]})})}),r.jsx(jX,{icon:Za,label:a("projectDetail.stats.printTime"),value:g0e(Ne.total_print_time_hours),color:"text-yellow-400"}),r.jsx(jX,{icon:gr,label:a("projectDetail.stats.filamentUsed"),value:$it(Ne.total_filament_grams),color:"text-purple-400"})]}),Ne&&(()=>{const Te=Ne.estimated_cost+Ne.total_energy_cost+Ne.bom_cost;return Ne.estimated_cost>0||Te>0||x.budget!==null})()&&r.jsx(Tt,{children:r.jsxs(Mt,{className:"p-4",children:[r.jsx("h2",{className:"text-lg font-semibold text-white mb-3",children:a("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:a("projectDetail.cost.filamentCost")}),r.jsxs("p",{className:"text-lg font-semibold text-white",children:[X,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:a("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:["(",X,Ne.total_energy_cost.toFixed(2),")"]})]})]}),(()=>{const Te=Ne.estimated_cost+Ne.total_energy_cost+Ne.bom_cost;return Te<=0?null:r.jsxs("div",{children:[r.jsx("p",{className:"text-xs text-bambu-gray uppercase",children:a("projectDetail.cost.totalCost")}),r.jsxs("p",{className:"text-lg font-semibold text-bambu-green",children:[X,Te.toFixed(2)]}),Ne.bom_cost>0&&r.jsx("p",{className:"text-xs text-bambu-gray/70",children:a("projectDetail.cost.includesBom")})]})})(),x.budget!==null&&(()=>{const Te=Ne.estimated_cost+Ne.total_energy_cost+Ne.bom_cost,Fe=x.budget-Te;return r.jsxs("div",{children:[r.jsx("p",{className:"text-xs text-bambu-gray uppercase",children:a("projectDetail.cost.budget")}),r.jsxs("p",{className:"text-sm text-bambu-gray",children:[a("projectDetail.cost.total"),": ",r.jsxs("span",{className:"text-white font-semibold",children:[X,x.budget.toFixed(2)]})]}),r.jsxs("p",{className:`text-sm ${Fe>=0?"text-bambu-green":"text-red-400"}`,children:[a("projectDetail.cost.remaining"),": ",r.jsxs("span",{className:"font-semibold",children:[X,Fe.toFixed(2)]})]})]})})()]})]})}),x.children&&x.children.length>0&&r.jsx(Tt,{children:r.jsxs(Mt,{className:"p-4",children:[r.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2 mb-3",children:[r.jsx(Hbe,{className:"w-5 h-5"}),a("projectDetail.subProjects.title",{count:x.children.length})]}),r.jsx("div",{className:"space-y-2",children:x.children.map(Te=>r.jsxs(Is,{to:`/projects/${Te.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:Te.color||"#6b7280"}}),r.jsx("span",{className:"text-white",children:Te.name}),r.jsx("span",{className:`text-xs px-2 py-0.5 rounded ${Te.status==="completed"?"bg-status-ok/20 text-status-ok":Te.status==="archived"?"bg-bambu-gray/20 text-bambu-gray":"bg-blue-500/20 text-blue-400"}`,children:Te.status})]}),Te.progress_percent!==null&&r.jsxs("span",{className:"text-sm text-bambu-gray",children:[Te.progress_percent.toFixed(0),"%"]})]},Te.id))})]})}),x.parent_id&&x.parent_name&&r.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[r.jsx(cn,{className:"w-4 h-4 text-bambu-gray"}),r.jsx("span",{className:"text-bambu-gray",children:a("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:a("projectDetail.priorityLabel")}),r.jsx(Wit,{priority:x.priority,t:a})]}),x.due_date&&r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(vn,{className:"w-4 h-4 text-bambu-gray"}),r.jsx("span",{className:"text-sm text-white",children:zg(x.due_date,{year:"numeric",month:"short",day:"numeric"})}),N3(x.due_date,a)&&r.jsxs("span",{className:`text-xs ${N3(x.due_date,a).color}`,children:["(",N3(x.due_date,a).label,")"]})]}),x.tags&&r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(Ym,{className:"w-4 h-4 text-bambu-gray"}),r.jsx("div",{className:"flex flex-wrap gap-1",children:x.tags.split(",").map((Te,Fe)=>r.jsx("span",{className:"px-2 py-0.5 bg-bambu-dark-tertiary text-bambu-gray text-xs rounded",children:Te.trim()},Fe))})]})]}),r.jsx(Tt,{children:r.jsxs(Mt,{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"}),a("projectDetail.notes.title")]}),c?r.jsxs("div",{className:"flex gap-2",children:[r.jsxs(je,{variant:"secondary",size:"sm",onClick:me,disabled:Q.isPending,children:[r.jsx($t,{className:"w-4 h-4 mr-1"}),a("common.cancel")]}),r.jsxs(je,{size:"sm",onClick:de,disabled:Q.isPending,children:[Q.isPending?r.jsx(pt,{className:"w-4 h-4 animate-spin mr-1"}):r.jsx(fs,{className:"w-4 h-4 mr-1"}),a("common.save")]})]}):r.jsxs(je,{variant:"secondary",size:"sm",onClick:le,disabled:!s("projects:update"),title:s("projects:update")?void 0:a("projectDetail.notes.noEditPermission"),children:[r.jsx(Rg,{className:"w-4 h-4 mr-1"}),a("common.edit")]})]}),c?r.jsx(XI,{content:u,onChange:m,placeholder:a("projectDetail.notes.placeholder")}):x.notes?r.jsx("div",{className:"prose prose-invert prose-sm max-w-none",dangerouslySetInnerHTML:{__html:k5.sanitize(x.notes)}}):r.jsx("p",{className:"text-bambu-gray/70 text-sm italic",children:a("projectDetail.notes.empty")})]})}),r.jsx(Tt,{children:r.jsxs(Mt,{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(El,{className:"w-5 h-5"}),a("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:a("projectDetail.files.linkFolders")})," ",a("projectDetail.files.forQuickAccess")]}),q&&q.length>0?r.jsx("div",{className:"space-y-4",children:q.map(Te=>{const Fe=L.get(Te.id)??[],et=O;return r.jsxs("div",{children:[r.jsxs(Is,{to:`/files?folder=${Te.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(El,{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:Te.name}),r.jsx("p",{className:"text-xs text-bambu-gray",children:a("projectDetail.files.fileCount",{count:Te.file_count})})]})]}),r.jsx(Hn,{className:"w-4 h-4 text-bambu-gray shrink-0"})]}),et?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"})}):Fe.length===0?r.jsx("p",{className:"text-bambu-gray/60 text-xs italic px-3",children:a("projectDetail.files.noFiles")}):r.jsx("div",{className:"space-y-1 pl-3",children:Fe.map(We=>{const Pe=Hit(We.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:We.thumbnail_path?r.jsx("img",{src:re.getLibraryFileThumbnailUrl(We.id),alt:We.print_name||We.filename,className:"w-full h-full object-cover"}):r.jsx(Ah,{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:We.print_name||We.filename,children:We.print_name||We.filename}),r.jsx("span",{className:`text-xs px-1.5 py-0.5 rounded font-medium ${We.file_type==="3mf"?"bg-bambu-green/20 text-bambu-green":We.file_type==="gcode"?"bg-blue-500/20 text-blue-400":"bg-bambu-gray/20 text-bambu-gray"}`,children:We.file_type.toUpperCase()})]}),Pe&&r.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[r.jsx("button",{onClick:()=>f(We),title:a("projectDetail.files.print"),className:"p-1.5 rounded hover:bg-bambu-green/20 text-bambu-green transition-colors",children:r.jsx(ys,{className:"w-4 h-4"})}),r.jsx("button",{onClick:()=>w(We),title:a("projectDetail.files.addToQueue"),className:"p-1.5 rounded hover:bg-blue-500/20 text-blue-400 transition-colors",children:r.jsx(uge,{className:"w-4 h-4"})})]})]},We.id)})})]},Te.id)})}):r.jsx("p",{className:"text-bambu-gray/70 text-sm italic",children:a("projectDetail.files.empty")})]})}),r.jsx(Tt,{children:r.jsxs(Mt,{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(mb,{className:"w-5 h-5"}),a("projectDetail.bom.title"),Ne&&Ne.bom_total_items>0&&r.jsxs("span",{className:"text-sm font-normal text-bambu-gray",children:["(",a("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(Te=>Te.is_complete)&&r.jsx("button",{onClick:()=>U(!ie),className:`text-xs px-2 py-1 rounded transition-colors ${ie?"bg-bambu-green/20 text-bambu-green":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:a(ie?"projectDetail.bom.showAll":"projectDetail.bom.hideDone")}),!W&&r.jsxs(je,{variant:"secondary",size:"sm",onClick:()=>z(!0),disabled:!s("projects:update"),title:s("projects:update")?void 0:a("projectDetail.bom.noAddPermission"),children:[r.jsx(er,{className:"w-4 h-4 mr-1"}),a("projectDetail.bom.addPart")]})]})]}),W&&r.jsxs("form",{onSubmit:Be,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:Z,onChange:Te=>ce(Te.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:a("projectDetail.bom.partNamePlaceholder"),autoFocus:!0}),r.jsxs("div",{className:"flex gap-2",children:[r.jsx("input",{type:"number",value:he,onChange:Te=>ue(parseInt(Te.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:a("projectDetail.bom.qty")}),r.jsx("input",{type:"number",step:"0.01",value:xe,onChange:Te=>H(Te.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:a("projectDetail.bom.price",{currency:X})})]})]}),r.jsx("input",{type:"url",value:J,onChange:Te=>A(Te.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:a("projectDetail.bom.sourcingUrlPlaceholder")}),r.jsx("input",{type:"text",value:E,onChange:Te=>B(Te.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:a("projectDetail.bom.remarksPlaceholder")}),r.jsxs("div",{className:"flex justify-end gap-2",children:[r.jsx(je,{type:"button",variant:"secondary",size:"sm",onClick:()=>z(!1),children:a("common.cancel")}),r.jsx(je,{type:"submit",size:"sm",disabled:!Z.trim()||ye.isPending,children:ye.isPending?r.jsx(pt,{className:"w-4 h-4 animate-spin"}):a("projectDetail.bom.addPart")})]})]}),j?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(Te=>!ie||!Te.is_complete).map(Te=>r.jsx("div",{className:`p-3 rounded-lg transition-colors ${Te.is_complete?"bg-status-ok/10":"bg-bambu-dark"}`,children:G?.id===Te.id?r.jsxs("form",{onSubmit:Ke,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:Y,onChange:Fe=>se(Fe.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:a("projectDetail.bom.partName"),autoFocus:!0}),r.jsxs("div",{className:"flex gap-2",children:[r.jsx("input",{type:"number",value:oe,onChange:Fe=>fe(parseInt(Fe.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:a("projectDetail.bom.qty")}),r.jsx("input",{type:"number",step:"0.01",value:ae,onChange:Fe=>pe(Fe.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:a("projectDetail.bom.price",{currency:X})})]})]}),r.jsx("input",{type:"url",value:$,onChange:Fe=>R(Fe.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:a("projectDetail.bom.sourcingUrlPlaceholder")}),r.jsx("input",{type:"text",value:ne,onChange:Fe=>be(Fe.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:a("projectDetail.bom.remarksPlaceholder")}),r.jsxs("div",{className:"flex justify-end gap-2",children:[r.jsx(je,{type:"button",variant:"secondary",size:"sm",onClick:Ue,children:a("common.cancel")}),r.jsx(je,{type:"submit",size:"sm",disabled:!Y.trim()||ge.isPending,children:ge.isPending?r.jsx(pt,{className:"w-4 h-4 animate-spin"}):a("common.save")})]})]}):r.jsxs("div",{className:"flex items-start gap-3",children:[r.jsx("button",{onClick:()=>s("projects:update")&&Le(Te),disabled:ge.isPending||!s("projects:update"),title:s("projects:update")?void 0:a("projectDetail.bom.noUpdatePermission"),className:`w-5 h-5 mt-0.5 rounded border-2 flex items-center justify-center transition-colors shrink-0 ${Te.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:Te.is_complete&&r.jsx(hr,{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 ${Te.is_complete?"text-bambu-gray line-through":"text-white"}`,children:[Te.name,r.jsxs("span",{className:"text-bambu-gray font-normal ml-2",children:["x",Te.quantity_needed]})]}),Te.unit_price!==null&&r.jsxs("span",{className:"text-xs text-bambu-green whitespace-nowrap",children:[X,(Te.unit_price*Te.quantity_needed).toFixed(2)]})]}),r.jsxs("div",{className:"flex items-center gap-1",children:[r.jsx("button",{onClick:()=>s("projects:update")&&Re(Te),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")?a("common.edit"):a("projectDetail.bom.noEditPermission"),children:r.jsx(yi,{className:"w-4 h-4"})}),r.jsx("button",{onClick:()=>s("projects:update")&&Oe(Te.id,Te.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")?a("common.delete"):a("projectDetail.bom.noDeletePermission"),children:r.jsx(ea,{className:"w-4 h-4"})})]})]}),Te.sourcing_url&&r.jsxs("a",{href:Te.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:Fe=>Fe.stopPropagation(),children:[r.jsx(Mr,{className:"w-3 h-3 shrink-0"}),r.jsx("span",{className:"truncate",children:(()=>{try{return new URL(Te.sourcing_url).hostname.replace("www.","")}catch{return Te.sourcing_url}})()})]}),Te.remarks&&r.jsx("p",{className:"mt-1 text-xs text-bambu-gray/80 italic",children:Te.remarks})]})]})},Te.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:a("projectDetail.bom.totalCost")}),r.jsxs("span",{className:"text-white font-medium",children:[X,Ne.bom_cost.toFixed(2)]})]})]}):r.jsx("p",{className:"text-bambu-gray/70 text-sm italic",children:a("projectDetail.bom.empty")})]})}),r.jsx(Tt,{children:r.jsxs(Mt,{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(Wh,{className:"w-5 h-5"}),a("projectDetail.timeline.title")]})}),k?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((Te,Fe)=>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 ${Te.event_type==="print_completed"?"bg-status-ok/20 text-status-ok":Te.event_type==="print_failed"?"bg-status-error/20 text-status-error":Te.event_type==="print_started"?"bg-yellow-500/20 text-yellow-400":"bg-bambu-dark-tertiary text-bambu-gray"}`,children:[Te.event_type==="print_completed"&&r.jsx(hr,{className:"w-4 h-4"}),Te.event_type==="print_failed"&&r.jsx(jr,{className:"w-4 h-4"}),Te.event_type==="print_started"&&r.jsx(gr,{className:"w-4 h-4"}),Te.event_type==="queued"&&r.jsx(tL,{className:"w-4 h-4"}),Te.event_type==="project_created"&&r.jsx(er,{className:"w-4 h-4"})]}),r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsx("p",{className:"text-sm text-white",children:Te.title}),Te.description&&r.jsx("p",{className:"text-xs text-bambu-gray truncate",children:Te.description}),r.jsx("p",{className:"text-xs text-bambu-gray/70",children:st(Te.timestamp)})]})]},Fe))}):r.jsx("p",{className:"text-bambu-gray/70 text-sm italic",children:a("projectDetail.timeline.empty")})]})}),!x.is_template&&r.jsx("div",{className:"flex justify-end",children:r.jsxs(je,{variant:"secondary",size:"sm",onClick:()=>Ee.mutate(),disabled:Ee.isPending||!s("projects:create"),title:s("projects:create")?void 0:a("projectDetail.template.noCreatePermission"),children:[Ee.isPending?r.jsx(pt,{className:"w-4 h-4 animate-spin mr-2"}):r.jsx(xi,{className:"w-4 h-4 mr-2"}),a("projectDetail.template.saveAsTemplate")]})}),Ne&&(Ne.queued_prints>0||Ne.in_progress_prints>0)&&r.jsx(Tt,{children:r.jsxs(Mt,{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(tL,{className:"w-5 h-5"}),a("projectDetail.queue.title")]}),r.jsx(Is,{to:`/queue?project=${b}`,className:"text-sm text-bambu-green hover:underline",children:a("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:a("projectDetail.queue.printing",{count:Ne.in_progress_prints})}),Ne.queued_prints>0&&r.jsx("span",{className:"text-bambu-gray",children:a("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(qr,{className:"w-5 h-5"}),a("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(Git,{archives:C||[],t:a})]}),o&&r.jsx(lde,{t:a,currencySymbol:X,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:Te=>Q.mutate(Te),isLoading:Q.isPending}),ve.isOpen&&r.jsx(wa,{title:ve.title,message:ve.message,confirmText:a("common.delete"),variant:"danger",onConfirm:ve.onConfirm,onCancel:()=>ke(Te=>({...Te,isOpen:!1}))}),p&&r.jsx(wc,{mode:"reprint",libraryFileId:p.id,archiveName:p.print_name||p.filename,projectId:b,onClose:()=>f(null),onSuccess:()=>{f(null),n.invalidateQueries({queryKey:["archives"]})}}),g&&r.jsx(wc,{mode:"add-to-queue",libraryFileId:g.id,archiveName:g.print_name||g.filename,projectId:b,onClose:()=>w(null),onSuccess:()=>{w(null),n.invalidateQueries({queryKey:["queue"]})}})]})}function Qit({archiveId:t,libraryFileId:e,title:a,fileType:n,onClose:i}){const{t:s}=vt(),{data:o}=Qe({queryKey:["settings"],queryFn:re.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),[j,F]=y.useState(!1),[k,M]=y.useState(null),[q,I]=y.useState(!1),[O,L]=y.useState(!1),X=y.useRef(null),ee=y.useRef(null),Q=10,le=160,de=240,me=.35;y.useEffect(()=>{const ae=pe=>{pe.key==="Escape"&&i()};return window.addEventListener("keydown",ae),()=>window.removeEventListener("keydown",ae)},[i]),y.useEffect(()=>{if(g(!0),c){const ae=(n||"").toLowerCase(),pe=ae==="3mf"||ae==="stl",$=ae==="gcode"||ae==="3mf";p({has_model:pe,has_gcode:$,has_source:!1,build_volume:{x:256,y:256,z:256},filament_colors:[]}),u(pe?"3d":$?"gcode":null),g(!1);return}if(!t){p(null),u(null),g(!1);return}re.getArchiveCapabilities(t).then(ae=>{p(ae),ae.has_model?u("3d"):ae.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,n,c]),y.useEffect(()=>{if(S(!0),C(null),T(0),c){const ae=(n||"").toLowerCase();if(!e||ae!=="3mf"){b(null),S(!1);return}re.getLibraryFilePlates(e).then(pe=>b(pe)).catch(()=>b(null)).finally(()=>S(!1));return}if(!t){b(null),S(!1);return}re.getArchivePlates(t).then(ae=>b(ae)).catch(()=>b(null)).finally(()=>S(!1))},[t,n,c,e]);const Z=y.useMemo(()=>w?.plates??[],[w]),ce=(w?.is_multi_plate??!1)&&Z.length>1,he=j&&ce,ue=N==null?null:Z.find(ae=>ae.index===N)??null,xe=ae=>ae.object_count??ae.objects?.length??0,H=Z.reduce((ae,pe)=>ae+xe(pe),0),J=ue?xe(ue):H,A=ue?s("modelViewer.plateNumber",{number:ue.index}):s("modelViewer.allPlates"),E=Z.length>0,B=y.useRef(null),W=y.useRef(null),[z,ie]=y.useState(10),[U,G]=y.useState(3),K=Z.length>z,Y=Math.max(1,Math.ceil(Z.length/z)),se=K?Z.slice(P*z,(P+1)*z):Z;y.useEffect(()=>{if(!he){ie(10),G(3);return}const ae=B.current,pe=W.current;if(!ae||!pe)return;let $=0;const R=()=>{const ve=pe.clientWidth,ye=Math.floor(ve/210),ge=Math.max(3,Math.min(5,ye||3));G(Ee=>Ee===ge?Ee:ge);const Me=window.getComputedStyle(ae),Be=Number.parseFloat(Me.rowGap||"0"),Oe=ae.querySelector("button")?.getBoundingClientRect().height??44,Re=pe.clientHeight,Ue=Math.max(1,Math.floor((Re+Be)/(Oe+Be)))*ge,lt=Math.max(1,Ue-1);ie(Ee=>Ee===lt?Ee:lt)},ne=()=>{$&&cancelAnimationFrame($),$=requestAnimationFrame(R)};ne();const be=new ResizeObserver(ne);return be.observe(pe),be.observe(ae),()=>{$&&cancelAnimationFrame($),be.disconnect()}},[he,Z.length]),y.useEffect(()=>{if(!K){T(0);return}T(ae=>Math.min(ae,Y-1))},[Z.length,K,Y]),y.useEffect(()=>{if(!K||N==null)return;const ae=Z.findIndex($=>$.index===N);if(ae<0)return;const pe=Math.floor(ae/z);T($=>$===pe?$:pe)},[Z,z,N,K]),y.useEffect(()=>{if(!he){M(null),L(!1);return}if(O)return;const ae=X.current,pe=ee.current;if(!ae||!pe)return;const $=ae.clientHeight;if(!$)return;const R=Math.max(de,$*me),ne=Math.max(le,$-Q-R),be=Math.min(pe.scrollHeight,ne);M(Math.max(le,be))},[he,O,Z.length,P,Q,le,de,me]),y.useEffect(()=>{if(!q)return;const ae=$=>{const R=X.current;if(!R)return;const ne=R.getBoundingClientRect(),be=ne.height;if(!be)return;const ve=Math.max(de,be*me),ke=Math.max(le,be-Q-ve),ye=Math.min(ke,Math.max(le,$.clientY-ne.top));M(ye)},pe=()=>{I(!1),L(!0)};return document.addEventListener("mousemove",ae),document.addEventListener("mouseup",pe),document.body.style.cursor="row-resize",document.body.style.userSelect="none",()=>{document.removeEventListener("mousemove",ae),document.removeEventListener("mouseup",pe),document.body.style.cursor="",document.body.style.userSelect=""}},[q,Q,le,de,me]);const oe=c?(n||"").toLowerCase()==="3mf":!0,fe=async()=>{if(!oe)return;const ae=a||"model";try{if(c){const{token:pe}=await re.createLibrarySlicerToken(e),$=re.getLibrarySlicerDownloadUrl(e,pe,ae);Lm(`${window.location.origin}${$}`,l)}else{const{token:pe}=await re.createArchiveSlicerToken(t),$=re.getArchiveSlicerDownloadUrl(t,pe,ae);Lm(`${window.location.origin}${$}`,l)}}catch{if(c){const pe=`${window.location.origin}${re.getLibraryFileDownloadUrl(e)}`;Lm(pe,l)}else{const pe=`${window.location.origin}${re.getArchiveForSlicer(t,ae)}`;Lm(pe,l)}}};return r.jsx("div",{className:`fixed inset-0 bg-black/70 flex items-center justify-center z-50 ${j?"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 ${j?"h-full max-w-none rounded-none":"h-[80vh] max-w-4xl rounded-xl"}`,onClick:ae=>ae.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:a}),E&&r.jsxs("span",{className:"text-xs text-bambu-gray bg-bambu-dark-tertiary/70 px-2 py-1 rounded whitespace-nowrap",children:[A,": ",s("modelViewer.objectCount",{count:J})]})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsxs(je,{variant:"secondary",size:"sm",onClick:fe,disabled:!oe,children:[r.jsx(Mr,{className:"w-4 h-4"}),s("modelViewer.openInSlicer")]}),r.jsx(je,{variant:"secondary",size:"sm",onClick:()=>F(ae=>!ae),title:j?"Exit fullscreen":"Enter fullscreen",children:j?r.jsx(MO,{className:"w-4 h-4"}):r.jsx(MT,{className:"w-4 h-4"})}),r.jsx(je,{variant:"ghost",size:"sm",onClick:i,children:r.jsx($t,{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(Mi,{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:X,className:`w-full h-full flex flex-col ${he?"gap-0 min-h-0":"gap-3"}`,children:[ce&&r.jsxs("div",{ref:ee,style:he&&k!=null?{height:k}:void 0,className:`rounded-lg border border-bambu-dark-tertiary bg-bambu-dark p-3 ${he?"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(cn,{className:"w-4 h-4"}),s("modelViewer.plates"),x&&r.jsx(pt,{className:"w-3 h-3 animate-spin"})]}),r.jsxs("div",{className:he?"flex flex-col min-h-0 flex-1":void 0,children:[r.jsx("div",{ref:W,className:he?"min-h-0 overflow-hidden pr-1 flex-1":void 0,children:r.jsxs("div",{ref:B,className:he?"grid gap-2":"grid grid-cols-2 md:grid-cols-3 gap-2",style:he?{gridTemplateColumns:`repeat(${U}, 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 ${he?"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 ${he?"w-8 h-8":"w-10 h-10"}`,children:r.jsx(cn,{className:`${he?"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:`${he?"text-xs":"text-sm"} text-white font-medium truncate`,children:s("modelViewer.allPlates")}),r.jsx("p",{className:`${he?"text-[10px]":"text-xs"} text-bambu-gray truncate`,children:s("modelViewer.plateCount",{count:Z.length})})]}),N==null&&r.jsx(kr,{className:`${he?"w-3.5 h-3.5":"w-4 h-4"} text-bambu-green flex-shrink-0`})]}),se.map(ae=>r.jsxs("button",{type:"button",onClick:()=>C(ae.index),className:`flex items-center rounded-lg border text-left transition-colors ${he?"gap-1.5 p-1.5 w-full":"gap-2 p-2"} ${N===ae.index?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary bg-bambu-dark-secondary hover:border-bambu-gray"}`,children:[ae.has_thumbnail&&ae.thumbnail_url?r.jsx("img",{src:ae.thumbnail_url,alt:`Plate ${ae.index}`,className:`${he?"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 ${he?"w-8 h-8":"w-10 h-10"}`,children:r.jsx(cn,{className:`${he?"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:`${he?"text-xs":"text-sm"} text-white font-medium truncate`,children:ae.name||s("modelViewer.plateNumber",{number:ae.index})}),r.jsx("p",{className:`${he?"text-[10px]":"text-xs"} text-bambu-gray truncate`,children:s("modelViewer.objectCount",{count:ae.object_count??ae.objects?.length??0})})]}),N===ae.index&&r.jsx(kr,{className:`${he?"w-3.5 h-3.5":"w-4 h-4"} text-bambu-green flex-shrink-0`})]},ae.index))]})}),(ue||K)&&r.jsxs("div",{className:"mt-auto pt-3 flex items-center gap-4 text-xs text-bambu-gray overflow-x-auto",children:[ue&&r.jsxs("div",{className:"flex items-center gap-3 whitespace-nowrap",children:[r.jsx("span",{children:s("modelViewer.plateNumber",{number:ue.index})}),ue.print_time_seconds!=null&&r.jsx("span",{children:s("modelViewer.eta",{minutes:Math.round(ue.print_time_seconds/60)})}),ue.filament_used_grams!=null&&r.jsxs("span",{children:[ue.filament_used_grams.toFixed(1)," g"]}),ue.filaments.length>0&&r.jsx("span",{children:s("modelViewer.filamentCount",{count:ue.filaments.length})})]}),K&&r.jsxs("div",{className:`flex items-center gap-2 whitespace-nowrap ${ue?"ml-auto":""}`,children:[r.jsx("span",{children:s("modelViewer.pagination.pageOf",{current:P+1,total:Y})}),r.jsxs("div",{className:"flex items-center gap-1",children:[r.jsx("button",{type:"button",onClick:()=>T(ae=>Math.max(ae-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 pe=Math.max(0,P-Math.floor(2.5));const $=Math.min(Y,pe+5);$-pe<5&&(pe=Math.max(0,$-5));const R=Array.from({length:$-pe},(ne,be)=>pe+be);return r.jsxs(r.Fragment,{children:[pe>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"}),pe>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)),$T(Y-1),className:`px-2 py-1 rounded border text-xs ${P===Y-1?"border-bambu-green text-bambu-green":"border-bambu-dark-tertiary text-bambu-gray hover:text-white hover:border-bambu-gray"}`,children:Y})]})})(),r.jsx("button",{type:"button",onClick:()=>T(ae=>Math.min(ae+1,Y-1)),disabled:P>=Y-1,className:`px-2 py-1 rounded border text-xs ${P>=Y-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")})]})]})]})]})]}),he&&r.jsx("div",{role:"separator","aria-orientation":"horizontal",onMouseDown:ae=>{ae.preventDefault(),I(!0),L(!0)},className:`h-2 cursor-row-resize flex items-center justify-center ${q?"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 ${he?"min-h-0":""}`,children:r.jsx(oee,{url:c?re.getLibraryFileDownloadUrl(e):m.has_source?re.getSource3mfDownloadUrl(t):re.getArchiveDownload(t),fileType:n,buildVolume:m.build_volume,filamentColors:m.filament_colors,selectedPlateId:N,className:"w-full h-full"})})]}):d==="gcode"&&m?r.jsx(Hee,{gcodeUrl:c?re.getLibraryFileGcodeUrl(e):re.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 Yit=90;function Xit({onClose:t}){const{t:e}=vt(),a=ta(),{showToast:n}=na(),[i,s]=y.useState(Yit),[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=Qe({queryKey:["library-purge-preview",c,o],queryFn:()=>re.previewLibraryPurge(c,o),enabled:c>=1}),m=ot({mutationFn:()=>re.executeLibraryPurge(i,o),onSuccess:b=>{n(e("libraryPurge.toast.success",{count:b.moved_to_trash}),"success"),a.invalidateQueries({queryKey:["library-files"]}),a.invalidateQueries({queryKey:["library-folders"]}),a.invalidateQueries({queryKey:["library-trash"]}),a.invalidateQueries({queryKey:["library-trash-count"]}),t()},onError:b=>n(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(ea,{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($t,{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:ps(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(ba,{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(je,{variant:"secondary",onClick:t,disabled:m.isPending,children:e("common.cancel")}),r.jsx(je,{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 Zit({parentId:t,onClose:e,onSave:a,isLoading:n,t:i}){const[s,o]=y.useState(""),l=c=>{c.preventDefault(),a({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(je,{type:"button",variant:"secondary",onClick:e,children:i("common.cancel")}),r.jsx(je,{type:"submit",disabled:!s.trim()||n,children:n?r.jsx(pt,{className:"w-4 h-4 animate-spin"}):i("common.create")})]})]})]})})}function Jit({onClose:t,onSave:e,isLoading:a,t:n}){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(oC,{className:"w-5 h-5 text-bambu-green"}),n("fileManager.linkExternalFolder")]}),r.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:n("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:n("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:n("fileManager.externalFolderNamePlaceholder"),autoFocus:!0,required:!0})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:n("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:n("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:n("fileManager.readOnly")}),r.jsxs("span",{className:"text-xs text-bambu-gray",children:["(",n("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:n("fileManager.showHiddenFiles")})]})]}),r.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[r.jsx(je,{type:"button",variant:"secondary",onClick:t,children:n("common.cancel")}),r.jsx(je,{type:"submit",disabled:!i.trim()||!o.trim()||a,children:a?r.jsx(pt,{className:"w-4 h-4 animate-spin"}):n("fileManager.linkFolder")})]})]})]})})}function est({type:t,currentName:e,onClose:a,onSave:n,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&&n(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(je,{type:"button",variant:"secondary",onClick:a,children:s("common.cancel")}),r.jsx(je,{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 tst({folders:t,selectedFiles:e,currentFolderId:a,onClose:n,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===a,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===a?"opacity-50 cursor-not-allowed text-bambu-gray":"hover:bg-bambu-dark text-white"}`,style:{paddingLeft:`${12+m.depth*16}px`},children:[r.jsx(El,{className:"w-4 h-4"}),m.name,m.id===a&&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(je,{type:"button",variant:"secondary",onClick:n,children:o("common.cancel")}),r.jsx(je,{onClick:()=>i(l),disabled:s,children:s?r.jsx(pt,{className:"w-4 h-4 animate-spin"}):o("common.move")})]})]})]})})}function ast({folder:t,onClose:e,onLink:a,isLoading:n,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}=Qe({queryKey:["projects"],queryFn:()=>re.getProjects(),select:g=>[...g].sort((w,b)=>w.name.localeCompare(b.name))}),{data:u}=Qe({queryKey:["archives-for-link"],queryFn:()=>re.getArchives(void 0,void 0,100)}),m=()=>{a(s==="project"?{project_id:l,archive_id:0}:{project_id:0,archive_id:l})},p=()=>{a({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(Eh,{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($t,{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($Z,{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(io,{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(Ah,{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(je,{variant:"danger",onClick:p,disabled:n,children:[r.jsx(su,{className:"w-4 h-4 mr-2"}),i("fileManager.unlink")]}),r.jsxs("div",{className:`flex gap-2 ${f?"":"ml-auto"}`,children:[r.jsx(je,{variant:"secondary",onClick:e,children:i("common.cancel")}),r.jsx(je,{onClick:m,disabled:!l||n,children:n?r.jsx(pt,{className:"w-4 h-4 animate-spin"}):i("fileManager.link")})]})]})]})})}function cde({folder:t,selectedFolderId:e,onSelect:a,onDelete:n,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:()=>a(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(Hn,{className:`w-3.5 h-3.5 transition-transform ${m?"rotate-90":""}`})}):r.jsx("div",{className:"w-4.5"}),x?r.jsx(oC,{className:"w-4 h-4 text-purple-400 flex-shrink-0"}):r.jsx(El,{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(Eh,{className:"w-3 h-3"}),t.project_name?r.jsx($Z,{className:"w-3 h-3"}):r.jsx(io,{className:"w-3 h-3"})]}),x&&t.external_readonly&&r.jsx("span",{title:u("fileManager.readOnly"),children:r.jsx(oc,{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(Eh,{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(Nm,{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(yi,{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(Eh,{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")&&(n(t.id),g(!1))},disabled:!d("library:delete_all"),title:d("library:delete_all")?void 0:u("fileManager.noPermissionDeleteFolder"),children:[r.jsx(ea,{className:"w-3.5 h-3.5"}),u("common.delete")]})]})]})]})})]}),w&&m&&r.jsx("div",{children:t.children.map(S=>r.jsx(cde,{folder:S,selectedFolderId:e,onSelect:a,onDelete:n,onLink:i,onRename:s,depth:o+1,wrapNames:l,defaultExpanded:c,hasPermission:d,t:u},S.id))})]})}function Pw(t){const e=t.toLowerCase();return e.endsWith(".gcode")||e.endsWith(".gcode.3mf")}function dde(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 rst({file:t,isSelected:e,isMobile:a,onSelect:n,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:()=>n(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:`${re.getLibraryFileThumbnailUrl(t.id)}${f?(re.getLibraryFileThumbnailUrl(t.id).includes("?")?"&":"?")+`v=${f}`:""}`,alt:t.filename,className:"w-full h-full object-cover"}):r.jsx(Ah,{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:ps(t.file_size)}),t.print_time_seconds&&r.jsxs("span",{className:"flex items-center gap-1",children:[r.jsx(Za,{className:"w-3 h-3"}),hs(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(gr,{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(Xm,{className:"w-3 h-3"}),t.created_by_username]})]}),r.jsxs("div",{className:`absolute bottom-2 right-2 transition-opacity ${a?"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(Nm,{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&&Pw(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(gr,{className:"w-3.5 h-3.5"}),x("common.print")]}),o&&Pw(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(Za,{className:"w-3.5 h-3.5"}),x("fileManager.schedulePrint")]}),c&&d&&dde(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(du,{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(Mi,{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(Ur,{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(yi,{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(uu,{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(ea,{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 ${a?"opacity-100":"opacity-0 group-hover:opacity-100"}`}`,children:e&&r.jsx("div",{className:"w-2 h-2 bg-white rounded-sm"})})]})}function nst(){const{t}=vt(),e=ta(),{showToast:a}=na(),{hasPermission:n,hasAnyPermission:i,canModify:s,authEnabled:o}=dr(),[l]=lb(),c=Oi(),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),[j,F]=y.useState(!1),[k,M]=y.useState(null),[q,I]=y.useState(null),[O,L]=y.useState(null),[X,ee]=y.useState(null),[Q,le]=y.useState(null),[de,me]=y.useState(null),[Z,ce]=y.useState(null),[he,ue]=y.useState({}),[xe,H]=y.useState(null),[J,A]=y.useState(()=>localStorage.getItem("library-view-mode")||"grid"),[E,B]=y.useState(()=>localStorage.getItem("library-wrap-folders")==="true"),[W,z]=y.useState(()=>localStorage.getItem("library-collapse-folders")==="true"),[ie,U]=y.useState(()=>{const Ae=localStorage.getItem("library-sidebar-width");return Ae?parseInt(Ae,10):256}),[G,K]=y.useState(!1),Y=y.useRef(null);y.useEffect(()=>{if(!G)return;document.body.style.userSelect="none",document.body.style.cursor="col-resize";const Ae=Je=>{if(!Y.current)return;const De=Y.current.parentElement?.getBoundingClientRect();if(!De)return;const bt=Je.clientX-De.left,Ce=Math.min(500,Math.max(200,bt));U(Ce)},Ve=()=>{K(!1),document.body.style.userSelect="",document.body.style.cursor="",localStorage.setItem("library-sidebar-width",String(ie))};return document.addEventListener("mousemove",Ae),document.addEventListener("mouseup",Ve),()=>{document.removeEventListener("mousemove",Ae),document.removeEventListener("mouseup",Ve),document.body.style.userSelect="",document.body.style.cursor=""}},[G,ie]);const[se,oe]=y.useState(""),[fe,ae]=y.useState("all"),[pe,$]=y.useState(""),[R,ne]=y.useState(()=>localStorage.getItem("library-sort-field")||"name"),[be,ve]=y.useState(()=>localStorage.getItem("library-sort-direction")||"asc"),ke=vse();y.useEffect(()=>{const Ae=l.get("folder");if(Ae){const Ve=parseInt(Ae,10);p(Ve)}},[l]);const{data:ye}=Qe({queryKey:["settings"],queryFn:()=>re.getSettings()}),{data:ge,isLoading:Me}=Qe({queryKey:["library-folders"],queryFn:()=>re.getLibraryFolders()}),{data:Be}=Qe({queryKey:["library-trash-count"],queryFn:async()=>{try{return(await re.listLibraryTrash(1,0)).total}catch{return 0}},staleTime:3e4}),{data:Le,isLoading:Oe}=Qe({queryKey:["library-files",m],queryFn:()=>re.getLibraryFiles(m,!1)}),{data:Re}=Qe({queryKey:["library-stats"],queryFn:()=>re.getLibraryStats()}),{data:Ke}=Qe({queryKey:["users"],queryFn:()=>re.getUsers()}),Ue=y.useMemo(()=>{if(!Le)return[];const Ae=new Set(Le.map(Ve=>Ve.file_type));return Array.from(Ae).sort()},[Le]),lt=y.useMemo(()=>{if(!Le)return[];let Ae=[...Le];if(se.trim()){const Ve=se.toLowerCase();Ae=Ae.filter(Je=>Je.filename.toLowerCase().includes(Ve)||Je.print_name&&Je.print_name.toLowerCase().includes(Ve))}if(fe!=="all"&&(Ae=Ae.filter(Ve=>Ve.file_type===fe)),pe.trim()){const Ve=pe.toLowerCase();Ae=Ae.filter(Je=>Je.created_by_username&&Je.created_by_username.toLowerCase().includes(Ve))}return Ae.sort((Ve,Je)=>{let De=0;switch(R){case"name":De=(Ve.print_name||Ve.filename).localeCompare(Je.print_name||Je.filename);break;case"date":De=(Qa(Ve.created_at)?.getTime()??0)-(Qa(Je.created_at)?.getTime()??0);break;case"size":De=Ve.file_size-Je.file_size;break;case"type":De=Ve.file_type.localeCompare(Je.file_type);break;case"prints":De=Ve.print_count-Je.print_count;break}return be==="asc"?De:-De}),Ae},[Le,se,fe,pe,R,be]),Ee=y.useMemo(()=>{if(!Re||!ye)return!1;const Ae=(ye.library_disk_warning_gb||5)*1024*1024*1024;return Re.disk_free_bytesre.createLibraryFolder(Ae),onSuccess:()=>{e.invalidateQueries({queryKey:["library-folders"]}),b(!1),a(t("fileManager.toast.folderCreated"),"success")},onError:Ae=>a(Ae.message,"error")}),Ne=ot({mutationFn:async Ae=>{const Ve=await re.createExternalFolder(Ae);return await re.scanExternalFolder(Ve.id),Ve},onSuccess:Ae=>{e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-stats"]}),S(!1),p(Ae.id),a(t("fileManager.toast.externalFolderLinked"),"success")},onError:Ae=>a(Ae.message,"error")}),Ze=ot({mutationFn:Ae=>re.scanExternalFolder(Ae),onSuccess:Ae=>{e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-stats"]}),a(t("fileManager.toast.folderScanned",{added:Ae.added,removed:Ae.removed}),"success")},onError:Ae=>a(Ae.message,"error")}),Ye=ot({mutationFn:Ae=>re.deleteLibraryFolder(Ae),onSuccess:()=>{e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-stats"]}),m===q?.id&&p(null),I(null),a(t("fileManager.toast.folderDeleted"),"success")},onError:Ae=>{I(null),a(Ae.message,"error")}}),Te=ot({mutationFn:Ae=>re.deleteLibraryFile(Ae),onSuccess:()=>{e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-stats"]}),e.invalidateQueries({queryKey:["library-trash-count"]}),g(Ae=>Ae.filter(Ve=>Ve!==q?.id)),I(null),a(t("fileManager.toast.fileDeleted"),"success")},onError:Ae=>{I(null),a(Ae.message,"error")}}),Fe=ot({mutationFn:Ae=>re.bulkDeleteLibrary(Ae,[]),onSuccess:(Ae,Ve)=>{e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-stats"]}),e.invalidateQueries({queryKey:["library-trash-count"]}),a(t("fileManager.toast.filesDeleted",{count:Ve.length}),"success"),g([]),I(null)},onError:Ae=>{I(null),a(Ae.message,"error")}}),et=ot({mutationFn:({fileIds:Ae,folderId:Ve})=>re.moveLibraryFiles(Ae,Ve),onSuccess:()=>{e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-folders"]}),g([]),C(!1),a(t("fileManager.toast.filesMoved"),"success")},onError:Ae=>a(Ae.message,"error")}),We=ot({mutationFn:({id:Ae,data:Ve})=>re.updateLibraryFolder(Ae,Ve),onSuccess:(Ae,Ve)=>{e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["project-folders"]}),e.invalidateQueries({queryKey:["archive-folders"]}),M(null);const Je=Ve.data.project_id===0&&Ve.data.archive_id===0;a(t(Je?"fileManager.toast.folderUnlinked":"fileManager.toast.folderLinked"),"success")},onError:Ae=>a(Ae.message,"error")}),Pe=ot({mutationFn:({id:Ae,filename:Ve})=>re.updateLibraryFile(Ae,{filename:Ve}),onSuccess:()=>{e.invalidateQueries({queryKey:["library-files"]}),ce(null),a(t("fileManager.toast.fileRenamed"),"success")},onError:Ae=>{ce(null),a(Ae.message,"error")}}),at=ot({mutationFn:({id:Ae,name:Ve})=>re.updateLibraryFolder(Ae,{name:Ve}),onSuccess:()=>{e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-files"]}),ce(null),a(t("fileManager.toast.folderRenamed"),"success")},onError:Ae=>{ce(null),a(Ae.message,"error")}}),nt=ot({mutationFn:()=>re.batchGenerateStlThumbnails({all_missing:!0}),onSuccess:Ae=>{if(e.invalidateQueries({queryKey:["library-files"]}),Ae.succeeded>0){const Ve=Date.now(),Je={};Ae.results.forEach(De=>{De.success&&(Je[De.file_id]=Ve)}),ue(De=>({...De,...Je}))}Ae.succeeded>0&&Ae.failed===0?a(t("fileManager.toast.thumbnailsGenerated",{count:Ae.succeeded}),"success"):Ae.succeeded>0&&Ae.failed>0?a(t("fileManager.toast.thumbnailsGeneratedPartial",{succeeded:Ae.succeeded,failed:Ae.failed}),"success"):Ae.processed===0?a(t("fileManager.toast.noStlMissingThumbnails"),"info"):a(t("fileManager.toast.failedToGenerateThumbnails",{error:Ae.results[0]?.error||"Unknown error"}),"error")},onError:Ae=>a(Ae.message,"error")}),At=ot({mutationFn:Ae=>re.batchGenerateStlThumbnails({file_ids:[Ae]}),onSuccess:Ae=>{if(e.invalidateQueries({queryKey:["library-files"]}),Ae.succeeded>0){const Ve=Ae.results[0]?.file_id;Ve&&ue(Je=>({...Je,[Ve]:Date.now()})),a(t("fileManager.toast.thumbnailGenerated"),"success")}else a(t("fileManager.toast.failedToGenerateThumbnail",{error:Ae.results[0]?.error||"Unknown error"}),"error")},onError:Ae=>a(Ae.message,"error")}),Bt=y.useCallback(Ae=>{const Ve=Ae.toLowerCase();return Ve.endsWith(".gcode")||Ve.includes(".gcode.")},[]),gt=y.useMemo(()=>Le?Le.filter(Ae=>f.includes(Ae.id)&&Bt(Ae.filename)):[],[Le,f,Bt]),Qt=y.useCallback(Ae=>{g(Ve=>Ve.includes(Ae)?Ve.filter(Je=>Je!==Ae):[...Ve,Ae])},[]),Xt=y.useCallback(()=>{lt.length>0&&g(lt.map(Ae=>Ae.id))},[lt]),ia=y.useCallback(()=>{g([])},[]),da=()=>{e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-stats"]})},ut=Ae=>{re.downloadLibraryFile(Ae).catch(Ve=>{console.error("Library file download failed:",Ve)})},_t=()=>{q&&(q.type==="file"?Te.mutate(q.id):q.type==="folder"?Ye.mutate(q.id):q.type==="bulk"&&Fe.mutate(f))},Ct=Ye.isPending||Te.isPending||Fe.isPending,dt=Ae=>{A(Ae),localStorage.setItem("library-view-mode",Ae)},Nt=Me||Oe,Ie=y.useMemo(()=>{if(!m||!ge)return null;const Ae=Ve=>{for(const Je of Ve){if(Je.id===m)return Je;const De=Ae(Je.children);if(De)return De}return null};return Ae(ge)},[m,ge]);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(El,{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:()=>dt("grid"),className:`p-1.5 rounded transition-colors ${J==="grid"?"bg-bambu-dark-secondary text-white":"text-bambu-gray hover:text-white"}`,title:t("fileManager.gridView"),children:r.jsx(DS,{className:"w-4 h-4"})}),r.jsx("button",{onClick:()=>dt("list"),className:`p-1.5 rounded transition-colors ${J==="list"?"bg-bambu-dark-secondary text-white":"text-bambu-gray hover:text-white"}`,title:t("fileManager.listView"),children:r.jsx(FS,{className:"w-4 h-4"})})]}),r.jsxs(je,{variant:"secondary",onClick:()=>nt.mutate(),disabled:nt.isPending||!i("library:update_own","library:update_all"),title:i("library:update_own","library:update_all")?t("fileManager.generateThumbnailsForMissing"):t("fileManager.noPermissionGenerateThumbnail"),children:[nt.isPending?r.jsx(pt,{className:"w-4 h-4 mr-2 animate-spin"}):r.jsx(uu,{className:"w-4 h-4 mr-2"}),t("fileManager.generateThumbnails")]}),r.jsxs(je,{variant:"secondary",onClick:()=>S(!0),disabled:!n("library:upload"),title:n("library:upload")?t("fileManager.linkExternalFolder"):t("fileManager.noPermissionCreateFolder"),children:[r.jsx(oC,{className:"w-4 h-4 mr-2"}),t("fileManager.linkExternal")]}),r.jsxs(je,{variant:"secondary",onClick:()=>b(!0),disabled:!n("library:upload"),title:n("library:upload")?void 0:t("fileManager.noPermissionCreateFolder"),children:[r.jsx(Ube,{className:"w-4 h-4 mr-2"}),t("fileManager.newFolder")]}),n("library:purge")&&r.jsxs(je,{variant:"secondary",onClick:()=>F(!0),title:t("libraryPurge.headerTooltip"),children:[r.jsx(ea,{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(ea,{className:"w-4 h-4 mr-2"}),t("libraryTrash.headerButton"),typeof Be=="number"&&Be>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:Be})]}),r.jsxs(je,{onClick:()=>T(!0),disabled:!n("library:upload"),title:n("library:upload")?void 0:t("fileManager.noPermissionUpload"),children:[r.jsx(Sn,{className:"w-4 h-4 mr-2"}),t("common.upload")]})]})]}),Ee&&Re&&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(ba,{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:ps(Re.disk_free_bytes),total:ps(Re.disk_total_bytes),threshold:ye.library_disk_warning_gb})})]})]}),Re&&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(jT,{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:Re.total_files})]}),r.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[r.jsx(El,{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:Re.total_folders})]}),r.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[r.jsx(ub,{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:ps(Re.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 ${Ee?"text-amber-500":"text-white"}`,children:ps(Re.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:Ae=>p(Ae.target.value?parseInt(Ae.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")]}),ge&&(()=>{const Ae=(Ve,Je=0)=>{const De=[];for(const bt of Ve)De.push({id:bt.id,name:bt.name,fileCount:bt.file_count,depth:Je}),bt.children.length>0&&De.push(...Ae(bt.children,Je+1));return De};return Ae(ge).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:Y,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:`${ie}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:Ae=>{Ae.preventDefault(),K(!0)},onDoubleClick:()=>{U(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 Ae=!W;z(Ae),localStorage.setItem("library-collapse-folders",String(Ae))},className:`text-xs px-1.5 py-0.5 rounded transition-colors ${W?"bg-bambu-green/20 text-bambu-green":"text-bambu-gray hover:text-white hover:bg-bambu-dark"}`,title:t(W?"fileManager.expandFoldersByDefault":"fileManager.collapseFoldersByDefault"),children:t("fileManager.collapse")}),r.jsx("button",{onClick:()=>{const Ae=!E;B(Ae),localStorage.setItem("library-wrap-folders",String(Ae))},className:`text-xs px-1.5 py-0.5 rounded transition-colors ${E?"bg-bambu-green/20 text-bambu-green":"text-bambu-gray hover:text-white hover:bg-bambu-dark"}`,title:t(E?"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(Ah,{className:"w-4 h-4"}),r.jsx("span",{className:"text-sm",children:t("fileManager.allFiles")})]}),ge?.map(Ae=>r.jsx(cde,{folder:Ae,selectedFolderId:m,onSelect:p,onDelete:Ve=>I({type:"folder",id:Ve}),onLink:M,onRename:Ve=>ce({type:"folder",id:Ve.id,name:Ve.name}),wrapNames:E,defaultExpanded:!W,hasPermission:n,t},`${Ae.id}-${W?"c":"e"}`))]})]}),r.jsxs("div",{className:"flex-1 flex flex-col min-w-0 min-h-0",children:[Ie?.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(oC,{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")}),Ie.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(oc,{className:"w-3 h-3"}),t("fileManager.readOnly")]})]}),r.jsx("p",{className:"text-xs text-bambu-gray truncate font-mono",title:Ie.external_path||"",children:Ie.external_path})]}),r.jsxs(je,{variant:"secondary",size:"sm",onClick:()=>m&&Ze.mutate(m),disabled:Ze.isPending,title:t("fileManager.scanFolder"),children:[Ze.isPending?r.jsx(pt,{className:"w-4 h-4 animate-spin"}):r.jsx(Xa,{className:"w-4 h-4"}),r.jsx("span",{className:"ml-1.5",children:t("fileManager.scanFolder")})]})]}),Le&&Le.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(fr,{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:se,onChange:Ae=>oe(Ae.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(jS,{className:"w-4 h-4 text-bambu-gray hidden sm:block"}),r.jsxs("select",{value:fe,onChange:Ae=>ae(Ae.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")}),Ue.map(Ae=>r.jsx("option",{value:Ae,children:Ae.toUpperCase()},Ae))]})]}),o&&r.jsxs("div",{className:"relative",children:[r.jsx("input",{type:"text",placeholder:t("fileManager.filterByUser",{defaultValue:"Filter by user"}),value:pe,onChange:Ae=>$(Ae.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 ${pe?"pr-7":""}`,style:pe?{WebkitAppearance:"none",MozAppearance:"textfield"}:void 0}),pe&&r.jsx("button",{onClick:()=>$(""),className:"absolute right-2 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white z-10",children:r.jsx($t,{className:"w-3 h-3"})}),r.jsx("datalist",{id:"usernames-list",children:Ke?.map(Ae=>r.jsx("option",{value:Ae.username},Ae.id))})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsxs("select",{value:R,onChange:Ae=>{const Ve=Ae.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(Ae=>{const Ve=Ae==="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(be==="asc"?"fileManager.ascending":"fileManager.descending"),children:be==="asc"?r.jsx($fe,{className:"w-4 h-4 text-white"}):r.jsx(Ife,{className:"w-4 h-4 text-white"})})]}),(se||fe!=="all"||pe)&&r.jsx("span",{className:"text-sm text-bambu-gray hidden sm:inline",children:t("fileManager.resultsCount",{showing:lt.length,total:Le.length})})]}),lt.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===lt.length&&f.length>0?r.jsxs(je,{variant:"secondary",size:"sm",onClick:ia,children:[r.jsx(lo,{className:"w-4 h-4 sm:mr-1"}),r.jsx("span",{className:"hidden sm:inline",children:t("fileManager.deselectAll")})]}):r.jsxs(je,{variant:"secondary",size:"sm",onClick:Xt,children:[r.jsx(ws,{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:[gt.length===1&&r.jsxs(je,{variant:"primary",size:"sm",onClick:()=>ee(gt[0]),disabled:!n("printers:control"),title:n("printers:control")?void 0:t("fileManager.noPermissionPrint"),children:[r.jsx(ys,{className:"w-4 h-4 sm:mr-1"}),r.jsx("span",{className:"hidden sm:inline",children:t("common.print")})]}),gt.length===1&&r.jsxs(je,{variant:"secondary",size:"sm",onClick:()=>le(gt[0]),disabled:!n("queue:create"),title:n("queue:create")?void 0:t("fileManager.noPermissionAddToQueue"),children:[r.jsx(Za,{className:"w-4 h-4 sm:mr-1"}),r.jsx("span",{className:"hidden sm:inline",children:t("fileManager.schedulePrint")})]}),r.jsxs(je,{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(aye,{className:"w-4 h-4 sm:mr-1"}),r.jsx("span",{className:"hidden sm:inline",children:t("common.move")})]}),r.jsxs(je,{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(ea,{className:"w-4 h-4 sm:mr-1"}),r.jsx("span",{className:"hidden sm:inline",children:t("common.delete")})]}),r.jsxs(je,{variant:"secondary",size:"sm",onClick:ia,children:[r.jsx($t,{className:"w-4 h-4 sm:mr-1"}),r.jsx("span",{className:"hidden sm:inline",children:t("common.clear")})]})]})]})]}),Nt?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")})]})}):Le?.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(Ah,{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(je,{onClick:()=>T(!0),disabled:!n("library:upload"),title:n("library:upload")?void 0:t("fileManager.noPermissionUpload"),children:[r.jsx(er,{className:"w-4 h-4 mr-2"}),t("fileManager.uploadFiles")]})]}):lt.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(fr,{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(je,{variant:"secondary",onClick:()=>{oe(""),ae("all")},children:t("fileManager.clearFilters")})]}):J==="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:lt.map(Ae=>r.jsx(rst,{file:Ae,isSelected:f.includes(Ae.id),isMobile:ke,t,onSelect:Qt,onDelete:Ve=>I({type:"file",id:Ve}),onDownload:ut,onAddToQueue:Ve=>{const Je=Le?.find(De=>De.id===Ve);Je&&le(Je)},onPrint:L,onSlice:me,useSlicerApi:ye?.use_slicer_api??!1,onPreview3d:Ve=>{Pw(Ve.filename)?c(`/gcode-viewer?library_file=${Ve.id}`):H(Ve)},onRename:Ve=>ce({type:"file",id:Ve.id,name:Ve.filename}),onGenerateThumbnail:Ve=>At.mutate(Ve.id),thumbnailVersion:he[Ae.id],hasPermission:n,canModify:s,authEnabled:o},Ae.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",{})]}),lt.map(Ae=>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(Ae.id)?"bg-bambu-green/10":""}`,onClick:()=>Qt(Ae.id),children:[r.jsx("div",{className:`w-5 h-5 rounded border-2 flex items-center justify-center ${f.includes(Ae.id)?"bg-bambu-green border-bambu-green":"border-bambu-gray/50"}`,children:f.includes(Ae.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:Ae.thumbnail_path?r.jsx("img",{src:`${re.getLibraryFileThumbnailUrl(Ae.id)}${he[Ae.id]?(re.getLibraryFileThumbnailUrl(Ae.id).includes("?")?"&":"?")+`v=${he[Ae.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(Ah,{className:"w-5 h-5 text-bambu-gray/50"})})}),Ae.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:`${re.getLibraryFileThumbnailUrl(Ae.id)}${he[Ae.id]?(re.getLibraryFileThumbnailUrl(Ae.id).includes("?")?"&":"?")+`v=${he[Ae.id]}`:""}`,alt:Ae.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:Ae.print_name||Ae.filename})})]}),o&&r.jsx("div",{className:"text-sm text-bambu-gray flex items-center gap-1",children:Ae.created_by_username?r.jsxs(r.Fragment,{children:[r.jsx(Xm,{className:"w-3 h-3"}),r.jsx("span",{className:"truncate",children:Ae.created_by_username})]}):"-"}),r.jsx("div",{children:r.jsx("span",{className:`text-xs px-1.5 py-0.5 rounded font-medium ${Ae.file_type==="3mf"?"bg-bambu-green/20 text-bambu-green":Ae.file_type==="gcode"?"bg-blue-500/20 text-blue-400":Ae.file_type==="stl"?"bg-purple-500/20 text-purple-400":"bg-bambu-gray/20 text-bambu-gray"}`,children:Ae.file_type.toUpperCase()})}),r.jsx("div",{className:"text-sm text-bambu-gray",children:ps(Ae.file_size)}),r.jsx("div",{className:"text-sm text-bambu-gray",children:Ae.print_count>0?`${Ae.print_count}x`:"-"}),r.jsxs("div",{className:"flex items-center gap-1",onClick:Ve=>Ve.stopPropagation(),children:[Pw(Ae.filename)&&r.jsxs(r.Fragment,{children:[r.jsx("button",{onClick:()=>n("printers:control")&&L(Ae),className:`p-1.5 rounded transition-colors ${n("printers:control")?"hover:bg-bambu-dark text-bambu-gray hover:text-bambu-green":"text-bambu-gray/50 cursor-not-allowed"}`,title:n("printers:control")?t("common.print"):t("fileManager.noPermissionPrint"),disabled:!n("printers:control"),children:r.jsx(gr,{className:"w-4 h-4"})}),r.jsx("button",{onClick:()=>{n("queue:create")&&le(Ae)},className:`p-1.5 rounded transition-colors ${n("queue:create")?"hover:bg-bambu-dark text-bambu-gray hover:text-white":"text-bambu-gray/50 cursor-not-allowed"}`,title:n("queue:create")?t("fileManager.schedulePrint"):t("fileManager.noPermissionAddToQueue"),disabled:!n("queue:create"),children:r.jsx(Za,{className:"w-4 h-4"})})]}),(ye?.use_slicer_api??!1)&&dde(Ae.filename)&&r.jsx("button",{onClick:()=>n("library:upload")&&me(Ae),className:`p-1.5 rounded transition-colors ${n("library:upload")?"hover:bg-bambu-dark text-bambu-gray hover:text-bambu-green":"text-bambu-gray/50 cursor-not-allowed"}`,title:n("library:upload")?t("slice.action"):t("fileManager.noPermissionSlice"),disabled:!n("library:upload"),children:r.jsx(du,{className:"w-4 h-4"})}),(Ae.file_type==="3mf"||Ae.file_type==="gcode"||Ae.file_type==="stl")&&r.jsx("button",{onClick:()=>{n("library:read")&&(Pw(Ae.filename)?c(`/gcode-viewer?library_file=${Ae.id}`):H(Ae))},className:`p-1.5 rounded transition-colors ${n("library:read")?"hover:bg-bambu-dark text-bambu-gray hover:text-bambu-green":"text-bambu-gray/50 cursor-not-allowed"}`,title:n("library:read")?"3D Preview":"You do not have permission to preview files",disabled:!n("library:read"),children:r.jsx(Mi,{className:"w-4 h-4"})}),r.jsx("button",{onClick:()=>n("library:read")&&ut(Ae.id),className:`p-1.5 rounded transition-colors ${n("library:read")?"hover:bg-bambu-dark text-bambu-gray hover:text-white":"text-bambu-gray/50 cursor-not-allowed"}`,title:n("library:read")?t("common.download"):t("fileManager.noPermissionDownload"),disabled:!n("library:read"),children:r.jsx(Ur,{className:"w-4 h-4"})}),r.jsx("button",{onClick:()=>s("library","update",Ae.created_by_id)&&ce({type:"file",id:Ae.id,name:Ae.filename}),className:`p-1.5 rounded transition-colors ${s("library","update",Ae.created_by_id)?"hover:bg-bambu-dark text-bambu-gray hover:text-white":"text-bambu-gray/50 cursor-not-allowed"}`,title:s("library","update",Ae.created_by_id)?t("common.rename"):t("fileManager.noPermissionRenameFile"),disabled:!s("library","update",Ae.created_by_id),children:r.jsx(yi,{className:"w-4 h-4"})}),Ae.file_type==="stl"&&r.jsx("button",{onClick:()=>s("library","update",Ae.created_by_id)&&At.mutate(Ae.id),className:`p-1.5 rounded transition-colors ${s("library","update",Ae.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",Ae.created_by_id)?t("fileManager.generateThumbnail"):t("fileManager.noPermissionGenerateThumbnail"),disabled:At.isPending||!s("library","update",Ae.created_by_id),children:r.jsx(uu,{className:"w-4 h-4"})}),r.jsx("button",{onClick:()=>s("library","delete",Ae.created_by_id)&&I({type:"file",id:Ae.id}),className:`p-1.5 rounded transition-colors ${s("library","delete",Ae.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",Ae.created_by_id)?t("common.delete"):t("fileManager.noPermissionDeleteFile"),disabled:!s("library","delete",Ae.created_by_id),children:r.jsx(ea,{className:"w-4 h-4"})})]})]},Ae.id))]})})]})]}),w&&r.jsx(Zit,{parentId:m,onClose:()=>b(!1),onSave:Ae=>st.mutate(Ae),isLoading:st.isPending,t}),x&&r.jsx(Jit,{onClose:()=>S(!1),onSave:Ae=>Ne.mutate(Ae),isLoading:Ne.isPending,t}),N&&ge&&r.jsx(tst,{folders:ge,selectedFiles:f,currentFolderId:m,onClose:()=>C(!1),onMove:Ae=>et.mutate({fileIds:f,folderId:Ae}),isLoading:et.isPending,t}),P&&r.jsx(lse,{folderId:m,onClose:()=>T(!1),onUploadComplete:da}),j&&r.jsx(Xit,{onClose:()=>F(!1)}),k&&r.jsx(ast,{folder:k,onClose:()=>M(null),onLink:Ae=>We.mutate({id:k.id,data:Ae}),isLoading:We.isPending,t}),q&&r.jsx(wa,{title:q.type==="folder"?t("fileManager.deleteFolder"):q.type==="bulk"?t("fileManager.deleteFilesCount",{count:q.count}):t("fileManager.deleteFile"),message:q.type==="folder"?t("fileManager.deleteFolderConfirm"):q.type==="bulk"?t("fileManager.deleteFilesConfirm",{count:q.count}):t("fileManager.deleteFileConfirm"),confirmText:t("common.delete"),variant:"danger",isLoading:Ct,loadingText:t("fileManager.deleting"),onConfirm:_t,onCancel:()=>I(null)}),O&&r.jsx(wc,{mode:"reprint",libraryFileId:O.id,archiveName:O.print_name||O.filename,onClose:()=>L(null),onSuccess:()=>{L(null),e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["archives"]})}}),X&&r.jsx(wc,{mode:"reprint",libraryFileId:X.id,archiveName:X.print_name||X.filename,onClose:()=>ee(null),onSuccess:()=>{ee(null),g([]),e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["archives"]})}}),Q&&r.jsx(wc,{mode:"add-to-queue",libraryFileId:Q.id,archiveName:Q.print_name||Q.filename,onClose:()=>le(null),onSuccess:()=>{le(null),g([]),e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["queue"]}),e.invalidateQueries({queryKey:["archives"]})}}),de&&r.jsx($A,{source:{kind:"libraryFile",id:de.id,filename:de.filename},onClose:()=>me(null)}),xe&&r.jsx(Qit,{libraryFileId:xe.id,title:xe.print_name||xe.filename,fileType:xe.file_type,onClose:()=>H(null)}),Z&&r.jsx(est,{type:Z.type,currentName:Z.name,onClose:()=>ce(null),onSave:Ae=>{Z.type==="file"?Pe.mutate({id:Z.id,filename:Ae}):at.mutate({id:Z.id,name:Ae})},isLoading:Pe.isPending||at.isPending,t})]})}function ist(t){const e=Qa(t);if(!e)return"";const a=Math.ceil((e.getTime()-Date.now())/(1e3*60*60*24));return a<=0?"any moment":a===1?"1 day":`${a} days`}function MX(t){const e=Qa(t);return e?e.toLocaleString():t}function sst(){const{t}=vt(),e=Oi(),a=ta(),{showToast:n}=na(),{hasPermission:i,authEnabled:s}=dr(),[o,l]=y.useState(null),[c,d]=y.useState(new Set),u=!s||i("library:purge"),m=Qe({queryKey:["library-trash"],queryFn:()=>re.listLibraryTrash(200,0)}),p=Qe({queryKey:["library-trash-settings"],queryFn:()=>re.getLibraryTrashSettings(),enabled:u}),[f,g]=y.useState(null);y.useEffect(()=>{p.data&&f===null&&g(p.data.retention_days)},[p.data,f]);const w=ot({mutationFn:O=>{const L=p.data;return re.updateLibraryTrashSettings({retention_days:O,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:O=>{n(t("libraryTrash.toast.retentionSaved",{days:O.retention_days}),"success"),a.invalidateQueries({queryKey:["library-trash-settings"]}),a.invalidateQueries({queryKey:["library-trash"]})},onError:O=>n(O.message||t("libraryTrash.toast.retentionFailed"),"error")}),b=ot({mutationFn:O=>re.restoreLibraryTrash(O),onSuccess:()=>{n(t("libraryTrash.toast.restored"),"success"),a.invalidateQueries({queryKey:["library-trash"]}),a.invalidateQueries({queryKey:["library-trash-count"]}),a.invalidateQueries({queryKey:["library-files"]}),a.invalidateQueries({queryKey:["library-folders"]})},onError:O=>n(O.message||t("libraryTrash.toast.restoreFailed"),"error")}),x=ot({mutationFn:O=>re.hardDeleteLibraryTrash(O),onSuccess:()=>{n(t("libraryTrash.toast.purged"),"success"),a.invalidateQueries({queryKey:["library-trash"]}),a.invalidateQueries({queryKey:["library-trash-count"]})},onError:O=>n(O.message||t("libraryTrash.toast.purgeFailed"),"error")}),S=ot({mutationFn:()=>re.emptyLibraryTrash(),onSuccess:O=>{n(t("libraryTrash.toast.emptied",{count:O.deleted}),"success"),a.invalidateQueries({queryKey:["library-trash"]}),a.invalidateQueries({queryKey:["library-trash-count"]})},onError:O=>n(O.message||t("libraryTrash.toast.emptyFailed"),"error")}),N=ot({mutationFn:O=>Promise.all(O.map(L=>re.restoreLibraryTrash(L))),onSuccess:(O,L)=>{n(t("libraryTrash.toast.bulkRestored",{count:L.length}),"success"),d(new Set),a.invalidateQueries({queryKey:["library-trash"]}),a.invalidateQueries({queryKey:["library-trash-count"]}),a.invalidateQueries({queryKey:["library-files"]}),a.invalidateQueries({queryKey:["library-folders"]})},onError:O=>n(O.message||t("libraryTrash.toast.restoreFailed"),"error")}),C=ot({mutationFn:O=>Promise.all(O.map(L=>re.hardDeleteLibraryTrash(L))),onSuccess:(O,L)=>{n(t("libraryTrash.toast.bulkPurged",{count:L.length}),"success"),d(new Set),a.invalidateQueries({queryKey:["library-trash"]}),a.invalidateQueries({queryKey:["library-trash-count"]})},onError:O=>n(O.message||t("libraryTrash.toast.purgeFailed"),"error")}),P=y.useMemo(()=>m.data?.items??[],[m.data?.items]),T=m.data?.retention_days??30,j=y.useMemo(()=>P.reduce((O,L)=>O+L.file_size,0),[P]),F=P.length>0&&P.every(O=>c.has(O.id)),k=c.size>0&&!F,M=O=>{d(L=>{const X=new Set(L);return X.has(O)?X.delete(O):X.add(O),X})},q=()=>{d(O=>O.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(PT,{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(je,{variant:"secondary",onClick:()=>l({type:"empty"}),className:"text-red-600 dark:text-red-400",children:[r.jsx(ea,{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:O=>g(Math.max(1,Math.min(365,parseInt(O.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(je,{variant:"secondary",onClick:()=>f!=null&&w.mutate(f),disabled:w.isPending||f==null||f===p.data.retention_days,className:"ml-auto",children:[r.jsx(fs,{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:ps(j)})}),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(je,{variant:"secondary",onClick:()=>N.mutate(Array.from(c)),disabled:N.isPending,children:[r.jsx(vs,{className:"w-4 h-4 mr-1"}),t("libraryTrash.bulkRestore")]}),r.jsxs(je,{variant:"secondary",onClick:()=>l({type:"bulkDelete",count:c.size}),disabled:C.isPending,className:"text-red-600 dark:text-red-400",children:[r.jsx(ea,{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:O=>{O&&(O.indeterminate=k)},onChange:q,"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(O=>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(O.id),onChange:()=>M(O.id),"aria-label":t("libraryTrash.selectOne",{filename:O.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:O.filename,children:O.filename}),r.jsx("td",{className:"px-3 py-2 text-gray-600 dark:text-gray-400",children:O.folder_name??"—"}),r.jsx("td",{className:"px-3 py-2 text-right text-gray-600 dark:text-gray-400 tabular-nums whitespace-nowrap",children:ps(O.file_size)}),r.jsx("td",{className:"px-3 py-2 text-gray-600 dark:text-gray-400 whitespace-nowrap",children:MX(O.deleted_at)}),r.jsx("td",{className:"px-3 py-2 text-gray-600 dark:text-gray-400 whitespace-nowrap",children:r.jsx("span",{title:MX(O.auto_purge_at),children:t("libraryTrash.autoPurgeIn",{when:ist(O.auto_purge_at)})})}),u&&r.jsx("td",{className:"px-3 py-2 text-gray-600 dark:text-gray-400",children:O.created_by_username??"—"}),r.jsxs("td",{className:"px-3 py-2 text-right whitespace-nowrap",children:[r.jsxs("button",{onClick:()=>b.mutate(O.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(vs,{className:"w-3.5 h-3.5"}),t("libraryTrash.restore")]}),r.jsxs("button",{onClick:()=>l({type:"delete",id:O.id,filename:O.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(ea,{className:"w-3.5 h-3.5"}),t("libraryTrash.purgeNow")]})]})]},O.id))})]})})]}),o&&r.jsx(wa,{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(je,{variant:"secondary",onClick:()=>e("/files"),className:"ml-3",children:t("libraryTrash.backToFiles")})]})]})}function ost(t,e){const a=`token=${encodeURIComponent(e)}`;let n=0;return t.querySelectorAll('img[src*="/api/v1/"], video[src*="/api/v1/"]').forEach(i=>{const s=i.getAttribute("src")||"";if(s.includes(a))return;const o=s.replace(/([?&])token=[^&]*(&|$)/,(c,d,u)=>u==="&"?d:""),l=o.includes("?")?"&":"?";i.src=`${o}${l}${a}`,n+=1}),n}function ude(){const{authEnabled:t,user:e}=dr(),a=ta(),n=y.useRef(!1),{data:i}=Qe({queryKey:["camera-stream-token",e?.id??null],queryFn:()=>re.getCameraStreamToken(),enabled:t?!!e:!0,staleTime:3e3*1e3,refetchInterval:3e3*1e3});y.useEffect(()=>{const s=i?.token??null;return _8(s),s&&ost(document,s),()=>_8(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=oJ();!d||!c.includes(`token=${encodeURIComponent(d)}`)||n.current||(n.current=!0,a.invalidateQueries({queryKey:["camera-stream-token"]}),setTimeout(()=>{n.current=!1},5e3))};return document.addEventListener("error",s,!0),()=>document.removeEventListener("error",s,!0)},[t,a])}const bN=5,lst=2e3,cst=3e4,dst=5e3;function ust(){const{t}=vt(),e=ta(),{showToast:a}=na(),{hasPermission:n,authEnabled:i,user:s}=dr(),{printerId:o}=TS(),l=parseInt(o||"0",10),[c]=lb(),d=parseInt(c.get("fps")||"15",10),u=Math.min(Math.max(isNaN(d)?15:d,1),30);ude();const{data:m}=Qe({queryKey:["camera-stream-token",s?.id??null],queryFn:()=>re.getCameraStreamToken(),enabled:i?!!s:!0,staleTime:3e3*1e3}),p=m?.token??oJ(),[f,g]=y.useState("stream"),[w,b]=y.useState(!1),[x,S]=y.useState(!1),[N,C]=y.useState(!1),[P,T]=y.useState(!0),[j,F]=y.useState(Date.now()),[k,M]=y.useState(!1),[q,I]=y.useState(!1),[O,L]=y.useState(0),[X,ee]=y.useState(!1),[Q,le]=y.useState(0),[de,me]=y.useState(1),[Z,ce]=y.useState({x:0,y:0}),[he,ue]=y.useState(!1),[xe,H]=y.useState({x:0,y:0}),[J,A]=y.useState(null),[E,B]=y.useState(null),W=y.useRef(null),z=y.useRef(null),ie=y.useRef(null),U=y.useRef(null),G=y.useRef(null),{data:K}=Qe({queryKey:["printer",l],queryFn:()=>re.getPrinter(l),enabled:l>0}),{data:Y}=Qe({queryKey:["printerStatus",l],queryFn:()=>re.getPrinterStatus(l),refetchInterval:3e4,enabled:l>0}),se=ot({mutationFn:Fe=>re.setChamberLight(l,Fe),onMutate:async Fe=>{await e.cancelQueries({queryKey:["printerStatus",l]});const et=e.getQueryData(["printerStatus",l]);return e.setQueryData(["printerStatus",l],We=>({...We,chamber_light:Fe})),{previousStatus:et}},onSuccess:(Fe,et)=>{a(`Chamber light ${et?"on":"off"}`)},onError:(Fe,et,We)=>{We?.previousStatus&&e.setQueryData(["printerStatus",l],We.previousStatus),a(Fe.message||t("printers.toast.failedToControlChamberLight"),"error")}}),oe=(Y?.state==="RUNNING"||Y?.state==="PAUSE")&&(Y?.printable_objects_count??0)>=2;y.useEffect(()=>(K&&(document.title=`${K.name} - Camera`),()=>{document.title="Bambuddy"}),[K]);const fe=y.useRef(!1);y.useEffect(()=>{const Fe=`/api/v1/printers/${l}/camera/stop`;fe.current=!1;const et=()=>{if(l>0&&!fe.current){fe.current=!0;const at={},nt=Jm();nt&&(at.Authorization=`Bearer ${nt}`),fetch(Fe,{method:"POST",keepalive:!0,headers:at}).catch(()=>{})}},We=()=>{et()};window.addEventListener("beforeunload",We);const Pe=W.current;return()=>{window.removeEventListener("beforeunload",We),Pe&&(Pe.src=""),et()}},[l]),y.useEffect(()=>{if(P&&!k){const et=setTimeout(()=>{T(!1)},f==="stream"?3e3:2e4);return()=>clearTimeout(et)}},[f,P,j,k]),y.useEffect(()=>{const Fe=()=>{const et=!!document.fullscreenElement;I(et),me(1),ce({x:0,y:0}),f==="stream"&&!k&&(W.current&&(W.current.src=""),setTimeout(()=>{T(!0),F(Date.now())},200))};return document.addEventListener("fullscreenchange",Fe),()=>document.removeEventListener("fullscreenchange",Fe)},[f,k]),y.useEffect(()=>{let Fe;const et=()=>{clearTimeout(Fe),Fe=setTimeout(()=>{localStorage.setItem("cameraWindowState",JSON.stringify({width:window.outerWidth,height:window.outerHeight,left:window.screenX,top:window.screenY}))},500)};return window.addEventListener("resize",et),()=>{clearTimeout(Fe),window.removeEventListener("resize",et)}},[]),y.useEffect(()=>()=>{ie.current&&clearTimeout(ie.current),U.current&&clearInterval(U.current),G.current&&clearInterval(G.current)},[]);const ae=y.useCallback(()=>{if(O>=bN){ee(!1),C(!0);return}const Fe=Math.min(lst*Math.pow(2,O),cst);ee(!0),le(Math.ceil(Fe/1e3)),U.current=setInterval(()=>{le(et=>et<=1?(U.current&&clearInterval(U.current),0):et-1)},1e3),ie.current=setTimeout(()=>{L(et=>et+1),ee(!1),T(!0),C(!1),W.current&&(W.current.src=""),F(Date.now())},Fe)},[O]);y.useEffect(()=>{if(f!=="stream"||P||X||k){G.current&&(clearInterval(G.current),G.current=null);return}return G.current=setInterval(async()=>{try{const Fe=await re.getCameraStatus(l);(Fe.stalled||!Fe.active&&!N)&&(console.log(`Stream issue detected: stalled=${Fe.stalled}, active=${Fe.active}, reconnecting...`),G.current&&(clearInterval(G.current),G.current=null),T(!1),ae())}catch{}},dst),()=>{G.current&&(clearInterval(G.current),G.current=null)}},[f,P,N,X,k,l,ae]);const pe=()=>{T(!1),f==="stream"&&O{if(T(!1),C(!1),L(0),ee(!1),ie.current&&clearTimeout(ie.current),U.current&&clearInterval(U.current),W.current&&!localStorage.getItem("cameraWindowState")){const Fe=W.current,et=Fe.naturalWidth,We=Fe.naturalHeight;if(et>0&&We>0){const nt=window.outerWidth-window.innerWidth,At=window.outerHeight-window.innerHeight,Bt=et+16+nt,gt=We+45+16+At;try{window.resizeTo(Bt,gt)}catch{}}}},R=()=>{if(l>0){const Fe={},et=Jm();et&&(Fe.Authorization=`Bearer ${et}`),fetch(`/api/v1/printers/${l}/camera/stop`,{method:"POST",headers:Fe}).catch(()=>{})}},ne=Fe=>{f===Fe||k||(M(!0),T(!0),C(!1),L(0),ee(!1),me(1),ce({x:0,y:0}),ie.current&&clearTimeout(ie.current),U.current&&clearInterval(U.current),W.current&&(W.current.src=""),f==="stream"&&R(),setTimeout(()=>{g(Fe),F(Date.now()),M(!1)},100))},be=()=>{k||(M(!0),T(!0),C(!1),L(0),ee(!1),ie.current&&clearTimeout(ie.current),U.current&&clearInterval(U.current),W.current&&(W.current.src=""),f==="stream"&&R(),setTimeout(()=>{F(Date.now()),M(!1)},100))},ve=()=>{z.current&&(document.fullscreenElement?document.exitFullscreen():z.current.requestFullscreen())},ke=()=>{me(Fe=>Math.min(Fe+.5,4))},ye=()=>{me(Fe=>{const et=Math.max(Fe-.5,1);return et===1&&ce({x:0,y:0}),et})},ge=Fe=>{Fe.preventDefault(),Fe.deltaY<0?ke():ye()},Me=Fe=>{de>1&&(Fe.preventDefault(),ue(!0),H({x:Fe.clientX-Z.x,y:Fe.clientY-Z.y}))},Be=y.useCallback(()=>{if(!z.current)return{x:300,y:200};const Fe=z.current.getBoundingClientRect(),et=Fe.width*(de-1)/2,We=Fe.height*(de-1)/2;return{x:Math.max(50,et),y:Math.max(50,We)}},[de]),Le=Fe=>{if(he&&de>1){const et=Fe.clientX-xe.x,We=Fe.clientY-xe.y,Pe=Be();ce({x:Math.max(-Pe.x,Math.min(Pe.x,et)),y:Math.max(-Pe.y,Math.min(Pe.y,We))})}},Oe=()=>{ue(!1)},Re=Fe=>{if(Fe.length<2)return 0;const et=Fe[0].clientX-Fe[1].clientX,We=Fe[0].clientY-Fe[1].clientY;return Math.sqrt(et*et+We*We)},Ke=Fe=>Fe.length<2?{x:Fe[0].clientX,y:Fe[0].clientY}:{x:(Fe[0].clientX+Fe[1].clientX)/2,y:(Fe[0].clientY+Fe[1].clientY)/2},Ue=Fe=>{Fe.touches.length===2?(Fe.preventDefault(),A(Re(Fe.touches)),B(Ke(Fe.touches))):Fe.touches.length===1&&de>1&&(Fe.preventDefault(),ue(!0),H({x:Fe.touches[0].clientX-Z.x,y:Fe.touches[0].clientY-Z.y}))},lt=Fe=>{if(Fe.touches.length===2&&J!==null){Fe.preventDefault();const et=Re(Fe.touches),We=et/J;me(at=>{const nt=Math.max(1,Math.min(4,at*We));return nt===1&&ce({x:0,y:0}),nt}),A(et);const Pe=Ke(Fe.touches);if(E){const at=Be();ce(nt=>({x:Math.max(-at.x,Math.min(at.x,nt.x+(Pe.x-E.x))),y:Math.max(-at.y,Math.min(at.y,nt.y+(Pe.y-E.y)))}))}B(Pe)}else if(Fe.touches.length===1&&he&&de>1){Fe.preventDefault();const et=Fe.touches[0].clientX-xe.x,We=Fe.touches[0].clientY-xe.y,Pe=Be();ce({x:Math.max(-Pe.x,Math.min(Pe.x,et)),y:Math.max(-Pe.y,Math.min(Pe.y,We))})}},Ee=Fe=>{Fe.touches.length<2&&(A(null),B(null)),Fe.touches.length===0&&ue(!1)},st=()=>{me(1),ce({x:0,y:0})},Ne=i&&!p,Ze=Fe=>p?`${Fe}&token=${encodeURIComponent(p)}`:Fn(Fe),Ye=k||Ne?"":Ze(f==="stream"?`/api/v1/printers/${l}/camera/stream?fps=${u}&t=${j}`:`/api/v1/printers/${l}/camera/snapshot?t=${j}`),Te=P||k||X;return l?r.jsxs("div",{ref:z,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(yy,{className:"w-4 h-4"}),K?.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:()=>ne("stream"),disabled:Te,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:()=>ne("snapshot"),disabled:Te,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:()=>se.mutate(!Y?.chamber_light),disabled:!Y?.connected||se.isPending||!n("printers:control"),className:`p-1.5 rounded disabled:opacity-50 ${Y?.chamber_light?"bg-yellow-500/20 hover:bg-yellow-500/30":"hover:bg-bambu-dark-tertiary"}`,title:n("printers:control")?t("camera.chamberLight"):t("printers.permission.noControl"),children:r.jsx(f4,{on:Y?.chamber_light??!1,className:"w-4 h-4"})}),r.jsx("button",{onClick:()=>b(!0),disabled:!oe||!n("printers:control"),className:`p-1.5 rounded disabled:opacity-50 ${oe&&n("printers:control")?"hover:bg-bambu-dark-tertiary":""}`,title:n("printers:control")?t(oe?"printers.skipObjects.tooltip":"printers.skipObjects.onlyWhilePrinting"):t("printers.permission.noControl"),children:r.jsx(WT,{className:"w-4 h-4 text-bambu-gray"})}),r.jsx("button",{onClick:be,disabled:Te,className:"p-1.5 hover:bg-bambu-dark-tertiary rounded disabled:opacity-50",title:t(f==="stream"?"camera.restartStream":"camera.refreshSnapshot"),children:r.jsx(Xa,{className:`w-4 h-4 text-bambu-gray ${Te?"animate-spin":""}`})}),r.jsx("button",{onClick:()=>S(!0),className:"p-1.5 hover:bg-bambu-dark-tertiary rounded",title:t("camera.diagnose.button"),children:r.jsx(Dl,{className:"w-4 h-4 text-bambu-gray"})}),r.jsx("button",{onClick:ve,className:"p-1.5 hover:bg-bambu-dark-tertiary rounded",title:t(q?"camera.exitFullscreen":"camera.fullscreen"),children:q?r.jsx(YZ,{className:"w-4 h-4 text-bambu-gray"}):r.jsx(Vxe,{className:"w-4 h-4 text-bambu-gray"})})]})]}),r.jsx("div",{className:"flex-1 flex items-center justify-center p-2 overflow-hidden",onWheel:ge,onMouseMove:Le,onMouseUp:Oe,onMouseLeave:Oe,onTouchStart:Ue,onTouchMove:lt,onTouchEnd:Ee,style:{touchAction:"none"},children:r.jsxs("div",{className:"relative w-full h-full flex items-center justify-center",children:[(P||k)&&!X&&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(Xa,{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")})]})}),X&&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(pu,{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(O+1,bN),max:bN})}),r.jsx("button",{onClick:be,className:"px-4 py-2 bg-bambu-green text-white text-sm rounded hover:bg-bambu-green/80 transition-colors",children:t("camera.reconnectNow")})]})}),N&&!X&&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(ba,{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.jsxs("div",{className:"flex gap-2 justify-center",children:[r.jsx("button",{onClick:be,className:"px-4 py-2 bg-bambu-green text-white rounded hover:bg-bambu-green/80 transition-colors",children:t("camera.retry")}),r.jsx("button",{onClick:()=>S(!0),className:"px-4 py-2 bg-bambu-dark border border-bambu-dark-tertiary text-bambu-gray hover:text-white rounded transition-colors",children:t("camera.diagnose.button")})]})]})}),r.jsx("img",{ref:W,src:Ye,alt:t("camera.cameraStream"),className:"max-w-full max-h-full object-contain select-none",style:{transform:`scale(${de}) translate(${Z.x/de}px, ${Z.y/de}px) rotate(${K?.camera_rotation||0}deg)`,...K?.camera_rotation===90||K?.camera_rotation===270?{maxWidth:"100vh",maxHeight:"100vw"}:{},cursor:de>1?he?"grabbing":"grab":"default"},onError:Ye?pe:void 0,onLoad:Ye?$:void 0,onMouseDown:Me,draggable:!1},j),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:ye,disabled:de<=1,className:"p-1.5 hover:bg-white/10 rounded disabled:opacity-30",title:t("camera.zoomOut"),children:r.jsx(LO,{className:"w-4 h-4 text-white"})}),r.jsxs("button",{onClick:st,className:"px-2 py-1 text-sm text-white hover:bg-white/10 rounded min-w-[48px]",title:t("camera.resetZoom"),children:[Math.round(de*100),"%"]}),r.jsx("button",{onClick:ke,disabled:de>=4,className:"p-1.5 hover:bg-white/10 rounded disabled:opacity-30",title:t("camera.zoomIn"),children:r.jsx(FO,{className:"w-4 h-4 text-white"})})]})]})}),r.jsx(g4,{printerId:l,isOpen:w,onClose:()=>b(!1)}),x&&r.jsx($ee,{printerId:l,printerName:K?.name||null,onClose:()=>S(!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 mst(t,e,a){if(!t)return"";if(!e)return t;const n=e.match(/plate_(\d+)\.gcode/);return n&&parseInt(n[1],10)>1?`${t} — ${a("printers.plateNumber","Plate {{number}}",{number:n[1]})}`:t}function pst(t){const e=t.get("show")?.split(",")||["progress","layers","eta","filename","status"],a=parseInt(t.get("fps")||"15",10),n=Math.min(Math.max(isNaN(a)?15:a,1),30),i=t.get("camera"),s=i!=="false"&&i!=="0";return{size:t.get("size")||"medium",fps:n,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 hst(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 fst(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 gst(){const{printerId:t}=TS(),[e]=lb(),{t:a}=vt(),n=ta(),i=parseInt(t||"0",10),[s,o]=y.useState(Date.now()),l=y.useMemo(()=>pst(e),[e]),c=fst(l.size),{data:d}=Qe({queryKey:["printer",i],queryFn:()=>re.getPrinter(i),enabled:i>0}),{data:u}=Qe({queryKey:["printerStatus",i],queryFn:()=>re.getPrinterStatus(i),enabled:i>0,refetchInterval:2e3}),{data:m}=Qe({queryKey:["settings"],queryFn:re.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&&n.setQueryData(["printerStatus",i],P.status)}catch{}},N.onerror=()=>{},()=>{N.close()}},[i,n]),y.useEffect(()=>(document.title=d?`${d.name} - ${a("streamOverlay.title")}`:a("streamOverlay.title"),()=>{document.title="Bambuddy"}),[d,a]);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:a("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:a("common.loading")})});const g=u.state==="RUNNING"||u.state==="PAUSE",w=u.progress||0,b=Fn(`/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:a("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(gr,{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:mst(u.current_print.replace(/\.gcode\.3mf$|\.3mf$|\.gcode$/i,""),u.gcode_file,a)}),l.showStatus&&r.jsx("div",{className:`${c.text} text-white/70 mb-2`,children:hst(u,a)}),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:a("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(cn,{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:hs(u.remaining_time*60)})]}),r.jsxs("div",{className:`flex items-center ${c.gap} text-white/70`,children:[r.jsx(Za,{className:c.icon}),r.jsxs("span",{className:`${c.text} text-white`,children:[a("streamOverlay.eta")," ",zO(u.remaining_time,p,a)]})]})]})]}),!g&&r.jsx("div",{className:`${c.text} text-white/70 py-2`,children:u.connected?a("streamOverlay.printerIdle"):a("streamOverlay.printerOffline")})]})})]})}function bst(){const{t}=vt(),{id:e}=TS(),{mode:a}=pb(),{data:n,isLoading:i,error:s}=Qe({queryKey:["external-link",e],queryFn:()=>re.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||!n?r.jsxs("div",{className:"flex flex-col items-center justify-center h-full gap-4 text-bambu-gray",children:[r.jsx(ba,{className:"w-12 h-12"}),r.jsx("p",{children:t("common.linkNotFound")})]}):r.jsx("iframe",{src:n.url,className:"h-full w-full border-0",style:{colorScheme:a},title:n.name,sandbox:"allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox"})}function EX(){const{id:t}=TS(),e=Oi(),a=ta(),{t:n}=vt(),{showToast:i}=na(),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}=Qe({queryKey:["group",t],queryFn:()=>re.getGroup(Number(t)),enabled:s}),{data:S,isLoading:N}=Qe({queryKey:["permissions"],queryFn:()=>re.getPermissions()});s&&b&&!g&&(l(b.name),d(b.description||""),m(b.permissions),w(!0));const C=ot({mutationFn:Q=>re.createGroup(Q),onSuccess:()=>{a.invalidateQueries({queryKey:["groups"]}),a.invalidateQueries({queryKey:["group"]}),i(n("groups.toast.created")),e("/settings?tab=users")},onError:Q=>{i(Q.message,"error")}}),P=ot({mutationFn:Q=>re.updateGroup(Number(t),Q),onSuccess:Q=>{a.invalidateQueries({queryKey:["groups"]}),Q&&a.setQueryData(["group",t],Q),i(n("groups.toast.updated")),e("/settings?tab=users")},onError:Q=>{i(Q.message,"error")}}),T=C.isPending||P.isPending,j=()=>{if(!o.trim()){i(n("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=Q=>{m(le=>le.includes(Q)?le.filter(de=>de!==Q):[...le,Q])},k=(Q,le)=>{const de=Q.permissions.map(me=>me.value);m(me=>{const Z=me.filter(ce=>!de.includes(ce));return le?[...Z,...de]:Z})},M=Q=>Q.permissions.every(le=>u.includes(le.value)),q=Q=>{const le=Q.permissions.filter(de=>u.includes(de.value)).length;return le>0&&le{S&&m(S.all_permissions)},O=()=>{m([])},L=p.toLowerCase(),X=y.useMemo(()=>S?L?S.categories.map(Q=>({...Q,permissions:Q.permissions.filter(le=>le.label.toLowerCase().includes(L))})).filter(Q=>Q.permissions.length>0):S.categories:[],[S,L]),ee=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(PT,{className:"w-5 h-5"})}),r.jsx("h1",{className:"text-xl font-bold text-white",children:n(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(ba,{className:"w-4 h-4 shrink-0"}),n("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:n("groups.form.groupName")}),r.jsx("input",{type:"text",value:o,onChange:Q=>l(Q.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:n("groups.form.groupNamePlaceholder")})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:n("groups.form.description")}),r.jsx("input",{type:"text",value:c,onChange:Q=>d(Q.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:n("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:[n("groups.editor.permissionsSelected",{count:u.length})," / ",ee]}),r.jsx(je,{size:"sm",variant:"ghost",onClick:I,children:n("groups.editor.selectAll")}),r.jsx(je,{size:"sm",variant:"ghost",onClick:O,children:n("groups.editor.clearAll")})]}),r.jsxs("div",{className:"relative",children:[r.jsx(fr,{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:Q=>f(Q.target.value),placeholder:n("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"})]})]}),X.length===0?r.jsx("div",{className:"text-center py-12 text-bambu-gray",children:n("groups.editor.noResults")}):r.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:X.map(Q=>{const le=S.categories.find(he=>he.name===Q.name),de=le.permissions.filter(he=>u.includes(he.value)).length,me=le.permissions.length,Z=M(le),ce=q(le);return r.jsxs(Tt,{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:()=>k(le,!Z),className:`w-5 h-5 rounded border flex items-center justify-center transition-colors shrink-0 ${Z?"bg-bambu-green border-bambu-green":ce?"bg-bambu-green/50 border-bambu-green":"border-bambu-gray hover:border-white"}`,children:[Z&&r.jsx(kr,{className:"w-3 h-3 text-white"}),ce&&!Z&&r.jsx(lC,{className:"w-3 h-3 text-white"})]}),r.jsx(vl,{className:"w-4 h-4 text-bambu-gray shrink-0"}),r.jsx("span",{className:"text-white font-medium text-sm",children:Q.name})]}),r.jsxs("span",{className:"text-xs text-bambu-gray tabular-nums",children:[de,"/",me]})]}),r.jsx("div",{className:"p-3 space-y-1",children:Q.permissions.map(he=>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(he.value),onChange:()=>F(he.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:he.label})]},he.value))})]},Q.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(je,{variant:"secondary",onClick:()=>e("/settings?tab=users"),children:n("common.cancel")}),r.jsx(je,{onClick:j,disabled:T||!o.trim(),children:T?r.jsxs(r.Fragment,{children:[r.jsx(pt,{className:"w-4 h-4 animate-spin"}),n("common.saving")]}):r.jsxs(r.Fragment,{children:[r.jsx(fs,{className:"w-4 h-4"}),n("common.save")]})})]})]})}const xst=1.65,DX=["#1DB954","#3B82F6","#F59E0B","#EF4444","#8B5CF6"];function Tw(t,e,a){return`${t}||${e??""}||${a??""}`}function Gm(t,e){const a=new Date(t);return a.setDate(a.getDate()+Math.round(e)),a}function CS(t){return t.toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})}function Aw(t){return t.toLocaleDateString(void 0,{month:"short",day:"numeric"})}function yst(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()),a=Date.now(),n=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 vst(t){const e=t.reduce((s,o)=>s+Math.max(0,o.weight_used-(o.weight_used_baseline??0)),0);if(e===0)return null;const a=Date.now(),n=t.reduce((s,o)=>{const l=new Date(o.created_at).getTime();return lre.getAllUsageHistory(5e3),staleTime:6e4,enabled:o}),{data:j=[]}=Qe({queryKey:["shopping-list"],queryFn:re.getShoppingList,staleTime:3e4,enabled:o}),F=C?.forecast_global_lead_time_days??0,k=y.useMemo(()=>{const le=new Map;for(const de of P)le.set(Tw(de.material,de.subtype,de.brand),de);return le},[P]),M=y.useMemo(()=>{const le=new Map;for(const de of T){const me=le.get(de.spool_id)??[];me.push(de),le.set(de.spool_id,me)}return le},[T]),q=y.useMemo(()=>{const le=new Map;for(const de of t){if(de.archived_at)continue;const me=Tw(de.material,de.subtype,de.brand),Z=le.get(me)??{key:me,material:de.material,subtype:de.subtype,brand:de.brand,spools:[]};Z.spools.push(de),le.set(me,Z)}return[...le.values()]},[t]),I=y.useMemo(()=>{const le=new Date;return le.setHours(0,0,0,0),q.map(de=>{const me=k.get(de.key)??null,Z=me?.lead_time_days??0,ce=Math.max(F,Z),he=me?.safety_margin_value??14,ue=me?.safety_margin_unit??"days",xe=de.spools.reduce((R,ne)=>R+Math.max(0,ne.label_weight-ne.weight_used),0),H=de.spools.reduce((R,ne)=>R+ne.label_weight,0),J=de.spools.reduce((R,ne)=>R+Math.max(0,ne.weight_used-(ne.weight_used_baseline??0)),0),A=[];for(const R of de.spools)A.push(...M.get(R.id)??[]);let E=null,B=null,W="none";const z=yst(A);if(z!==null)E=z.rate,B=z.stdDev,W="history";else{const R=vst(de.spools);R!==null&&(E=R,W="delta")}const ie=B??(E!==null?E*.2:0),U=xst*ie*Math.sqrt(ce),G=ue==="g"?he:E!==null?E*he:he*5,K=U+G,Y=E!==null?E*ce+K:0,se=E&&E>0?Math.floor(xe/E):null,oe=se!==null?Gm(le,se):null,fe=E&&E>0?Math.floor((xe-Y)/E):null,ae=fe!==null?Gm(le,Math.max(0,fe)):null,pe=se!==null&&ce>0&&se<=ce,$=!pe&&fe!==null&&fe<=0;return{group:de,settings:me,totalRemainingG:xe,totalLabelG:H,totalSpools:de.spools.length,totalUsedG:J,dailyRateG:E,dailyRateStdDev:B,rateTier:W,effectiveLeadTimeDays:ce,safetyStockG:K,reorderPointG:Y,daysRemaining:se,daysUntilROP:fe,projectedEmptyDate:oe,reorderTriggerDate:ae,reorderAlert:$,stockBreakAlert:pe}})},[q,k,M,F]),O=y.useMemo(()=>{const le=[...I];return le.sort((de,me)=>{let Z=0,ce=0;switch(u){case"material":Z=[de.group.material,de.group.subtype??"",de.group.brand??""].join(" ").toLowerCase(),ce=[me.group.material,me.group.subtype??"",me.group.brand??""].join(" ").toLowerCase();break;case"used":Z=de.totalUsedG,ce=me.totalUsedG;break;case"days_left":Z=de.daysRemaining??999999,ce=me.daysRemaining??999999;break;case"stock":Z=de.totalRemainingG,ce=me.totalRemainingG;break}const he=Zce?1:0;return p==="asc"?he:-he}),le},[I,u,p]),L=y.useMemo(()=>I.filter(le=>!le.settings?.alerts_snoozed&&(le.stockBreakAlert||le.reorderAlert)),[I]),X=y.useMemo(()=>[...I].filter(le=>le.dailyRateG!==null).sort((le,de)=>de.totalUsedG-le.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(oc,{className:"w-8 h-8 opacity-40"}),r.jsx("p",{className:"text-sm",children:n("forecast.noReadAccess")})]});function ee(le){u===le?f(de=>de==="asc"?"desc":"asc"):(m(le),f(le==="days_left"?"asc":"desc"))}const Q=j.length>0?j.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(le=>!le),className:`flex items-center gap-2 px-3 py-1.5 rounded-lg border text-sm font-medium transition-colors ${L.some(le=>le.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(ba,{className:"w-4 h-4"}),n("forecast.alertCount",{count:L.length}),c?r.jsx(al,{className:"w-3.5 h-3.5"}):r.jsx(Da,{className:"w-3.5 h-3.5"})]}),l&&r.jsx(Cst,{value:F,onSave:le=>{re.updateSettings({forecast_global_lead_time_days:le}).then(()=>{e.invalidateQueries({queryKey:["settings"]}),a(n("forecast.globalLeadTimeSaved"),"success")})}}),r.jsxs("button",{onClick:()=>x(le=>!le),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(mb,{className:"w-4 h-4"}),r.jsx("span",{className:"hidden sm:inline",children:n("forecast.shoppingList")}),Q&&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:Q})]})]}),c&&L.length>0&&r.jsx("div",{className:"space-y-2",children:L.map(le=>r.jsx(kst,{forecast:le,onCart:()=>w(le)},le.group.key))}),b&&r.jsx(jst,{items:j,forecasts:I,globalLeadTime:F,canWrite:l,onClose:()=>x(!1),onRemove:le=>{re.removeFromShoppingList(le).then(()=>e.invalidateQueries({queryKey:["shopping-list"]})).catch(()=>a(n("forecast.failedSaveSettings"),"error"))},onClear:()=>{re.clearShoppingList().then(()=>e.invalidateQueries({queryKey:["shopping-list"]})).catch(()=>a(n("forecast.failedSaveSettings"),"error"))}}),X.length>0&&r.jsx(Nst,{forecasts:X,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(US,{className:"w-10 h-10 mb-3 opacity-40"}),r.jsx("p",{className:"text-sm",children:n("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(xN,{col:"material",active:u,dir:p,onSort:ee,children:n("forecast.sku")}),r.jsx(xN,{col:"stock",active:u,dir:p,onSort:ee,children:n("forecast.stock")}),r.jsx(xN,{col:"used",active:u,dir:p,onSort:ee,children:n("forecast.dailyRate")}),r.jsx(xN,{col:"days_left",active:u,dir:p,onSort:ee,children:n("forecast.daysLeft")}),r.jsx("th",{className:"px-4 py-3 text-left text-xs font-medium text-bambu-gray uppercase tracking-wide",children:n("forecast.emptyBy")}),r.jsx("th",{className:"px-4 py-3 text-left text-xs font-medium text-bambu-gray uppercase tracking-wide",children:n("forecast.reorderBy")}),r.jsx("th",{className:"w-24 px-4 py-3"})]})}),r.jsx("tbody",{className:"divide-y divide-bambu-dark-tertiary",children:O.map(le=>r.jsx(Pst,{forecast:le,globalLeadTime:F,canWrite:l,onSaved:()=>e.invalidateQueries({queryKey:["sku-settings"]}),onCart:()=>w(le),showToast:a},le.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"}),n("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"}),n("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"}),n("forecast.noDataLegend")]})]})]}),g&&r.jsx(Est,{forecast:g,onClose:()=>w(null),onAdd:le=>{re.addToShoppingList(le).then(()=>{e.invalidateQueries({queryKey:["shopping-list"]}),a(n("forecast.addedToCart"),"success"),w(null),x(!0)}).catch(()=>a(n("forecast.failedAddItem"),"error"))}})]})}function xN({col:t,active:e,dir:a,onSort:n,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:()=>n(t),children:r.jsxs("span",{className:"inline-flex items-center",children:[i,s?a==="asc"?r.jsx(Km,{className:"w-3 h-3 ml-1 text-bambu-green"}):r.jsx(Vh,{className:"w-3 h-3 ml-1 text-bambu-green"}):r.jsx(TT,{className:"w-3 h-3 ml-1 opacity-40"})]})})}function kst({forecast:t,onCart:e}){const{t:a}=vt(),n=[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(ba,{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:n}),i?r.jsxs("span",{className:"ml-2 text-xs opacity-80",children:[a("forecast.stockBreakRisk")," — ",a("forecast.stockBreakDetail",{days:t.daysRemaining,lt:t.effectiveLeadTimeDays})]}):r.jsxs("span",{className:"ml-2 text-xs opacity-80",children:[a("forecast.reorderNow")," — ",a("forecast.reorderTriggerPassed",{date:t.reorderTriggerDate?CS(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(mb,{className:"w-3 h-3"})," ",a("forecast.order")]})]})}const _st=[{label:"1W",value:7},{label:"1M",value:30},{label:"6M",value:180}];function Nst({forecasts:t,days:e,onDaysChange:a}){const{t:n}=vt(),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:DX[m%DX.length],rop:u.reorderPointG,points:wst(u,e)})),o=i.map(u=>{const m={day:u,label:Aw(Gm(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(US,{className:"w-4 h-4 text-bambu-green"}),r.jsx("h3",{className:"text-sm font-semibold text-white",children:n("forecast.chartTitle")}),r.jsx("span",{className:"text-xs text-bambu-gray ml-1 hidden sm:inline",children:n("forecast.dashedLinesROP")}),r.jsx("div",{className:"ml-auto flex items-center bg-bambu-dark-tertiary rounded-lg p-0.5",children:_st.map(u=>r.jsx("button",{onClick:()=>a(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(tu,{width:"100%",height:220,children:r.jsxs(v5,{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(Em,{strokeDasharray:"3 3",stroke:"#374151",strokeOpacity:.5}),r.jsx(Dm,{dataKey:"label",tick:{fill:"#6B7280",fontSize:10},interval:Math.max(0,Math.ceil(l/8)-1),axisLine:!1,tickLine:!1}),r.jsx(Fm,{tick:{fill:"#6B7280",fontSize:10},axisLine:!1,tickLine:!1,tickFormatter:u=>u>=1e3?`${(u/1e3).toFixed(1)}kg`:`${u}g`,width:48}),r.jsx(ru,{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($4,{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(qA,{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(nu,{y:u.rop,stroke:u.color,strokeDasharray:"4 3",strokeOpacity:.6},`rop-${u.key}`))]})})]})}function Cst({value:t,onSave:e}){const{t:a}=vt(),[n,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(Ei,{className:"w-3.5 h-3.5 flex-shrink-0","aria-label":a("forecast.globalLeadTimeHint")}),r.jsxs("span",{className:"hidden sm:inline",children:[a("forecast.globalLeadTime"),":"]}),n?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:a("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(fc,{className:"w-3 h-3"})})]})]})}function Pst({forecast:t,globalLeadTime:e,canWrite:a,onSaved:n,onCart:i,showToast:s}){const{t:o}=vt(),[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=ot({mutationFn:re.upsertSkuSettings,onSuccess:()=>{n(),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",j=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 k(O,L,X,ee=C){N.mutate({material:t.group.material,subtype:t.group.subtype,brand:t.group.brand,lead_time_days:O,safety_margin_value:L,safety_margin_unit:X,alerts_snoozed:ee})}function M(O){O.stopPropagation(),k(t.settings?.lead_time_days??0,t.settings?.safety_margin_value??14,t.settings?.safety_margin_unit??"days",!C)}const q=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(O=>!O),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 ${j>50?"bg-bambu-green":j>20?"bg-yellow-500":"bg-red-500"}`,style:{width:`${Math.min(j,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:q})]}),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?CS(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?CS(t.reorderTriggerDate):"—"})}),r.jsx("td",{className:"px-4 py-3",onClick:O=>O.stopPropagation(),children:r.jsxs("div",{className:"flex items-center justify-end gap-1",children:[a&&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(mb,{className:"w-4 h-4"})}),!C&&(t.stockBreakAlert?r.jsx(ba,{className:"w-4 h-4 text-red-400","aria-label":o("forecast.stockBreakRisk")}):t.reorderAlert?r.jsx(ba,{className:"w-4 h-4 text-yellow-400","aria-label":o("forecast.reorderNow")}):t.daysRemaining!==null?r.jsx(kr,{className:"w-4 h-4 text-bambu-green/50"}):null),a&&r.jsx("button",{onClick:M,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(HZ,{className:"w-3.5 h-3.5"})}),r.jsx("button",{onClick:O=>{O.stopPropagation(),c(L=>!L)},className:"p-1.5 text-bambu-gray hover:text-white rounded transition-colors",children:l?r.jsx(al,{className:"w-4 h-4"}):r.jsx(Da,{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(C3,{label:o("forecast.effectiveLeadTime"),value:`${t.effectiveLeadTimeDays}d`,hint:o("forecast.effectiveLeadTimeHint",{global:e,sku:t.settings?.lead_time_days??0})}),r.jsx(C3,{label:o("forecast.safetyMarginLabel"),value:`${Math.round(t.safetyStockG)}g`,hint:o("forecast.safetyMarginHint")}),r.jsx(C3,{label:o("forecast.reorderPoint"),value:`${Math.round(t.reorderPointG)}g`,hint:o("forecast.reorderPointHint")})]}),a&&r.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[r.jsx(Tst,{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 O=parseInt(f,10);!isNaN(O)&&O>=0&&(k(O,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(Ast,{value:t.settings?.safety_margin_value??14,unit:x,editing:m,inputValue:w,dailyRateG:t.dailyRateG,onInputChange:b,onUnitChange:O=>S(O),onEdit:()=>{b(String(t.settings?.safety_margin_value??14)),S(t.settings?.safety_margin_unit??"days"),p(!0)},onSave:()=>{const O=parseInt(w,10);!isNaN(O)&&O>=0&&(k(t.settings?.lead_time_days??0,O,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(O=>{const L=Math.max(0,O.label_weight-O.weight_used),X=O.label_weight>0?L/O.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:["#",O.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 ${X>50?"bg-bambu-green":X>20?"bg-yellow-500":"bg-red-500"}`,style:{width:`${Math.min(X,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(Math.max(0,O.weight_used-(O.weight_used_baseline??0))),"g"]})}),r.jsx("td",{className:"px-4 py-2",children:r.jsxs("span",{className:"text-sm text-bambu-gray",children:[O.label_weight,"g"]})})]},O.id)})})]})})]})]})})})]})}function C3({label:t,value:e,hint:a}){return r.jsxs("div",{className:"bg-bambu-dark-tertiary/40 rounded-lg p-3",title:a,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 Tst({label:t,hint:e,unit:a,editing:n,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(Ei,{className:"w-3 h-3 text-bambu-gray/50"})})]}),n?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:a}),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:a}),r.jsx("button",{onClick:l,className:"p-1 text-bambu-gray hover:text-white rounded transition-colors",children:r.jsx(fc,{className:"w-3 h-3"})})]})]})}function Ast({value:t,unit:e,editing:a,inputValue:n,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}=vt(),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(Ei,{className:"w-3 h-3 text-bambu-gray/50"})})]}),a?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:n,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(fc,{className:"w-3 h-3"})})]})]})}function jst({items:t,forecasts:e,globalLeadTime:a,canWrite:n,onClose:i,onRemove:s,onClear:o}){const{t:l}=vt(),c=ta(),[d,u]=y.useState("list"),m=ot({mutationFn:async({id:b,status:x,item:S,avgSpoolG:N})=>{if(await re.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 re.bulkCreateSpools(P,S.quantity_spools),await re.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(Tw(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 j=p.get(Tw(T.material,T.subtype,T.brand))??null,F=j&&j.totalSpools>0?j.totalLabelG/j.totalSpools:1e3,k=Math.round(T.quantity_spools*F),M=j?.effectiveLeadTimeDays??a??0,q=M>0?CS(Gm(new Date,M)):"";return[T.quantity_spools,T.material,T.brand??"",T.subtype??"",k,M||"",q,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(mb,{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(qr,{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(gge,{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(Ur,{className:"w-3 h-3"}),l("forecast.downloadCsv")]}),n&&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($t,{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(qr,{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(q=>q.item.id===b.id),N=p.get(Tw(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??a??0,j=T>0?Gm(new Date,T):null,F=b.status==="purchased"||b.status==="received",k=b.status==="received",M=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(ba,{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:j?CS(j):"—"})}),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 ${k?"bg-bambu-green/20 text-bambu-green":F?"bg-blue-400/20 text-blue-400":"bg-bambu-dark-tertiary text-bambu-gray"}`,children:l(k?"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:n&&r.jsxs(r.Fragment,{children:[r.jsx("button",{onClick:()=>m.mutate({id:b.id,status:F?"pending":"purchased"}),disabled:M||k,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(vs,{className:"w-3.5 h-3.5"}):r.jsx(rbe,{className:"w-3.5 h-3.5"})}),r.jsx("button",{onClick:()=>m.mutate({id:b.id,status:"received",item:b,avgSpoolG:C}),disabled:M||!F||k,title:l("forecast.markReceived"),className:"p-1 rounded transition-colors text-bambu-gray hover:text-bambu-green disabled:opacity-30",children:r.jsx(oye,{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(ea,{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(Mst,{item:b,forecast:x,globalLeadTime:a,canWrite:n,onRemove:()=>s(b.id)},b.id))})]})}function Mst({item:t,forecast:e,globalLeadTime:a,canWrite:n,onRemove:i}){const{t:s}=vt(),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=Aw(Gm(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(ru,{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(qA,{type:"linear",dataKey:"stock",stroke:"#1DB954",strokeWidth:2,fill:`url(#cart-post-${t.id})`,dot:!1,activeDot:{r:3}}),e.reorderPointG>0&&r.jsx(nu,{y:e.reorderPointG,stroke:"#F59E0B",strokeDasharray:"5 3",strokeOpacity:.8,label:{value:"ROP",position:"insideTopRight",fill:"#F59E0B",fontSize:9}}),e.safetyStockG>0&&r.jsx(nu,{y:e.safetyStockG,stroke:"#6B7280",strokeDasharray:"3 3",strokeOpacity:.6,label:{value:"SS",position:"insideTopRight",fill:"#6B7280",fontSize:9}}),r.jsx(nu,{x:Aw(Gm(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(nu,{x:Aw(Gm(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 Est({forecast:t,onClose:e,onAdd:a}){const{t:n}=vt(),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(),a({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(mb,{className:"w-5 h-5 text-bambu-green"}),r.jsx("h2",{className:"text-base font-semibold text-white",children:n("forecast.addToCartTitle")})]}),r.jsx("button",{onClick:e,className:"p-1 text-bambu-gray hover:text-white transition-colors",children:r.jsx($t,{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:n("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:n("forecast.byDuration")})]}),s==="qty"?r.jsxs("div",{className:"space-y-1.5",children:[r.jsx("label",{className:"text-xs text-bambu-gray",children:n("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:n("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:n("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:n("forecast.noUsageQty")})]}),r.jsxs("div",{className:"space-y-1.5",children:[r.jsx("label",{className:"text-xs text-bambu-gray",children:n("forecast.noteOptional")}),r.jsx("input",{type:"text",maxLength:200,value:m,onChange:b=>p(b.target.value),placeholder:n("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:n("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:n("forecast.cancel")})]})]})]})})}const sO={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},Dst=new Set(["material","subtype","brand","rgba","color_name","label_weight"]);function mde(t,e=!1,a=!1){const n={};return e||a?(!t.material&&!t.spoolman_filament_id&&(n.material="Material is required"),{isValid:Object.keys(n).length===0,errors:n}):(t.slicer_filament||(n.slicer_filament="Slicer preset is required"),t.material||(n.material="Material is required"),t.brand||(n.brand="Brand is required"),t.subtype||(n.subtype="Subtype is required"),{isValid:Object.keys(n).length===0,errors:n})}const pde=["PLA","PETG","ABS","TPU","ASA","PC","PA","PVA","HIPS","PA-CF","PETG-CF","PLA-CF"],Fst=["Bambu","PolyLite","PolyTerra","eSUN","Overture","Fiberon","SUNLU","Inland","Hatchbox","Generic"],jw=["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"],hde=[{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"}],Lst=[{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"}],FX=[...hde,...Lst],fde="bambuddy-recent-colors",Rst=8,Ist=[{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 rf(t){let e=t.replace(/@.*$/,"").trim();e=e.replace(/\(Custom\)/i,"").trim(),e=e.replace(/^[#*]+\s*/,"").trim();const a=["PLA-CF","PETG-CF","ABS-GF","ASA-CF","PA-CF","PAHT-CF","PA6-CF","PA6-GF","PPA-CF","PPA-GF","PET-CF","PPS-CF","PC-CF","PC-ABS","ABS-GF","PCTG","PETG","PLA","ABS","ASA","PC","PA","TPU","PVA","HIPS","BVOH","PPS","PEEK","PEI"];let n="",i=-1;for(const c of a){const d=e.toUpperCase().indexOf(c.toUpperCase());if(d!==-1){n=c,i=d;break}}let s="";i>0&&(s=e.substring(0,i).trim(),s=s.replace(/[-_\s]+$/,""));let o="";i!==-1&&n&&(o=e.substring(i+n.length).trim(),o=o.replace(/^[-_\s]+/,""));let l="";for(const c of jw)if(o.toLowerCase().includes(c.toLowerCase())){l=c;break}if(!l&&s)for(const c of jw){const d=new RegExp(`\\s+${c}$`,"i");if(d.test(s)){l=c,s=s.replace(d,"").trim();break}}return{brand:s,material:n,variant:l}}function gde(t,e){const a=new Set(Fst);for(const n of t){const{brand:i}=rf(n.name);i&&i.length>1&&a.add(i)}if(e)for(const n of e)if(n.filament_vendor&&n.filament_vendor.length>1)a.add(n.filament_vendor);else{const{brand:i}=rf(n.name);i&&i.length>1&&a.add(i)}return Array.from(a).sort((n,i)=>n.localeCompare(i))}function Ost(t){const e=t.filter(n=>n.preset_type==="filament");return e.length===0?[]:e.map(n=>{const i=String(n.id),s=n.filament_type||i,o=Array.from(new Set([i,s]));return{code:i,name:n.name,displayName:n.name,isCustom:!1,allCodes:o}}).sort((n,i)=>n.displayName.localeCompare(i.displayName))}function bde(t,e,a,n){const i=[],s=[],o=new Set;for(const u of t)if(u.is_custom){const m=u.name.toUpperCase();(e.size===0||Array.from(e).some(f=>m.includes(f))||!m.includes("@"))&&(i.push({code:u.setting_id,name:u.name,displayName:`${u.name} (Custom)`,isCustom:!0,allCodes:[u.setting_id]}),o.add(u.setting_id))}else s.push({code:u.setting_id,name:u.name,displayName:u.name,isCustom:!1,allCodes:[u.setting_id]}),o.add(u.setting_id);const l=a&&a.length>0?Ost(a):[],c=[];if(n&&n.length>0)for(const u of n){const m=u.filament_id.startsWith("GF")?"GFS"+u.filament_id.slice(2):u.filament_id;o.has(u.filament_id)||o.has(m)||c.push({code:u.filament_id,name:u.name,displayName:u.name,isCustom:!1,allCodes:[u.filament_id,m]})}const d=[...i,...s,...l,...c];return d.length===0?Ist:d.sort((u,m)=>u.displayName.localeCompare(m.displayName))}function xde(t,e){if(!t)return;let a=e.find(n=>n.code===t);if(a||(a=e.find(n=>n.allCodes.includes(t))),!a){const n=t.toLowerCase();a=e.find(i=>i.code.toLowerCase()===n||i.allCodes.some(s=>s.toLowerCase()===n))}return a}function yde(){try{const t=localStorage.getItem(fde);if(t)return JSON.parse(t)}catch{}return[]}function vde(t,e){const a=e.filter(i=>i.hex.toUpperCase()!==t.hex.toUpperCase()),n=[t,...a].slice(0,Rst);try{localStorage.setItem(fde,JSON.stringify(n))}catch{}return n}function P3(t,e){if(!e.material)return!1;const n=(t.name||"").replace(/^High Flow[_\s]+/i,"").replace(/^Standard[_\s]+/i,"").replace(/^HF[_\s]+/i,"").replace(/^S[_\s]+/i,"").trim(),i=rf(n);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())||n.toLowerCase().includes(e.subtype.toLowerCase())))}function wde({formData:t,updateField:e,cloudAuthenticated:a,loadingCloudPresets:n,presetInputValue:i,setPresetInputValue:s,selectedPresetOption:o,filamentOptions:l,availableBrands:c,availableMaterials:d,quickAdd:u,quantity:m,onQuantityChange:p,errors:f}){const{t:g}=vt(),[w,b]=y.useState(!1),[x,S]=y.useState(!1),[N,C]=y.useState(!1),[P,T]=y.useState(!1),[j,F]=y.useState(""),[k,M]=y.useState(""),[q,I]=y.useState(""),[O,L]=y.useState(String(t.label_weight)),[X,ee]=y.useState(!1),Q=y.useRef(null),le=y.useRef(null),de=y.useRef(null),me=y.useRef(null);y.useEffect(()=>{const H=J=>{Q.current&&!Q.current.contains(J.target)&&b(!1),me.current&&!me.current.contains(J.target)&&T(!1),le.current&&!le.current.contains(J.target)&&S(!1),de.current&&!de.current.contains(J.target)&&C(!1)};return document.addEventListener("mousedown",H),()=>document.removeEventListener("mousedown",H)},[]);const Z=y.useMemo(()=>{if(!i)return l;const H=i.toLowerCase();return l.filter(J=>J.displayName.toLowerCase().includes(H)||J.code.toLowerCase().includes(H))},[l,i]),ce=y.useMemo(()=>{if(!j)return c;const H=j.toLowerCase();return c.filter(A=>A.toLowerCase().includes(H)).sort((A,E)=>{const B=A.toLowerCase()===H,W=E.toLowerCase()===H;return B&&!W?-1:!B&&W?1:A.localeCompare(E)})},[c,j]),he=y.useMemo(()=>{if(!k)return jw;const H=k.toLowerCase();return jw.filter(J=>J.toLowerCase().includes(H))},[k]),ue=y.useMemo(()=>{if(!q)return d;const H=q.toLowerCase();return d.filter(A=>A.toLowerCase().includes(H)).sort((A,E)=>{const B=A.toLowerCase()===H,W=E.toLowerCase()===H;return B&&!W?-1:!B&&W?1:A.localeCompare(E)})},[q,d]);y.useEffect(()=>{X||L(String(t.label_weight))},[t.label_weight,X]);const xe=H=>{e("slicer_filament",H.code),s(H.displayName),b(!1);const J=rf(H.name);J.material&&e("material",J.material),J.brand&&e("brand",J.brand),J.variant&&e("subtype",J.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:n?r.jsxs(r.Fragment,{children:[r.jsx(pt,{className:"w-3 h-3 animate-spin"})," ",g("inventory.loadingPresets")]}):a?r.jsxs(r.Fragment,{children:[r.jsx(Gh,{className:"w-3 h-3 text-bambu-green"})," ",g("inventory.cloudConnected")]}):r.jsxs(r.Fragment,{children:[r.jsx(Z3,{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:Q,children:[r.jsx(fr,{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:H=>{s(H.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:Z.length===0?r.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:g("inventory.noPresetsFound")}):Z.map(H=>r.jsx("button",{type:"button",className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary truncate ${o?.code===H.code?"bg-bambu-green/10 text-bambu-green":"text-white"}`,onClick:()=>xe(H),children:H.displayName},`${H.code}::${H.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:me,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?q:t.material,onChange:H=>{I(H.target.value),T(!0)},onFocus:()=>{T(!0),I("")}}),r.jsx(Da,{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:[ue.length===0?r.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:g("inventory.noResults")}):ue.map(H=>r.jsx("button",{type:"button",className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary ${t.material===H?"bg-bambu-green/10 text-bambu-green":"text-white"}`,onClick:()=>{e("material",H),T(!1),I("")},children:H},H)),q&&!ue.includes(q)&&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",q),T(!1),I("")},children:g("inventory.useCustomMaterial",{material:q})})]})]}),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:le,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?j:t.brand,onChange:H=>{F(H.target.value),S(!0)},onFocus:()=>{S(!0),F("")}}),r.jsx(Da,{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:[ce.length===0?r.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:g("inventory.noResults")}):ce.map(H=>r.jsx("button",{type:"button",className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary ${t.brand===H?"bg-bambu-green/10 text-bambu-green":"text-white"}`,onClick:()=>{e("brand",H),S(!1),F("")},children:H},H)),j&&!ce.includes(j)&&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",j),S(!1),F("")},children:g("inventory.useCustomBrand",{brand:j})})]})]}),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:de,children:[r.jsx("input",{type:"text",value:N?k:t.subtype,onChange:H=>{M(H.target.value),C(!0)},onFocus:()=>{C(!0),M("")},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(Da,{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:[he.length===0?r.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:g("inventory.noResults")}):he.map(H=>r.jsx("button",{type:"button",className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary ${t.subtype===H?"bg-bambu-green/10 text-bambu-green":"text-white"}`,onClick:()=>{e("subtype",H),C(!1),M("")},children:H},H)),k&&!jw.some(H=>H.toLowerCase()===k.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",k),C(!1),M("")},children:g("inventory.useCustomBrand",{brand:k})})]})]}),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:O,min:0,onFocus:()=>ee(!0),onChange:H=>L(H.target.value),onBlur:()=>{ee(!1);const H=O.trim(),J=Number(H);if(!H||!Number.isFinite(J)||J<0){L(String(t.label_weight));return}const A=Math.round(J);e("label_weight",A),L(String(A))}}),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:H=>{const J=Math.max(1,Math.min(100,parseInt(H.target.value)||1));p(J)}})]})]})}function zst(t){const e=t.split(/[\s,]+/).map(i=>i.trim().replace(/^#/,"")).filter(Boolean),a=[],n=[];for(const i of e)(i.length===6||i.length===8)&&/^[0-9a-fA-F]+$/.test(i)?a.push(i.toLowerCase()):n.push(i);return{value:a.join(","),invalid:n}}function Sde({formData:t,updateField:e,recentColors:a,onColorUsed:n,catalogColors:i}){const{t:s}=vt(),[o,l]=y.useState(!1),[c,d]=y.useState(""),u=t.rgba.replace("#","").substring(0,6),[m,p]=y.useState(u);y.useEffect(()=>{p(u)},[u]);const f=M=>u.toUpperCase()===M.toUpperCase(),g=(M,q,I,O)=>{if(e("rgba",M.toUpperCase()+"FF"),e("color_name",q),I!==void 0){const L=I??"";C(L),T([]),j.current=L,e("extra_colors",L)}O!==void 0&&e("effect_type",O??""),n({name:q,hex:M})},w=y.useMemo(()=>{if(i.length===0)return[];const M=t.brand?.trim(),q=t.material?.toLowerCase().trim(),I=t.subtype?.toLowerCase().trim();if(!M&&!q)return[];const O=M?M.toLowerCase().split(/[\s\-_]+/).filter(ee=>ee.length>=2):[],L=ee=>{if(O.length===0)return!0;const Q=ee.toLowerCase();return O.some(le=>Q.includes(le))};if(M&&!q){const ee=i.filter(Q=>L(Q.manufacturer));if(ee.length>0)return ee.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 X=q&&I?`${q} ${I}`:"";if(X){const ee=i.filter(le=>L(le.manufacturer)&&le.material?.toLowerCase()===X);if(ee.length>0)return ee.map(le=>({name:le.color_name,hex:le.hex_color.replace("#","").substring(0,6),manufacturer:le.manufacturer,material:typeof le.material=="string"?le.material:void 0,extra_colors:le.extra_colors??null,effect_type:le.effect_type??null}));const Q=X.replace(/\+$/,"");if(Q!==X){const le=i.filter(de=>L(de.manufacturer)&&de.material?.toLowerCase()===Q);if(le.length>0)return le.map(de=>({name:de.color_name,hex:de.hex_color.replace("#","").substring(0,6),manufacturer:de.manufacturer,material:typeof de.material=="string"?de.material:void 0}))}}if(q){const ee=i.filter(Q=>L(Q.manufacturer)&&(!Q.material||Q.material.toLowerCase().startsWith(q)));if(ee.length>0)return ee.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]),b=y.useMemo(()=>{if(!c)return w;if(w.length===0)return[];const M=c.toLowerCase();return w.filter(I=>I.name.toLowerCase().includes(M)||(I.manufacturer?.toLowerCase().includes(M)??!1)||(I.material?.toLowerCase().includes(M)??!1))},[c,w]),x=w.length>0,S=y.useMemo(()=>c?FX.filter(M=>M.name.toLowerCase().includes(c.toLowerCase())):o?FX:hde,[c,o]),[N,C]=y.useState(t.extra_colors),[P,T]=y.useState([]),j=y.useRef(t.extra_colors);y.useEffect(()=>{t.extra_colors!==j.current&&(C(t.extra_colors),T([]),j.current=t.extra_colors)},[t.extra_colors]);const F=y.useMemo(()=>pj({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]),k=M=>{if(C(M),!M.trim()){T([]),j.current="",e("extra_colors","");return}const{value:q,invalid:I}=zst(M);T(I),j.current=q,e("extra_colors",q)};return r.jsxs("div",{className:"space-y-3",children:[r.jsx("div",{className:"h-10 rounded-lg border border-bambu-dark-tertiary",style:F,"data-testid":"color-preview-banner"}),a.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(Za,{className:"w-3 h-3"}),r.jsx("span",{children:s("inventory.recentColors")})]}),r.jsx("div",{className:"flex flex-wrap gap-1.5",children:a.map(M=>r.jsx("button",{type:"button",onClick:()=>g(M.hex,M.name),className:`w-6 h-6 rounded border-2 transition-all hover:scale-110 ${f(M.hex)?"border-bambu-green ring-1 ring-bambu-green/30 scale-110":"border-bambu-dark-tertiary"}`,style:{backgroundColor:`#${M.hex}`},title:M.name},M.hex))})]}),r.jsxs("div",{className:"relative",children:[r.jsx(fr,{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:M=>d(M.target.value)})]}),x?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:[b.map(M=>r.jsx("button",{type:"button",onClick:()=>g(M.hex,M.name,M.extra_colors,M.effect_type),className:`w-6 h-6 rounded border-2 transition-all hover:scale-110 hover:z-20 relative group ${f(M.hex)?"border-bambu-green ring-1 ring-bambu-green/30 scale-110":"border-bambu-dark-tertiary"}`,style:{backgroundColor:`#${M.hex}`},title:M.manufacturer&&M.material?`${M.name} (${M.manufacturer} — ${M.material})`:M.manufacturer?`${M.name} (${M.manufacturer})`:M.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:M.manufacturer&&M.material?`${M.name} (${M.manufacturer} — ${M.material})`:M.manufacturer?`${M.name} (${M.manufacturer})`:M.name})},`${M.hex}-${M.name}-${M.manufacturer??""}`)),b.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(al,{className:"w-3 h-3"})]}):r.jsxs(r.Fragment,{children:[s("inventory.showAll")," ",r.jsx(Da,{className:"w-3 h-3"})]})})]}),r.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[S.map(M=>r.jsx("button",{type:"button",onClick:()=>g(M.hex,M.name),className:`w-6 h-6 rounded border-2 transition-all hover:scale-110 hover:z-20 relative group ${f(M.hex)?"border-bambu-green ring-1 ring-bambu-green/30 scale-110":"border-bambu-dark-tertiary"}`,style:{backgroundColor:`#${M.hex}`},title:M.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:M.name})},M.hex)),S.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:M=>e("color_name",M.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:m.toUpperCase(),onChange:M=>{const q=M.target.value.replace("#","").replace(/[^0-9A-Fa-f]/g,"").toUpperCase(),I=q.length>6?q.substring(0,6):q;p(I),I.length===6&&e("rgba",I+"FF")},onBlur:()=>{if(m.length>0&&m.length<6){const M=m.padEnd(6,"0");p(M),e("rgba",M+"FF")}}})]}),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:M=>{const q=M.target.value.replace("#","").toUpperCase();e("rgba",q+"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:N,onChange:M=>k(M.target.value),"data-testid":"extra-colors-input"}),P.length>0&&r.jsx("p",{className:"text-xs text-red-400 mt-1",children:s("inventory.extraColorsInvalid",{tokens:P.join(", ")})}),!P.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(Ig,{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:M=>e("effect_type",M.target.value),"data-testid":"effect-type-select",children:nO.map(M=>r.jsx("option",{value:M.value,children:s(M.labelKey)},M.value||"none"))}),r.jsx(bU,{rgba:t.rgba,extraColors:t.extra_colors,effectType:t.effect_type,subtype:t.subtype,effectSize:"preview",className:"w-10 h-10",shape:"square"})]})]})]})]})}function Ust({catalog:t,value:e,onChange:a,catalogId:n,onCatalogIdChange:i}){const{t:s}=vt(),[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(n){const b=t.find(x=>x.id===n);if(b&&b.weight===e)return}w.length===1?i(w[0].id):w.length===0&&n!==null&&i(null)},[e,t,n,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(n){const w=t.find(b=>b.id===n);if(w)return w.name}return f.length>0?f[0].name:""},[o,c,n,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(ZZ,{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 ${(n?w.id===n:w.weight===e)?"bg-bambu-green/10 text-bambu-green":"text-white"}`,onClick:()=>{i(w.id),a(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&&a(b)}}),r.jsx("span",{className:"text-bambu-gray text-sm",children:"g"})]})]})]})}function kde({formData:t,updateField:e,spoolCatalog:a,currencySymbol:n,availableCategories:i,globalLowStockThreshold:s,spoolmanMode:o=!1}){const{t:l}=vt(),{showToast:c}=na(),[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(Ust,{catalog:a,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 j=Math.round(C),F=Math.max(0,Math.min(t.label_weight,j-t.core_weight));e("weight_used",Math.max(0,t.label_weight-F)),u(String(j))},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:n}),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,n.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 Bst({filaments:t,isLoading:e,selectedId:a,onSelect:n}){const{t:i}=vt(),[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===a)??null,[t,a]);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=>{n(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(qr,{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(Da,{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===a?"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 _de({formData:t,printersWithCalibrations:e,selectedProfiles:a,setSelectedProfiles:n,expandedPrinters:i,setExpandedPrinters:s}){const{t:o}=vt(),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"}`;n(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=>P3(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}`)}}n(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=>P3(w,t)).length:p,0),m=(p,f)=>{const g=`${p.id}:${f.cali_idx}:${f.extruder_id??"null"}`,w=a.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(Ig,{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=>P3(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(Da,{className:"w-4 h-4 text-bambu-gray"}):r.jsx(Hn,{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)})}),a.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:a.size})," ",o("inventory.profilesSelected")]})})]})}function qst(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 Hst={completed:"text-bambu-green",failed:"text-red-400",aborted:"text-yellow-400"};function $st({spoolId:t}){const{t:e}=vt(),a=ta(),{showToast:n}=na(),{data:i,isLoading:s}=Qe({queryKey:["spool-usage",t],queryFn:()=>re.getSpoolUsageHistory(t)}),o=ot({mutationFn:()=>re.clearSpoolUsageHistory(t),onSuccess:()=>{a.invalidateQueries({queryKey:["spool-usage",t]}),n(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(Za,{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(je,{variant:"ghost",size:"sm",onClick:()=>o.mutate(),disabled:o.isPending,className:"text-xs text-bambu-gray hover:text-red-400",children:[r.jsx(ea,{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:qst(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:Hst[l.status]||"text-bambu-gray",children:l.status})]})]},l.id))})]})}const LX={tag_uid:null,tray_uuid:null,tag_type:null,data_origin:null};function Vst({isOpen:t,onClose:e,spool:a,mode:n,printersWithCalibrations:i=[],currencySymbol:s,onSpoolsCreated:o,spoolmanMode:l=!1,spoolsQueryKey:c=["inventory-spools"]}){const{t:d}=vt(),u=ta(),{showToast:m}=na(),p=n==="edit",f=n==="copy",[g,w]=y.useState(sO),[b,x]=y.useState({}),[S,N]=y.useState("filament"),[C,P]=y.useState(!1),[T,j]=y.useState(!1),[F,k]=y.useState(!1),[M,q]=y.useState(1),[I,O]=y.useState(!1),[L,X]=y.useState(!1),[ee,Q]=y.useState([]),[le,de]=y.useState(""),[me,Z]=y.useState([]),[ce,he]=y.useState([]),[ue,xe]=y.useState([]),[H,J]=y.useState([]),[A,E]=y.useState([]),[B,W]=y.useState([]),[z,ie]=y.useState(new Set),[U,G]=y.useState(new Set),K=i.length>0?i:B,Y=z.size,{data:se=[],isLoading:oe,error:fe}=Qe({queryKey:["spoolman-inventory-filaments"],queryFn:()=>re.getSpoolmanInventoryFilaments(),enabled:l&&t,staleTime:6e4,retry:!1});y.useEffect(()=>{E(yde())},[]),y.useEffect(()=>{t&&((async()=>{X(!0);try{const at=await re.getCloudStatus();if(O(at.is_authenticated),at.is_authenticated){const nt=await re.getFilamentPresets();Q(nt)}}catch(at){console.error("Failed to fetch cloud presets:",at),O(!1)}finally{X(!1)}})(),l||re.getSpoolCatalog().then(Z).catch(console.error),re.getColorCatalog().then(J).catch(console.error),re.getLocalPresets().then(at=>he(at.filament)).catch(console.error),re.getBuiltinFilaments().then(xe).catch(console.error),i.length===0&&(async()=>{try{const at=await re.getPrinters(),nt=await Promise.all(at.map(Bt=>re.getPrinterStatus(Bt.id).catch(()=>null))),At=[];for(let Bt=0;Bt({cali_idx:ut.slot_id,filament_id:ut.filament_id,setting_id:ut.setting_id||"",name:ut.name,k_value:parseFloat(ut.k_value)||0,n_coef:parseFloat(ut.n_coef)||0,extruder_id:ut.extruder_id,nozzle_diameter:ut.nozzle_diameter}))}catch{}At.push({printer:{...gt,connected:Xt},calibrations:ia})}W(At)}catch(at){console.error("Failed to fetch printer calibrations:",at)}})())},[t,i.length]);const ae=y.useMemo(()=>bde(ee,new Set,ce,ue),[ee,ce,ue]),pe=y.useMemo(()=>{const Pe=gde(ee,ce),at=H.map(At=>At.manufacturer?.trim()).filter(At=>!!At),nt=new Set([...Pe,...at]);return Array.from(nt).sort((At,Bt)=>At.localeCompare(Bt))},[ee,ce,H]),$=y.useMemo(()=>{const Pe=H.map(nt=>nt.material?.trim()).filter(nt=>!!nt),at=new Set([...pde,...Pe]);return Array.from(at).sort((nt,At)=>nt.localeCompare(At))},[H]),R=y.useMemo(()=>{const Pe=[];for(const at of H){const nt=at.manufacturer?.trim(),At=at.material?.trim();nt&&At&&Pe.push({brand:nt,material:At})}for(const at of ee){const nt=rf(at.name);nt.brand&&nt.material&&Pe.push({brand:nt.brand,material:nt.material})}for(const at of ce){const nt=rf(at.name),At=at.filament_vendor?.trim()||nt.brand,Bt=nt.material;At&&Bt&&Pe.push({brand:At,material:Bt})}return Pe},[ee,H,ce]),ne=y.useMemo(()=>{const Pe=new Map;for(const at of R){const nt=at.brand.toLowerCase(),At=at.material.toLowerCase();Pe.has(nt)||Pe.set(nt,new Set),Pe.get(nt).add(At)}return Pe},[R]),be=y.useMemo(()=>{const Pe=new Map;for(const at of R){const nt=at.brand.toLowerCase(),At=at.material.toLowerCase();Pe.has(At)||Pe.set(At,new Set),Pe.get(At).add(nt)}return Pe},[R]),ve=y.useMemo(()=>{if(!g.material)return pe;const Pe=g.material.toLowerCase(),at=be.get(Pe);return!at||at.size===0?pe:pe.filter(nt=>at.has(nt.toLowerCase()))},[pe,g.material,be]),ke=y.useMemo(()=>{if(!g.brand)return $;const Pe=g.brand.toLowerCase(),at=ne.get(Pe);return!at||at.size===0?$:$.filter(nt=>at.has(nt.toLowerCase()))},[$,g.brand,ne]),ye=y.useMemo(()=>xde(g.slicer_filament,ae),[g.slicer_filament,ae]);y.useEffect(()=>{if(t){if(a){const Pe=a.rgba&&/^[0-9A-Fa-f]{8}$/.test(a.rgba)?a.rgba:"808080FF";if(w({material:a.material||"",subtype:a.subtype||"",brand:a.brand||"",color_name:a.color_name_is_synthesized?"":a.color_name||"",rgba:Pe,extra_colors:a.extra_colors||"",effect_type:a.effect_type||"",label_weight:a.label_weight||1e3,core_weight:a.core_weight||250,core_weight_catalog_id:a.core_weight_catalog_id??null,weight_used:f?0:a.weight_used||0,slicer_filament:a.slicer_filament||"",note:a.note||"",cost_per_kg:a.cost_per_kg??null,category:a.category||"",low_stock_threshold_pct:a.low_stock_threshold_pct??null,storage_location:a.storage_location||"",spoolman_filament_id:null}),de(a.slicer_filament_name||a.slicer_filament||""),a.k_profiles&&a.k_profiles.length>0){const at=new Set;for(const nt of a.k_profiles)nt.cali_idx!==null&&nt.cali_idx!==void 0&&at.add(`${nt.printer_id}:${nt.cali_idx}:${nt.extruder??"null"}`);ie(at)}else ie(new Set)}else w(sO),de(""),ie(new Set),k(!1),q(1);x({}),N("filament"),P(!1),j(!1)}},[t,a,n,f]),y.useEffect(()=>{t&&K.length>0&&G(new Set(K.map(Pe=>String(Pe.printer.id))))},[t,K]);const ge=(Pe,at)=>{const nt=Dst.has(Pe);l&&nt&&g.spoolman_filament_id!==null&&m(d("inventory.spoolmanFilamentUnlinked"),"info"),w(At=>({...At,[Pe]:at,...l&&nt&&At.spoolman_filament_id!==null?{spoolman_filament_id:null}:{}})),Pe==="weight_used"&&P(!0),Pe==="storage_location"&&j(!0),b[Pe]&&x(At=>({...At,[Pe]:void 0}))},Me=Pe=>{const at=Pe.material||"",nt=Pe.name||"",At=at&&nt.startsWith(at)?nt.slice(at.length).trim():nt,Bt=(Pe.color_hex??"").replace("#","").toUpperCase(),gt=/^[0-9A-F]{6}$/.test(Bt)?Bt:"808080";w(Qt=>({...Qt,spoolman_filament_id:Pe.id,material:at,subtype:At,brand:Pe.vendor?.name||"",rgba:`${gt}FF`,color_name:Pe.color_name||"",label_weight:Pe.weight??Qt.label_weight})),m(d("inventory.spoolmanFilamentSelected"),"success")},Be=Pe=>{E(at=>vde(Pe,at))},Le=ot({mutationFn:Pe=>l?re.createSpoolmanInventorySpool(Pe):re.createSpool(Pe),onSuccess:async Pe=>{Pe?.id&&!await Fe(Pe.id)||(await u.invalidateQueries({queryKey:c}),o&&o([Pe]),m(d("inventory.spoolCreated"),"success"),e())},onError:Pe=>{Pe instanceof cs&&Pe.status===503?m(d("inventory.spoolmanUnreachable"),"error"):m(d("inventory.saveFailed"),"error")}}),Oe=ot({mutationFn:({data:Pe,qty:at})=>l?re.bulkCreateSpoolmanInventorySpools(Pe,at):re.bulkCreateSpools(Pe,at),onSuccess:async Pe=>{const at=l&&"created"in Pe?Pe:null,nt=at?at.created:Pe;if(z.size>0)for(const At of nt)await Fe(At.id);await u.invalidateQueries({queryKey:c}),o&&o(nt),at&&at.failed_count>0?m(d("inventory.spoolsPartiallyCreated",{created:nt.length,total:at.requested_count}),"warning"):m(d("inventory.spoolsCreated",{count:nt.length}),"success"),e()},onError:Pe=>{Pe instanceof cs&&Pe.status===503?m(d("inventory.spoolmanUnreachable"),"error"):m(d("inventory.saveFailed"),"error")}}),Re=ot({mutationFn:Pe=>l?re.updateSpoolmanInventorySpool(a.id,Pe):re.updateSpool(a.id,Pe),onSuccess:async()=>{a?.id&&!await Fe(a.id)||(await u.invalidateQueries({queryKey:c}),m(d("inventory.spoolUpdated"),"success"),e())},onError:Pe=>{Pe instanceof cs&&Pe.status===503?m(d("inventory.spoolmanUnreachable"),"error"):m(d("inventory.saveFailed"),"error")}}),Ke=ot({mutationFn:()=>l?re.updateSpoolmanInventorySpool(a.id,LX):re.updateSpool(a.id,LX),onSuccess:async()=>{await u.invalidateQueries({queryKey:c}),m(d("inventory.rfidCleared","RFID tag cleared"),"success"),e()},onError:Pe=>{Pe instanceof cs&&Pe.status===503?m(d("inventory.spoolmanUnreachable"),"error"):m(d("inventory.tagClearFailed"),"error")}}),{data:Ue}=Qe({queryKey:["spool-assignments"],queryFn:()=>re.getAssignments(),enabled:t&&p&&!l}),{data:lt}=Qe({queryKey:["spoolman-slot-assignments-all"],queryFn:()=>re.getSpoolmanSlotAssignments(),enabled:t&&p&&l}),Ee=(()=>{if(a)return l?lt?.find(Pe=>Pe.spoolman_spool_id===a.id):Ue?.find(Pe=>Pe.spool_id===a.id)})(),{data:st}=Qe({queryKey:["inventory-spools"],queryFn:()=>re.getSpools(!0),enabled:t}),{data:Ne}=Qe({queryKey:["settings"],queryFn:re.getSettings,enabled:t}),Ze=(()=>{const Pe=new Set;for(const at of st??[]){const nt=at.category?.trim();nt&&Pe.add(nt)}return Array.from(Pe).sort((at,nt)=>at.localeCompare(nt))})(),Ye=Ne?.low_stock_threshold??20,Te=ot({mutationFn:async()=>{if(!Ee)throw new Error("No assignment");if(l){if(!a)throw new Error("No spool");await re.unassignSpoolmanSlot(a.id);return}await re.unassignSpool(Ee.printer_id,Ee.ams_id,Ee.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:Pe=>{m(Pe.message,"error")}}),Fe=async Pe=>{const at=l?re.saveSpoolmanKProfiles:re.saveSpoolKProfiles;if(z.size===0)try{return await at(Pe,[]),!0}catch(Bt){return console.error("Failed to save K-profiles:",Bt),m(d("inventory.kProfileSaveFailed"),"warning"),!1}const nt=[];let At=0;for(const Bt of z){const[gt,Qt,Xt]=Bt.split(":"),ia=parseInt(gt),da=parseInt(Qt),ut=Xt==="null"?0:parseInt(Xt),_t=K.find(Ct=>Ct.printer.id===ia);if(_t){const Ct=_t.calibrations.find(dt=>dt.cali_idx===da);Ct?nt.push({printer_id:ia,extruder:ut,nozzle_diameter:Ct.nozzle_diameter||"0.4",k_value:Ct.k_value,name:Ct.name||null,cali_idx:Ct.cali_idx,setting_id:Ct.setting_id||null}):At++}else At++}if(At>0)return console.error(`saveKProfiles: ${At} profile key(s) could not be resolved`,Array.from(z)),m(d("inventory.kProfileSaveFailed"),"warning"),!1;if(nt.length>0)try{return await at(Pe,nt),!0}catch(Bt){return console.error("Failed to save K-profiles:",Bt),m(d("inventory.kProfileSaveFailed"),"warning"),!1}return!0};if(y.useEffect(()=>{if(!t)return;const Pe=at=>{at.key==="Escape"&&e()};return document.addEventListener("keydown",Pe),()=>document.removeEventListener("keydown",Pe)},[t,e]),!t)return null;const et=()=>{const Pe=mde(g,F,l);if(!Pe.isValid){x(Pe.errors),(Pe.errors.slicer_filament||Pe.errors.material||Pe.errors.brand||Pe.errors.subtype)&&N("filament");return}const at=ye?.displayName||le||null,nt={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:at,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)&&(nt.weight_used=g.weight_used),(!p||T)&&(nt.storage_location=g.storage_location||null),p?Re.mutate(nt):M>1?Oe.mutate({data:nt,qty:M}):Le.mutate(nt)},We=Le.isPending||Oe.isPending||Re.isPending||Ke.isPending||Te.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.jsxs("h2",{className:"text-lg font-semibold text-white flex items-baseline gap-2",children:[d(p?"inventory.editSpool":f?"inventory.copySpool":"inventory.addSpool"),p&&a&&r.jsxs("span",{className:"text-sm font-mono text-bambu-gray",children:["#",a.id]})]}),r.jsx("button",{onClick:e,className:"p-1 text-bambu-gray hover:text-white rounded transition-colors",children:r.jsx($t,{className:"w-5 h-5"})})]}),n==="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(Nc,{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:()=>{k(!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(LS,{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(Wfe,{className:"w-4 h-4"}),d("inventory.paProfileTab"),Y>0&&r.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded-full bg-bambu-green/20 text-bambu-green",children:Y})]})]}),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(Bst,{filaments:se,isLoading:oe,selectedId:g.spoolman_filament_id,onSelect:Me})}),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(wde,{formData:g,updateField:ge,cloudAuthenticated:I,loadingCloudPresets:L,presetInputValue:le,setPresetInputValue:de,selectedPresetOption:ye,filamentOptions:ae,availableBrands:ve,availableMaterials:ke,quickAdd:F,quantity:M,onQuantityChange:q,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(Sde,{formData:g,updateField:ge,recentColors:A,onColorUsed:Be,catalogColors:H})]}),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(kde,{formData:g,updateField:ge,spoolCatalog:me,currencySymbol:s,availableCategories:Ze,globalLowStockThreshold:Ye,spoolmanMode:l})]}),p&&a&&!l&&r.jsx("div",{children:r.jsx($st,{spoolId:a.id})})]}):r.jsx(_de,{formData:g,updateField:ge,printersWithCalibrations:K,selectedProfiles:z,setSelectedProfiles:ie,expandedPrinters:U,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(je,{variant:"secondary",onClick:()=>Ke.mutate(),disabled:We||!a?.tag_uid,children:[r.jsx(Ym,{className:"w-4 h-4"}),d("inventory.clearRfid","Clear RFID Tag")]}),r.jsxs(je,{variant:"secondary",onClick:()=>Te.mutate(),disabled:We||!Ee,children:[r.jsx(su,{className:"w-4 h-4"}),d("inventory.unassignSpool","Unassign")]})]}),r.jsxs("div",{className:"flex gap-2 ml-auto",children:[r.jsx(je,{variant:"secondary",onClick:e,children:d("common.cancel")}),r.jsx(je,{onClick:et,disabled:We,children:We?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(fs,{className:"w-4 h-4"}),d(p?"common.save":f?"inventory.copySpool":"inventory.addSpool")]})})]})]})]})]})}function Gst({isOpen:t,onClose:e,columns:a,defaultColumns:n,onSave:i}){const{t:s}=vt(),[o,l]=y.useState(a),[c,d]=y.useState(null),u=y.useRef(null);if(y.useEffect(()=>{t&&l(a.map(C=>({...C})))},[t,a]),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,j)=>j===C?{...T,visible:!T.visible}:T))},p=(C,P)=>{P<0||P>=o.length||l(T=>{const j=[...T],[F]=j.splice(C,1);return j.splice(P,0,F),j})},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(n.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(Tt,{className:"w-full max-w-md max-h-[80vh] flex flex-col",onClick:C=>C.stopPropagation(),children:r.jsxs(Mt,{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(Mh,{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(al,{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(Da,{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(Ml,{className:"w-4 h-4"}):r.jsx(db,{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(je,{variant:"secondary",onClick:x,className:"mr-auto",children:[r.jsx(vs,{className:"w-4 h-4"}),s("inventory.reset")]}),r.jsx(je,{variant:"secondary",onClick:e,children:s("inventory.cancel")}),r.jsx(je,{onClick:S,children:s("inventory.applyChanges")})]})]})})})}const Wst=[{value:"ams_holder_74x33",i18nKey:"amsHolderSmall",fallbackLabel:"AMS holder — small (74 × 33 mm)",fallbackHint:"Single label per page; matches the printable label from MakerWorld model 752566 (AMS Filament Label Holder)."},{value:"ams_holder_75x55",i18nKey:"amsHolderLarge",fallbackLabel:"AMS holder — large (75 × 55 mm)",fallbackHint:"Single label per page; fits the cardstock-insert variant of the AMS Filament Label Holder. Roomy enough for swatch, brand, material, ID, and QR code."},{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 Kst(t){const e=window.URL.createObjectURL(t);if(!window.open(e,"_blank","noopener,noreferrer")){const n=document.createElement("a");n.href=e,n.download="bambuddy-labels.pdf",document.body.appendChild(n),n.click(),document.body.removeChild(n)}setTimeout(()=>window.URL.revokeObjectURL(e),6e4)}function Qst(t){if(!t)return{backgroundColor:"#808080"};const e=t.replace(/^#/,"").slice(0,6);return e.length===6?{backgroundColor:`#${e}`}:{backgroundColor:"#808080"}}function Yst(t){const e=t.color_name??`${t.material}${t.subtype?` ${t.subtype}`:""}`,a=t.brand?` · ${t.brand}`:"";return`${e}${a}`}function Xst(t){return[t.color_name,t.material,t.subtype,t.brand,`#${t.id}`].filter(Boolean).join(" ").toLowerCase()}function RX(t){if(!t)return[1,0];const e=t.replace(/^#/,"").slice(0,6);if(e.length!==6)return[1,0];const a=parseInt(e.slice(0,2),16),n=parseInt(e.slice(2,4),16),i=parseInt(e.slice(4,6),16);if([a,n,i].some(Number.isNaN))return[1,0];const s=a/255,o=n/255,l=i/255,c=Math.max(s,o,l),d=Math.min(s,o,l),u=(c+d)/2,m=c-d;if((m===0?0:m/(1-Math.abs(2*u-1)))<.1)return[1,u];let f=0;return c===s?f=(o-l)/m%6:c===o?f=(l-s)/m+2:f=(s-o)/m+4,f=f*60,f<0&&(f+=360),[0,f]}function Zst({isOpen:t,onClose:e,availableSpools:a,initialSelectedIds:n,spoolmanMode:i}){const{t:s}=vt(),{showToast:o}=na(),[l,c]=y.useState(null),[d,u]=y.useState(new Set),[m,p]=y.useState(""),[f,g]=y.useState(""),[w,b]=y.useState("id");y.useEffect(()=>{if(t){const I=new Set(a.map(O=>O.id));u(new Set(n.filter(O=>I.has(O)))),p(""),g(""),b("id"),c(null)}},[t]);const x=y.useMemo(()=>{const I=[...a];return w==="color"?(I.sort((O,L)=>{const X=RX(O.rgba),ee=RX(L.rgba);return X[0]!==ee[0]?X[0]-ee[0]:X[1]!==ee[1]?X[1]-ee[1]:O.id-L.id}),I):(I.sort((O,L)=>O.id-L.id),I)},[a,w]),S=y.useMemo(()=>{const I=new Set;for(const O of x)O.material&&I.add(O.material.toUpperCase());return[...I].sort()},[x]),N=y.useMemo(()=>{const I=m.trim().toLowerCase();return x.filter(O=>!(f&&(O.material||"").toUpperCase()!==f||I&&!Xst(O).includes(I)))},[x,m,f]),C=N.length>0&&N.every(I=>d.has(I.id));if(!t)return null;const P=d.size,T=P===0;function j(I){u(O=>{const L=new Set(O);return L.has(I)?L.delete(I):L.add(I),L})}function F(){u(I=>{const O=new Set(I);for(const L of N)O.add(L.id);return O})}function k(){u(I=>{const O=new Set(I);for(const L of N)O.delete(L.id);return O})}function M(){u(new Set)}async function q(I){if(T||l)return;const O=x.filter(L=>d.has(L.id)).map(L=>L.id);c(I);try{const L=i?await re.printSpoolmanSpoolLabels({spool_ids:O,template:I}):await re.printSpoolLabels({spool_ids:O,template:I});Kst(L),e()}catch(L){const X=L instanceof Error?L.message:String(L);o(s("inventory.labels.error","Could not generate labels: {{msg}}",{msg:X}),"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(gr,{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")}),P>0&&r.jsxs("span",{className:"text-sm text-bambu-gray",children:["(",s("inventory.labels.selectedCount","{{count}} selected",{count:P}),")"]})]}),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($t,{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(fr,{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:I=>p(I.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"})]}),S.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")}),S.map(I=>r.jsx("button",{type:"button",onClick:()=>g(I),className:`px-2 py-0.5 text-xs rounded-full border transition ${f===I?"bg-bambu-green text-bambu-dark border-bambu-green":"bg-bambu-dark text-bambu-gray border-bambu-dark-tertiary hover:border-bambu-gray"}`,children:I},I))]}),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.sortBy.label")}),r.jsx("button",{type:"button",onClick:()=>b("id"),className:`px-2 py-0.5 text-xs rounded-full border transition ${w==="id"?"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.sortBy.id")}),r.jsx("button",{type:"button",onClick:()=>b("color"),className:`px-2 py-0.5 text-xs rounded-full border transition ${w==="color"?"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.sortBy.color")})]})]}),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:C?k:F,disabled:N.length===0,className:"text-bambu-green hover:underline disabled:opacity-50 disabled:no-underline disabled:cursor-not-allowed",children:C?s("inventory.labels.deselectVisible","Deselect visible"):s("inventory.labels.selectVisible","Select all visible ({{count}})",{count:N.length})}),r.jsx("button",{type:"button",onClick:M,disabled:P===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:N.length===0?r.jsx("div",{className:"text-center text-sm text-bambu-gray py-6",children:x.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:N.map(I=>{const O=d.has(I.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:[O?r.jsx(ws,{className:"w-4 h-4 text-bambu-green shrink-0"}):r.jsx(lo,{className:"w-4 h-4 text-bambu-gray shrink-0"}),r.jsx("input",{type:"checkbox",checked:O,onChange:()=>j(I.id),className:"sr-only"}),r.jsx("span",{className:"w-4 h-4 rounded border border-black/20 shrink-0",style:Qst(I.rgba)}),r.jsx("span",{className:"flex-1 min-w-0 truncate text-sm text-white",children:Yst(I)}),r.jsxs("span",{className:"text-xs font-mono text-bambu-gray shrink-0",children:["#",I.id]})]})},I.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:Wst.map(I=>{const O=l===I.value,L=s(`inventory.labels.templates.${I.i18nKey}.label`,I.fallbackLabel),X=s(`inventory.labels.templates.${I.i18nKey}.hint`,I.fallbackHint);return r.jsxs("button",{disabled:T||l!==null,onClick:()=>q(I.value),title:`${L} — ${X}`,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:L}),r.jsx("div",{className:"text-xs text-bambu-gray mt-0.5 truncate",children:X})]}),O&&r.jsx(pt,{className:"w-4 h-4 animate-spin text-bambu-green shrink-0"})]},I.value)})}),r.jsx("div",{className:"flex justify-end gap-2 px-5 py-2 border-t border-bambu-dark-tertiary",children:r.jsx(je,{variant:"secondary",onClick:e,disabled:l!==null,children:s("common.cancel","Cancel")})})]})]})}function Jst(t){const e=t[0];let a=0,n=0,i=0;for(const s of t)a+=s.label_weight,n+=s.weight_used,i+=s.core_weight;return{...e,label_weight:a,weight_used:n,core_weight:i}}function IX(t){return`${t.material}|${t.subtype||""}|${t.brand||""}|${t.color_name||""}|${t.rgba||""}|${t.extra_colors||""}|${t.effect_type||""}|${t.label_weight}`}const Nde="bambuddy-inventory-columns",QN=[{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 eot(){try{const t=localStorage.getItem(Nde);if(t){const e=JSON.parse(t),a=new Set(QN.map(o=>o.id)),n=new Set(e.map(o=>o.id)),i=e.filter(o=>a.has(o.id)),s=QN.filter(o=>!n.has(o.id));return[...i,...s]}}catch{}return QN.map(t=>({...t}))}function tot(t){try{localStorage.setItem(Nde,JSON.stringify(t))}catch{}}function iu(t,e=!1){return e&&t>=1e3?`${(t/1e3).toFixed(1)}kg`:`${Math.round(t)}g`}const aot={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 T3(t,e="system"){if(!t)return"-";const a=Qa(t);return a?oL(a,e):"-"}const rot={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")},oO={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:T3(t.created_at,e)}),encode_time:({spool:t,dateFormat:e})=>r.jsx("span",{className:"text-sm text-bambu-gray",children:T3(t.encode_time,e)}),last_used_time:({spool:t,dateFormat:e})=>r.jsx("span",{className:"text-sm text-bambu-gray",children:t.last_used?T3(t.last_used,e):"Never"}),rgba:({spool:t})=>r.jsx("div",{className:"flex items-center justify-center",children:r.jsx(bU,{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:FT(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 a=e[t.id];if(!a)return r.jsx("span",{className:"text-sm text-bambu-gray",children:"-"});const n=a.printer_name||`Printer ${a.printer_id}`,i=a.ams_id===254||a.ams_id===255,s=!i&&a.ams_id>=128,o=hk(a.ams_id,a.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:[n," ",o,a.ams_label?` (${a.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:iu(t.label_weight)}),net:({remaining:t})=>r.jsx("span",{className:"text-sm text-white",children:iu(t)}),gross:({spool:t,remaining:e})=>r.jsx("span",{className:"text-sm text-bambu-gray",children:iu(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?iu(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 a=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:a?.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 a=t.last_scale_weight;if(a==null)return r.jsx("span",{className:"text-sm text-bambu-gray/50",title:"No scale measurement",children:"-"});const n=t.core_weight||0,i=Math.max(0,t.label_weight-t.weight_used)+n;let s,o;a0?`+${Math.round(s)}`:`${Math.round(s)}`,c=o?`Scale: ${Math.round(a)}g Calculated: ${Math.round(i)}g Difference: ${l}g (within tolerance)`:`Scale: ${Math.round(a)}g diff --git a/static/index.html b/static/index.html index bcbebf677..5e0884c85 100644 --- a/static/index.html +++ b/static/index.html @@ -26,7 +26,7 @@ - +