diff --git a/CHANGELOG.md b/CHANGELOG.md index 08fe3f665..327e77c5b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,7 @@ All notable changes to Bambuddy will be documented in this file. - **Printer Card Shows Plate Name on Multi-Plate Prints** ([#881](https://github.com/maziggy/bambuddy/issues/881)) — When two printers were running different plates of the same multi-plate 3MF, the Printers page cards displayed the same file name on both and gave no visual way to tell them apart. The Queue view already showed the plate name by querying the archive's plate list; the Printers page didn't have that linkage. The `GET /printers/{id}/status` endpoint now returns `current_archive_id` (resolved by matching the MQTT `subtask_id` against `PrintArchive.subtask_id`, the same bridge introduced in #972 for restart-resume) and `current_plate_id` (parsed from the MQTT `gcode_file` path by a new shared `parse_plate_id` helper that's also used by the WebSocket push path, so plate transitions within a running print reflect immediately instead of waiting 30 s for the next REST poll). The card fetches plate metadata via the same `api.getArchivePlates()` call the Queue page uses — shared React Query cache keeps it cheap across polls — and renders the actual plate name (or a "Plate N" fallback) only when the source 3MF is multi-plate, so single-plate prints stay noise-free. Falls back to the previous `plate_(\d+).gcode` regex when there's no archive linkage (e.g. prints started directly from the printer LCD). Regression tests cover the plate-id extraction across Bambu Studio path shapes and the label-override precedence in `formatPrintName`. Thanks to @stringham for the follow-up and screenshot. ### Fixed +- **Single Malformed `rgba` Bricks the Entire Filaments Inventory Page** ([#1055](https://github.com/maziggy/bambuddy/issues/1055)) — A user's Filaments page went blank and "Add Spool" became a no-op with no visible error. The backend was returning HTTP 500 from `GET /api/v1/inventory/spools` with `fastapi.exceptions.ResponseValidationError: rgba → 'FFFFFFF' should match pattern '^[0-9A-Fa-f]{8}$'` — a single legacy spool row had a 7-char rgba (missing one trailing `F`) and Pydantic's strict pattern on `SpoolResponse` refused to serialize the whole list because of it. Root cause spans three layers: (1) `SpoolUpdate` had no rgba pattern constraint, so PATCH calls could plant malformed values straight into the DB (`SpoolCreate` did validate, but only on initial create); (2) the `ColorSection` hex input's onChange ternary `val.length <= 6 ? 'FF' : ''` silently emitted 7-char strings for 5-char or 7-char typed input (5 chars + `FF` alpha = 7 chars; 7 chars got no alpha appended at all), which then flowed to the unvalidated PATCH endpoint; (3) `SpoolResponse` inherited the same pattern as `SpoolCreate`, so any malformed row already in the DB exploded the entire list endpoint on serialize even though write-side validation was the right place for the check. Fixed on all three layers: `SpoolUpdate.rgba` now carries the same `^[0-9A-Fa-f]{8}$` pattern as `SpoolCreate`, so PATCH requests with malformed rgba are rejected with 422 at the boundary. The hex input always emits a fully-formed 8-char RRGGBBAA on every keystroke — 8-char paste passes through, 7-char drops the stray char, shorter input is right-padded with `'0'` and given FF alpha. `SpoolResponse.rgba` is now an unconstrained `Optional[str]`: the pattern belongs on request schemas where Pydantic can reject bad input, not on responses where it turns a single bad row into a total page failure. A legacy malformed row still appears in the UI (the color just renders as whatever browser default applies) but the user can see, edit, and delete it instead of having to hand-edit SQLite. Backend tests cover all three schema contracts (16 cases across `SpoolCreate` accept/reject, `SpoolUpdate` accept/reject, `SpoolResponse` lenient-tolerance on 7-char / null / garbage). Frontend tests cover the hex-input normalization for every input length 0–8 plus non-hex strip-and-pad. Thanks to @fdsghy4a for the end-to-end debugging and for locating the exact malformed row in their DB. - **Printer-Card "Print" Button Leaves Transient Copy in File Manager** ([#730](https://github.com/maziggy/bambuddy/issues/730)) — The "Print" button on a printer card (and the equivalent drag-drop-onto-card flow) was silently uploading the chosen file into the Library file manager as a side effect before printing. Root cause is structural: the frontend opened `FileUploadModal` to persist the file as a `LibraryFile`, then `PrintModal` dispatched a library print through `POST /library/files/{id}/print`, which uses the LibraryFile as the source for both the archive copy and the FTP upload to the printer. When the dispatch finished, both the `LibraryFile` row and its disk file in `data/library/` were left behind, so every one-off Direct-Print accumulated an unwanted File Manager entry that the user had to find and delete manually. The other three print entry points are untouched: Archive "Reprint" never involved the library, and File Manager "Print" / Project Detail "Print" are paths where the user deliberately put the file in the library, so their entries are preserved. `POST /library/files/{id}/print` now accepts an optional `cleanup_library_after_dispatch` boolean. When true, `_run_print_library_file` stages the LibraryFile row for deletion in the same transaction as the archive insert (so a mid-flight FTP or `start_print` failure rolls back both at once, leaving no orphan), commits together, then unlinks the library disk file and thumbnail from disk after commit succeeds. External library files (`is_external = True`, pointing at user-managed folders outside Bambuddy's control) are never touched regardless of the flag. The Printers-page Direct-Print flow is the only caller that sends `true`; every other `api.printLibraryFile` call site leaves the flag unset so default-False preserves their library entries. Added two unit tests at the enqueue level (default-false + flag-propagates-true), two integration tests at the endpoint level (default-false + forwards-true + cleanup flag never leaks into the MQTT options dict), and two frontend tests on `PrintModal` guarding that `cleanupLibraryAfterDispatch` only forwards when explicitly set — so future File Manager / Project Detail entry points can't accidentally inherit the Direct-Print semantics. Thanks to @3823u44238 for flagging the surprising side effect. - **Direct / File Manager / Library Prints Still Unattributed to User** ([#730](https://github.com/maziggy/bambuddy/issues/730)) — The 0.2.3.1 fix (commit `f03d0c4c`) plumbed the authenticated user from `POST /library/files/{id}/print` into the background-dispatch job object, but the dispatcher itself never read it back out: `_run_print_library_file` called `ArchiveService.archive_print()` without the `created_by_id` parameter and never called `printer_manager.set_current_print_user()`. Net effect: direct prints from the printer-card "Print" button, File Manager prints, and Library prints all continued to land archives with `created_by_id = NULL` (invisible to the per-user stats filter), and the post-print email notification had no user to target. The dispatcher now forwards `job.requested_by_user_id` to the archive at creation time and registers the current-print user after `start_print` succeeds — matching the reprint path's behaviour. Reprint-from-Archive attribution is a separate bug (the reprint reuses the source archive row as-is, so a NULL `created_by_id` stays NULL) and is tracked on #730. Thanks to @3823u44238 for the thorough end-to-end retest. - **Spoolman Iframe Blocked by CSP on HTTP Instances** ([#1054](https://github.com/maziggy/bambuddy/issues/1054)) — The Filament tab showed a blank page with a brief Spoolman flash on reload. Browser console reported `Content-Security-Policy: The page's settings blocked the loading of a resource (frame-src) at http://:7912/spool because it violates the following directive: "frame-src 'self' https:"`. Root cause: commit `53a70e37` (#995) tightened the CSP to allow external sidebar iframes but only whitelisted `https:`, overlooking that self-hosted services on LANs — Spoolman, OctoPrint, etc. — almost always run over plain HTTP. The `frame-src` directive now allows `http:` as well (`frame-src 'self' http: https:`), matching the `connect-src 'self' ws: wss:` pattern already used for WebSockets. `frame-ancestors 'none'` still prevents Bambuddy itself from being framed cross-origin. Thanks to @saint-hh for reporting. diff --git a/backend/app/schemas/spool.py b/backend/app/schemas/spool.py index f226a5e7c..df63fe8a8 100644 --- a/backend/app/schemas/spool.py +++ b/backend/app/schemas/spool.py @@ -41,7 +41,7 @@ class SpoolUpdate(BaseModel): material: str | None = None subtype: str | None = None color_name: str | None = None - rgba: str | None = None + rgba: str | None = Field(None, pattern=r"^[0-9A-Fa-f]{8}$") brand: str | None = None label_weight: int | None = None core_weight: int | None = None @@ -82,6 +82,11 @@ class SpoolKProfileResponse(SpoolKProfileBase): class SpoolResponse(SpoolBase): id: int + # rgba is intentionally unconstrained on the response side: the write paths + # (SpoolCreate, SpoolUpdate) enforce the 8-char hex pattern, but legacy rows + # or data sourced from AMS firmware / backups may carry malformed values. + # A single bad row must not 500 the entire inventory list endpoint (#1055). + rgba: str | None = None added_full: bool | None = None last_used: datetime | None = None encode_time: datetime | None = None diff --git a/backend/tests/unit/test_spool_schemas_rgba.py b/backend/tests/unit/test_spool_schemas_rgba.py new file mode 100644 index 000000000..5c710361c --- /dev/null +++ b/backend/tests/unit/test_spool_schemas_rgba.py @@ -0,0 +1,131 @@ +"""Schema validation tests for the spool rgba field (#1055). + +Three guarantees to lock in: +1. SpoolCreate and SpoolUpdate must reject malformed rgba (short, long, non-hex) + on the write path — this is the "add a check" the reporter asked for. +2. SpoolResponse must NOT validate rgba on the read path: a single legacy row + with a 7-char rgba (as in #1055) must not 500 the entire inventory list. +3. Valid 8-char hex must continue to round-trip through all three schemas. +""" + +import pytest +from pydantic import ValidationError + +from backend.app.schemas.spool import SpoolCreate, SpoolUpdate + + +class TestSpoolCreateRgbaValidation: + """Write-path validation on the create schema.""" + + def test_accepts_valid_8char_hex(self): + spool = SpoolCreate(material="PLA", rgba="FF00AAFF") + assert spool.rgba == "FF00AAFF" + + def test_accepts_lowercase_hex(self): + spool = SpoolCreate(material="PLA", rgba="ff00aaff") + assert spool.rgba == "ff00aaff" + + def test_accepts_null_rgba(self): + spool = SpoolCreate(material="PLA", rgba=None) + assert spool.rgba is None + + def test_rejects_7char_rgba(self): + """#1055 repro: a 7-char 'FFFFFFF' must not be acceptable on create.""" + with pytest.raises(ValidationError, match="rgba"): + SpoolCreate(material="PLA", rgba="FFFFFFF") + + def test_rejects_6char_rgba(self): + """Plain RRGGBB without alpha must be rejected — frontend appends FF.""" + with pytest.raises(ValidationError, match="rgba"): + SpoolCreate(material="PLA", rgba="FF0000") + + def test_rejects_non_hex_char(self): + with pytest.raises(ValidationError, match="rgba"): + SpoolCreate(material="PLA", rgba="FFZZ00FF") + + +class TestSpoolUpdateRgbaValidation: + """Write-path validation on the update schema — the gap that let #1055 happen. + + Before the fix, SpoolUpdate.rgba was a bare `str | None` so a PATCH could + plant a 7-char value straight into the DB. That row then caused a 500 on + the next GET because SpoolResponse enforced the pattern at serialize time. + """ + + def test_accepts_valid_8char_hex(self): + update = SpoolUpdate(rgba="00FF00FF") + assert update.rgba == "00FF00FF" + + def test_accepts_null_rgba(self): + update = SpoolUpdate(rgba=None) + assert update.rgba is None + + def test_accepts_missing_rgba(self): + """Partial updates — rgba not present in payload — must still be valid.""" + update = SpoolUpdate(material="PETG") + assert update.rgba is None + + def test_rejects_7char_rgba(self): + """#1055 repro: PATCH must reject the exact pattern that bricked the reporter.""" + with pytest.raises(ValidationError, match="rgba"): + SpoolUpdate(rgba="FFFFFFF") + + def test_rejects_9char_rgba(self): + with pytest.raises(ValidationError, match="rgba"): + SpoolUpdate(rgba="FFFFFFFFF") + + def test_rejects_non_hex_char(self): + with pytest.raises(ValidationError, match="rgba"): + SpoolUpdate(rgba="FFGG00FF") + + +class TestSpoolResponseRgbaLeniency: + """Read-path leniency — a legacy bad row must never 500 the list endpoint. + + Before the fix, SpoolResponse inherited the pattern from SpoolBase so a + single 7-char rgba in the DB blew up the whole inventory listing. The + response schema now treats rgba as an unconstrained Optional[str] — write + validation is where the pattern belongs; responses must tolerate whatever + is already persisted. + """ + + # SpoolResponse requires id + timestamps so it's easier to test via a + # minimal dict payload than by constructing a full instance. + @staticmethod + def _make_response_kwargs(**overrides): + from datetime import datetime + + base = { + "id": 1, + "material": "PLA", + "created_at": datetime.fromisoformat("2026-01-01T00:00:00"), + "updated_at": datetime.fromisoformat("2026-01-01T00:00:00"), + } + base.update(overrides) + return base + + def test_tolerates_7char_rgba_on_serialize(self): + """This is the #1055 bug fixed: malformed legacy rgba must serialize cleanly.""" + from backend.app.schemas.spool import SpoolResponse + + response = SpoolResponse(**self._make_response_kwargs(rgba="FFFFFFF")) + assert response.rgba == "FFFFFFF" + + def test_tolerates_null_rgba(self): + from backend.app.schemas.spool import SpoolResponse + + response = SpoolResponse(**self._make_response_kwargs(rgba=None)) + assert response.rgba is None + + def test_tolerates_non_hex_rgba(self): + """Even completely garbage rgba shouldn't crash the endpoint.""" + from backend.app.schemas.spool import SpoolResponse + + response = SpoolResponse(**self._make_response_kwargs(rgba="not-hex-at-all")) + assert response.rgba == "not-hex-at-all" + + def test_passes_valid_rgba_through(self): + from backend.app.schemas.spool import SpoolResponse + + response = SpoolResponse(**self._make_response_kwargs(rgba="FF00AAFF")) + assert response.rgba == "FF00AAFF" diff --git a/frontend/src/__tests__/components/SpoolFormModal.test.tsx b/frontend/src/__tests__/components/SpoolFormModal.test.tsx index a72de1ae9..9336a62c6 100644 --- a/frontend/src/__tests__/components/SpoolFormModal.test.tsx +++ b/frontend/src/__tests__/components/SpoolFormModal.test.tsx @@ -348,6 +348,73 @@ describe('SpoolFormModal weightTouched', () => { expect(payload).toHaveProperty('cost_per_kg', null); }); + it('normalizes a malformed legacy rgba on edit-form load so PATCH is not rejected (#1055)', async () => { + // #1055 regression guard: a spool with a legacy 7-char rgba (e.g. 'FFFFFFF') + // was editable in the UI but any save 422'd because SpoolUpdate now enforces + // the 8-char pattern. The form must sanitize the loaded value to a valid + // default so users can edit unrelated fields without being forced to fix + // a color they may not even have noticed was broken. + const spoolWithBadRgba: InventorySpool = { + ...existingSpool, + rgba: 'FFFFFFF', // 7 chars — the exact #1055 trigger pattern + }; + + render( + + ); + + await waitFor(() => { + expect(screen.getByText('Edit Spool')).toBeInTheDocument(); + }); + + const saveButton = screen.getByRole('button', { name: /save/i }); + fireEvent.click(saveButton); + + await waitFor(() => { + expect(api.updateSpool).toHaveBeenCalledTimes(1); + }); + + const [, payload] = vi.mocked(api.updateSpool).mock.calls[0]; + // The PATCH payload must carry a valid 8-char rgba — never the raw 7-char + // value loaded from the stale DB row. + expect(payload).toHaveProperty('rgba'); + expect(typeof (payload as { rgba: unknown }).rgba).toBe('string'); + expect((payload as { rgba: string }).rgba).toMatch(/^[0-9A-Fa-f]{8}$/); + }); + + it('preserves a valid existing rgba on edit (no forced default)', async () => { + // Sanity: the normalization only kicks in for malformed values. A valid + // 8-char rgba must round-trip untouched so untouched edits don't quietly + // reset a user's chosen color. + render( + + ); + + await waitFor(() => { + expect(screen.getByText('Edit Spool')).toBeInTheDocument(); + }); + + const saveButton = screen.getByRole('button', { name: /save/i }); + fireEvent.click(saveButton); + + await waitFor(() => { + expect(api.updateSpool).toHaveBeenCalledTimes(1); + }); + + const [, payload] = vi.mocked(api.updateSpool).mock.calls[0]; + expect((payload as { rgba: string }).rgba).toBe('FF0000FF'); + }); + it('displays correct catalog name when duplicates exist', async () => { const spoolWithCatalogId: InventorySpool = { ...existingSpool, diff --git a/frontend/src/__tests__/components/spool-form/ColorSectionHexInput.test.tsx b/frontend/src/__tests__/components/spool-form/ColorSectionHexInput.test.tsx new file mode 100644 index 000000000..6caccebac --- /dev/null +++ b/frontend/src/__tests__/components/spool-form/ColorSectionHexInput.test.tsx @@ -0,0 +1,119 @@ +/** + * Regression tests for the ColorSection hex input normalization (#1055). + * + * The original bug: typing 5 hex chars on the RRGGBB field produced a 7-char + * rgba ("FFFFF" + "FF" alpha = 7 chars); typing 7 chars left the 7-char string + * unpadded. Either way the value passed frontend validation, survived a backend + * PATCH (SpoolUpdate had no pattern constraint), and then bricked the entire + * Filaments page because SpoolResponse enforced the 8-char pattern on serialize + * and one bad row 500'd the whole list endpoint. + * + * The input now emits a valid 8-char RRGGBBAA on every keystroke: shorter input + * is right-padded with '0' and given FF alpha; 7-char input drops the stray 7th + * char; 8-char paste passes through unchanged. + * + * These tests drive the onChange handler directly (via fireEvent.change) rather + * than userEvent.type so each assertion exercises a specific input length. The + * component itself is a controlled input whose displayed value derives from + * formData.rgba.substring(0, 6), so the real-world UX of typing one char at a + * time is quirkier than the handler contract — but the handler contract is + * what this regression guards. + */ + +import { describe, it, expect, vi } from 'vitest'; +import { render, screen, fireEvent } from '@testing-library/react'; +import { I18nextProvider } from 'react-i18next'; +import i18n from '../../../i18n'; +import { ColorSection } from '../../../components/spool-form/ColorSection'; +import { defaultFormData } from '../../../components/spool-form/types'; + +type UpdateField = ( + key: K, + value: (typeof defaultFormData)[K], +) => void; + +function renderColorSection(overrides: Partial = {}) { + const updateField = vi.fn() as ReturnType & UpdateField; + const formData = { ...defaultFormData, ...overrides }; + + render( + + + , + ); + + const hexInput = screen.getByPlaceholderText('RRGGBB') as HTMLInputElement; + return { hexInput, updateField }; +} + +function lastRgba(updateField: ReturnType): string | undefined { + const rgbaCalls = updateField.mock.calls.filter(([key]) => key === 'rgba'); + return rgbaCalls.at(-1)?.[1] as string | undefined; +} + +describe('ColorSection hex input normalization (#1055)', () => { + it('pads a 6-char RRGGBB to 8-char RRGGBBAA with FF alpha', () => { + const { hexInput, updateField } = renderColorSection(); + fireEvent.change(hexInput, { target: { value: 'FF0000' } }); + expect(lastRgba(updateField)).toBe('FF0000FF'); + }); + + it('passes an 8-char RRGGBBAA paste through unchanged', () => { + const { hexInput, updateField } = renderColorSection(); + fireEvent.change(hexInput, { target: { value: '00112233' } }); + expect(lastRgba(updateField)).toBe('00112233'); + }); + + it('drops the stray 7th char — the exact #1055 trigger pattern', () => { + const { hexInput, updateField } = renderColorSection(); + fireEvent.change(hexInput, { target: { value: 'FFFFFFF' } }); + // Previously emitted "FFFFFFF" (7 chars) verbatim. Must now be 8 chars. + const rgba = lastRgba(updateField); + expect(rgba).toBe('FFFFFFFF'); + expect(rgba).toMatch(/^[0-9A-F]{8}$/); + }); + + it('pads a 5-char input to 8 chars instead of emitting a 7-char rgba', () => { + // 5-char + 'FF' alpha = 7 chars was the other #1055 trigger pattern. + // Right-pad RGB to 6 with '0' so the output is always 8 chars. + const { hexInput, updateField } = renderColorSection(); + fireEvent.change(hexInput, { target: { value: 'FFFFF' } }); + const rgba = lastRgba(updateField); + expect(rgba).toBe('FFFFF0FF'); + expect(rgba).toMatch(/^[0-9A-F]{8}$/); + }); + + it('pads any partial input to exactly 8 chars — never 7', () => { + // The essential invariant: for every legal input length (0..8), the + // emitted rgba must be 8 chars. Anything else risks reintroducing #1055. + const { hexInput, updateField } = renderColorSection(); + for (const input of ['', 'F', 'FF', 'FFF', 'FFFF', 'FFFFF', 'FFFFFF', 'FFFFFFF', 'FFFFFFFF']) { + updateField.mockClear(); + fireEvent.change(hexInput, { target: { value: input } }); + const rgba = lastRgba(updateField); + expect(rgba).toBeDefined(); + expect(rgba!.length).toBe(8); + expect(rgba).toMatch(/^[0-9A-F]{8}$/); + } + }); + + it('ignores input past 8 chars (no updateField call)', () => { + const { hexInput, updateField } = renderColorSection({ rgba: 'FFFFFFFF' }); + updateField.mockClear(); + fireEvent.change(hexInput, { target: { value: '0011223344' } }); + expect(updateField.mock.calls.filter(([k]) => k === 'rgba')).toHaveLength(0); + }); + + it('strips non-hex characters before normalizing', () => { + // '#FF00ZZ' → strip '#' and non-hex → 'FF00' (4 chars) → pad to 6 + FF alpha + const { hexInput, updateField } = renderColorSection(); + fireEvent.change(hexInput, { target: { value: '#FF00ZZ' } }); + expect(lastRgba(updateField)).toBe('FF0000FF'); + }); +}); diff --git a/frontend/src/components/SpoolFormModal.tsx b/frontend/src/components/SpoolFormModal.tsx index 94618e387..573dfba44 100644 --- a/frontend/src/components/SpoolFormModal.tsx +++ b/frontend/src/components/SpoolFormModal.tsx @@ -253,12 +253,22 @@ export function SpoolFormModal({ useEffect(() => { if (isOpen) { if (spool) { + // Legacy rows may carry a malformed rgba (e.g. the 7-char 'FFFFFFF' + // from #1055 before the create/update pattern was enforced). The + // backend SpoolUpdate schema rejects non-8-char hex on PATCH, so + // re-submitting a malformed value would 422 every edit on that spool + // — even edits that don't touch color. Normalize on load: any value + // that isn't exactly 8 hex chars falls back to the default, so the + // user can save unrelated fields (weight, material, note) without + // first being forced to fix a color they may not even be aware is + // broken. Saving also purges the bad value from the DB. + const validRgba = spool.rgba && /^[0-9A-Fa-f]{8}$/.test(spool.rgba) ? spool.rgba : '808080FF'; setFormData({ material: spool.material || '', subtype: spool.subtype || '', brand: spool.brand || '', color_name: spool.color_name || '', - rgba: spool.rgba || '808080FF', + rgba: validRgba, label_weight: spool.label_weight || 1000, core_weight: spool.core_weight || 250, core_weight_catalog_id: spool.core_weight_catalog_id ?? null, diff --git a/frontend/src/components/spool-form/ColorSection.tsx b/frontend/src/components/spool-form/ColorSection.tsx index b44f2f6ab..d6c4cc9ab 100644 --- a/frontend/src/components/spool-form/ColorSection.tsx +++ b/frontend/src/components/spool-form/ColorSection.tsx @@ -298,8 +298,18 @@ export function ColorSection({ placeholder="RRGGBB" value={currentHex.toUpperCase()} onChange={(e) => { - const val = e.target.value.replace('#', '').replace(/[^0-9A-Fa-f]/g, ''); - if (val.length <= 8) updateField('rgba', val.toUpperCase() + (val.length <= 6 ? 'FF' : '')); + const val = e.target.value.replace('#', '').replace(/[^0-9A-Fa-f]/g, '').toUpperCase(); + if (val.length > 8) return; + // Normalize to a valid 8-char RRGGBBAA on every keystroke so + // the backend never receives a malformed rgba (#1055). 8-char + // paste passes through; 7-char drops the stray typo; anything + // shorter is right-padded with '0' to a full RGB triplet and + // given FF alpha. Prior logic emitted 3/5/7-char strings mid- + // typing that PATCH would accept (SpoolUpdate was unchecked) + // and later 500 the list endpoint on response serialization. + const rgba = + val.length === 8 ? val : val.length === 7 ? val.substring(0, 6) + 'FF' : val.padEnd(6, '0') + 'FF'; + updateField('rgba', rgba); }} /> diff --git a/static/assets/index-BskdRxdi.js b/static/assets/index-CASdUlGi.js similarity index 99% rename from static/assets/index-BskdRxdi.js rename to static/assets/index-CASdUlGi.js index 0a3cdfd51..4bd7eee76 100644 --- a/static/assets/index-BskdRxdi.js +++ b/static/assets/index-CASdUlGi.js @@ -8721,7 +8721,7 @@ Accuracy: ${t.time_accuracy.toFixed(0)}%`:t.actual_time_seconds?`Actual: ${ws(t. `+n+"]";if(typeof t=="object"){const r=Object.entries(t);return r.length===0?"{}":`{ `+r.map(([s,o])=>n+" "+JSON.stringify(s)+": "+lO(o,e+1)).join(`, `)+` -`+n+"}"}return String(t)}function $nt({setting:t,onClose:e,onDeleted:n,onDuplicate:r,onEdit:i,hasPermission:s,t:o}){const{showToast:l}=hn(),c=nn(),[d,u]=w.useState(!1),{data:m,isLoading:p}=Xe({queryKey:["cloudSettingDetail",t.setting_id],queryFn:()=>de.getCloudSettingDetail(t.setting_id)}),f=it({mutationFn:()=>de.deleteCloudSetting(t.setting_id),onSuccess:()=>{l(o("profiles.presets.toast.deleted")),c.invalidateQueries({queryKey:["cloudSettings"]}),n()},onError:b=>l(b.message,"error")}),y=Kw(t.setting_id),v=b5(t.name,m?.setting?.inherits);return a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:a.jsx(Tt,{className:"w-full max-w-3xl max-h-[90vh] flex flex-col overflow-hidden",children:a.jsxs(Mt,{className:"p-0 flex flex-col min-h-0 flex-1",children:[a.jsxs("div",{className:"flex-shrink-0 flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("h2",{className:"text-xl font-semibold text-white truncate",children:t.name}),y&&a.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")})]}),a.jsxs("div",{className:"flex items-center gap-2 mt-1 text-sm text-bambu-gray",children:[a.jsx("span",{className:"capitalize",children:o(`profiles.presets.types.${t.type}`)}),v.printer&&a.jsxs(a.Fragment,{children:[a.jsx("span",{children:"•"}),a.jsx("span",{children:v.printer})]})]})]}),a.jsx("button",{onClick:e,className:"p-2 text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary rounded-lg transition-colors",children:a.jsx(Ht,{className:"w-5 h-5"})})]}),a.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto p-4",children:p?a.jsx("div",{className:"flex items-center justify-center py-16",children:a.jsx(pt,{className:"w-8 h-8 text-bambu-green animate-spin"})}):m?a.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:lO(m)}):a.jsx("div",{className:"text-center py-16 text-bambu-gray",children:o("profiles.presets.failedToLoadDetails")})}),d?a.jsxs("div",{className:"flex-shrink-0 p-4 border-t border-bambu-dark-tertiary bg-red-500/5",children:[a.jsxs("div",{className:"flex items-center gap-2 mb-3 text-red-400",children:[a.jsx(Dn,{className:"w-5 h-5"}),a.jsx("span",{className:"font-medium",children:o("profiles.presets.deleteConfirm")})]}),a.jsx("p",{className:"text-sm text-bambu-gray mb-4",children:o("profiles.presets.deleteWarning",{name:t.name})}),a.jsxs("div",{className:"flex gap-2",children:[a.jsx(De,{variant:"secondary",onClick:()=>u(!1),disabled:f.isPending,className:"flex-1",children:o("common.cancel")}),a.jsxs(De,{variant:"danger",onClick:()=>f.mutate(),disabled:f.isPending,className:"flex-1",children:[f.isPending?a.jsx(pt,{className:"w-4 h-4 animate-spin"}):a.jsx(en,{className:"w-4 h-4"}),o("common.delete")]})]})]}):a.jsx("div",{className:"flex-shrink-0 p-4 border-t border-bambu-dark-tertiary",children:a.jsxs("div",{className:"flex gap-2",children:[a.jsx(De,{variant:"secondary",onClick:e,className:"flex-1",children:o("common.close")}),a.jsxs(De,{variant:"secondary",onClick:r,disabled:!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.presets.noDuplicatePermission"),children:[a.jsx(qs,{className:"w-4 h-4"}),o("profiles.presets.duplicate")]}),y&&a.jsxs(a.Fragment,{children:[a.jsxs(De,{variant:"secondary",onClick:i,disabled:p||!m||!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.presets.noEditPermission"),children:[a.jsx(ci,{className:"w-4 h-4"}),o("common.edit")]}),a.jsx(De,{variant:"danger",onClick:()=>u(!0),disabled:!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.presets.noDeletePermission"),children:a.jsx(en,{className:"w-4 h-4"})})]})]})})]})})})}function zle(){try{const t=localStorage.getItem("bambusy_preset_templates");return t?JSON.parse(t):[]}catch{return[]}}function Ule(t){localStorage.setItem("bambusy_preset_templates",JSON.stringify(t))}function Vnt({onClose:t,onApply:e,t:n}){const{showToast:r}=hn(),[i,s]=w.useState(zle),[o,l]=w.useState("all"),[c,d]=w.useState(null),[u,m]=w.useState(""),[p,f]=w.useState(""),[y,v]=w.useState("{}"),[b,g]=w.useState(null),[_,C]=w.useState(null),P=o==="all"?i:i.filter(Q=>Q.type===o),N=Q=>{s(Q),Ule(Q)},A=Q=>{const L=i.filter(te=>te.id!==Q);N(L),C(null),r(n("profiles.templates.toast.deleted"))},T=Q=>{d(Q.id),m(Q.name),f(Q.description),v(JSON.stringify(Q.settings,null,2)),g(null)},F=()=>{if(!(!c||!u.trim()))try{const Q=JSON.parse(y),L=i.map(te=>te.id===c?{...te,name:u.trim(),description:p.trim(),settings:Q}:te);N(L),d(null),r(n("profiles.templates.toast.updated"))}catch(Q){g(Q.message)}},k=()=>{d(null),m(""),f(""),v("{}"),g(null)},D=Q=>{const L=i.map(te=>te.id===Q?{...te,showInModal:!te.showInModal}:te);N(L)},H={filament:{label:n("profiles.presets.types.filament"),icon:qP,color:"text-amber-400"},print:{label:n("profiles.presets.types.process"),icon:Ud,color:"text-blue-400"},printer:{label:n("profiles.presets.types.printer"),icon:Er,color:"text-purple-400"}},z=_?i.find(Q=>Q.id===_):null;return w.useEffect(()=>{const Q=L=>{L.key==="Escape"&&(_?C(null):c?k():t())};return window.addEventListener("keydown",Q),()=>window.removeEventListener("keydown",Q)},[_,c,t]),a.jsxs("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:[z&&a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-60",children:a.jsx(Tt,{className:"w-full max-w-md",children:a.jsxs(Mt,{className:"p-6",children:[a.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[a.jsx("div",{className:"p-2 bg-red-500/20 rounded-lg",children:a.jsx(Dn,{className:"w-6 h-6 text-red-400"})}),a.jsxs("div",{children:[a.jsx("h3",{className:"text-lg font-semibold text-white",children:n("profiles.templates.deleteTitle")}),a.jsx("p",{className:"text-sm text-bambu-gray",children:n("profiles.templates.deleteWarning")})]})]}),a.jsx("p",{className:"text-white mb-6",children:n("profiles.templates.deleteConfirm",{name:z.name})}),a.jsxs("div",{className:"flex gap-2",children:[a.jsx(De,{variant:"secondary",onClick:()=>C(null),className:"flex-1",children:n("common.cancel")}),a.jsxs(De,{onClick:()=>A(_),className:"flex-1 bg-red-500 hover:bg-red-600",children:[a.jsx(en,{className:"w-4 h-4"}),n("common.delete")]})]})]})})}),a.jsx(Tt,{className:"w-full max-w-2xl max-h-[80vh] flex flex-col",children:a.jsxs(Mt,{className:"p-0 flex flex-col h-full",children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx($x,{className:"w-5 h-5 text-amber-400"}),n("profiles.templates.title")]}),a.jsx("button",{onClick:t,className:"text-bambu-gray hover:text-white",children:a.jsx(Ht,{className:"w-5 h-5"})})]}),a.jsxs("div",{className:"flex items-center gap-2 p-4 border-b border-bambu-dark-tertiary",children:[a.jsx("span",{className:"text-sm text-bambu-gray",children:n("profiles.templates.typeFilter")}),["all","filament","print","printer"].map(Q=>a.jsx("button",{onClick:()=>l(Q),className:`px-3 py-1 text-sm rounded-lg transition-colors ${o===Q?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:Q==="all"?n("common.all"):H[Q].label},Q))]}),a.jsx("div",{className:"flex-1 overflow-y-auto p-4",children:P.length===0?a.jsxs("div",{className:"text-center py-12 text-bambu-gray",children:[a.jsx($x,{className:"w-12 h-12 mx-auto mb-4 opacity-30"}),a.jsx("p",{children:n("profiles.templates.noTemplates")}),a.jsx("p",{className:"text-sm mt-1",children:n("profiles.templates.createFirst")})]}):a.jsx("div",{className:"space-y-2",children:P.map(Q=>{const L=H[Q.type],te=L.icon;return c===Q.id?a.jsxs("div",{className:"p-4 bg-bambu-dark rounded-lg border border-bambu-green",children:[a.jsxs("div",{className:"grid grid-cols-2 gap-3 mb-3",children:[a.jsx("input",{type:"text",value:u,onChange:ie=>m(ie.target.value),placeholder:n("profiles.templates.namePlaceholder"),className:"px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none",autoFocus:!0}),a.jsx("input",{type:"text",value:p,onChange:ie=>f(ie.target.value),placeholder:n("profiles.templates.descriptionPlaceholder"),className:"px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none"})]}),a.jsxs("div",{className:"mb-3",children:[a.jsx("label",{className:"text-xs text-bambu-gray mb-1 block",children:n("profiles.templates.settingsJson")}),a.jsx("textarea",{value:y,onChange:ie=>{v(ie.target.value),g(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&&a.jsx("p",{className:"text-xs text-red-400 mt-1",children:b})]}),a.jsxs("div",{className:"flex gap-2",children:[a.jsxs(De,{size:"sm",onClick:F,disabled:!u.trim(),children:[a.jsx(_s,{className:"w-4 h-4"}),"Save"]}),a.jsx(De,{size:"sm",variant:"secondary",onClick:k,children:"Cancel"})]})]},Q.id):a.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:[a.jsx(te,{className:`w-5 h-5 ${L.color} flex-shrink-0`}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("p",{className:"text-sm font-medium text-white",children:Q.name}),a.jsx("p",{className:"text-xs text-bambu-gray truncate",children:Q.description})]}),a.jsx("span",{className:"text-xs text-bambu-gray-dark px-2 py-1 bg-bambu-dark-secondary rounded",children:n("profiles.templates.fieldsCount",{count:Object.keys(Q.settings).length})}),a.jsx("button",{onClick:()=>D(Q.id),className:`p-1 transition-colors ${Q.showInModal?"text-bambu-green hover:text-bambu-green/70":"text-bambu-gray hover:text-white"}`,title:Q.showInModal?n("profiles.templates.shownInModals"):n("profiles.templates.hiddenInModals"),children:Q.showInModal?a.jsx(vl,{className:"w-4 h-4"}):a.jsx(Og,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>e(Q),className:"px-3 py-1 text-xs bg-bambu-green/20 text-bambu-green rounded hover:bg-bambu-green/30 transition-colors",children:n("profiles.templates.apply")}),a.jsx("button",{onClick:()=>T(Q),className:"p-1 text-bambu-gray hover:text-white",title:n("common.edit"),children:a.jsx(ci,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>C(Q.id),className:"p-1 text-bambu-gray hover:text-red-400",title:n("common.delete"),children:a.jsx(en,{className:"w-4 h-4"})})]},Q.id)})})})]})})]})}function Ble({onClose:t,leftPreset:e,rightPreset:n,leftLabel:r,rightLabel:i,t:s}){const[o,l]=w.useState("changes"),[c,d]=w.useState(""),u=w.useMemo(()=>{const y=new Set([...Object.keys(e),...Object.keys(n)]),v=[];for(const b of y){if(b==="inherits"||b==="version")continue;const g=e[b],_=n[b],C=b in e,P=b in n;let N;!C&&P?N="added":C&&!P?N="removed":JSON.stringify(g)!==JSON.stringify(_)?N="changed":N="same",v.push({key:b,left:g,right:_,status:N})}return v.sort((b,g)=>{const _={changed:0,added:1,removed:2,same:3};return _[b.status]!==_[g.status]?_[b.status]-_[g.status]:b.key.localeCompare(g.key)})},[e,n]),m=w.useMemo(()=>{let y=[...u];if(o==="changes"&&(y=y.filter(v=>v.status!=="same")),c){const v=c.toLowerCase();y=y.filter(b=>b.key.toLowerCase().includes(v)||String(b.left).toLowerCase().includes(v)||String(b.right).toLowerCase().includes(v))}return y},[u,o,c]),p=w.useMemo(()=>({added:u.filter(y=>y.status==="added").length,removed:u.filter(y=>y.status==="removed").length,changed:u.filter(y=>y.status==="changed").length,same:u.filter(y=>y.status==="same").length}),[u]),f=y=>{if(y===void 0)return"—";if(y===null)return"null";if(Array.isArray(y))return y.length===0?"[]":y.length===1?String(y[0]):y.join(", ");if(typeof y=="object")return JSON.stringify(y);const v=String(y);if(v.includes("\\n")||v.length>100){const b=v.split("\\n").length;if(b>1)return`[${b} lines of G-code/script]`;if(v.length>100)return v.substring(0,100)+"…"}return v};return w.useEffect(()=>{const y=v=>{v.key==="Escape"&&t()};return window.addEventListener("keydown",y),()=>window.removeEventListener("keydown",y)},[t]),a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:a.jsx(Tt,{className:"w-full max-w-4xl max-h-[85vh] flex flex-col overflow-hidden",children:a.jsxs(Mt,{className:"p-0 flex flex-col min-h-0 flex-1",children:[a.jsxs("div",{className:"flex-shrink-0 flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(Cx,{className:"w-5 h-5 text-blue-400"}),s("profiles.diff.title")]}),a.jsx("button",{onClick:t,className:"text-bambu-gray hover:text-white",children:a.jsx(Ht,{className:"w-5 h-5"})})]}),a.jsxs("div",{className:"flex-shrink-0 grid grid-cols-2 gap-4 p-4 border-b border-bambu-dark-tertiary bg-bambu-dark",children:[a.jsxs("div",{className:"text-center",children:[a.jsx("span",{className:"text-sm text-bambu-gray",children:s("profiles.diff.left")}),a.jsx("p",{className:"text-white font-medium truncate",children:r})]}),a.jsxs("div",{className:"text-center",children:[a.jsx("span",{className:"text-sm text-bambu-gray",children:s("profiles.diff.right")}),a.jsx("p",{className:"text-white font-medium truncate",children:i})]})]}),a.jsxs("div",{className:"flex-shrink-0 flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-4 text-sm",children:[a.jsxs("span",{className:"flex items-center gap-1 text-green-400",children:[a.jsx(sr,{className:"w-3.5 h-3.5"}),p.added," ",s("profiles.diff.added")]}),a.jsxs("span",{className:"flex items-center gap-1 text-red-400",children:[a.jsx(kN,{className:"w-3.5 h-3.5"}),p.removed," ",s("profiles.diff.removed")]}),a.jsxs("span",{className:"flex items-center gap-1 text-amber-400",children:[a.jsx(rF,{className:"w-3.5 h-3.5"}),p.changed," ",s("profiles.diff.changed")]}),a.jsxs("span",{className:"flex items-center gap-1 text-bambu-gray",children:[a.jsx(jM,{className:"w-3.5 h-3.5"}),p.same," ",s("profiles.diff.same")]})]}),a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsxs("div",{className:"relative",children:[a.jsx(Pr,{className:"absolute left-2 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),a.jsx("input",{type:"text",value:c,onChange:y=>d(y.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&&a.jsxs("div",{className:"flex rounded overflow-hidden border border-bambu-dark-tertiary",children:[a.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")}),a.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")})]})]})]}),a.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto",children:m.length===0?a.jsxs("div",{className:"text-center py-12 text-bambu-gray",children:[a.jsx(jM,{className:"w-12 h-12 mx-auto mb-4 opacity-30"}),a.jsx("p",{children:s(o==="changes"?"profiles.diff.noDifferences":"profiles.diff.noFieldsMatch")})]}):a.jsxs("table",{className:"w-full",children:[a.jsx("thead",{className:"sticky top-0 bg-bambu-dark-secondary",children:a.jsxs("tr",{className:"text-sm text-bambu-gray border-b border-bambu-dark-tertiary",children:[a.jsx("th",{className:"text-left p-3 w-1/3",children:s("profiles.diff.field")}),a.jsx("th",{className:"text-left p-3 w-1/3",children:r}),a.jsx("th",{className:"text-left p-3 w-1/3",children:i})]})}),a.jsx("tbody",{children:m.map(y=>{const v={added:"bg-green-500/10",removed:"bg-red-500/10",changed:"bg-amber-500/10",same:""}[y.status],b={added:a.jsx(sr,{className:"w-3.5 h-3.5 text-green-400"}),removed:a.jsx(kN,{className:"w-3.5 h-3.5 text-red-400"}),changed:a.jsx(rF,{className:"w-3.5 h-3.5 text-amber-400"}),same:a.jsx(jM,{className:"w-3.5 h-3.5 text-bambu-gray-dark"})}[y.status];return a.jsxs("tr",{className:`border-b border-bambu-dark-tertiary ${v}`,children:[a.jsx("td",{className:"p-3",children:a.jsxs("div",{className:"flex items-center gap-2",children:[b,a.jsx("span",{className:"text-sm text-white font-mono",children:y.key})]})}),a.jsx("td",{className:"p-3",children:a.jsx("span",{className:`text-sm font-mono break-all ${y.status==="removed"?"text-red-300":y.status==="changed"?"text-white":"text-bambu-gray"}`,children:f(y.left)})}),a.jsx("td",{className:"p-3",children:a.jsx("span",{className:`text-sm font-mono break-all ${y.status==="added"?"text-green-300":y.status==="changed"?"text-white":"text-bambu-gray"}`,children:f(y.right)})})]},y.key)})})]})})]})})})}function Gnt({onClose:t,initialData:e,allPresets:n,t:r}){const{showToast:i}=hn(),s=nn(),o=!!e?.setting_id,[l,c]=w.useState("common"),[d,u]=w.useState(e?.type||"filament"),[m,p]=w.useState(e?.name?o?e.name:`${e.name} (Copy)`:""),[f,y]=w.useState(e?.base_id||""),[v,b]=w.useState(""),[g,_]=w.useState(e?.setting||{inherits:""}),[C,P]=w.useState(JSON.stringify(e?.setting||{inherits:""},null,2)),[N,A]=w.useState(null),[T,F]=w.useState(""),[k,D]=w.useState(!1),[H,z]=w.useState(""),[Q,L]=w.useState(!1),[te,ie]=w.useState(zle),[J,oe]=w.useState(!1),[fe,re]=w.useState(""),[W,ne]=w.useState(""),[me,be]=w.useState(!0),[Ce,q]=w.useState(null),[Y,E]=w.useState(!1),j=w.useMemo(()=>({filament:n.filament,print:n.process,printer:n.printer})[d]||[],[n,d]),O=w.useMemo(()=>j.filter(Re=>Kw(Re.setting_id)),[j]),{data:K}=Xe({queryKey:["cloudFields",d],queryFn:()=>de.getCloudFields(d==="print"?"process":d),staleTime:1e3*60*60}),{data:U}=Xe({queryKey:["allPresetDetails",d,O.map(Re=>Re.setting_id).join(",")],queryFn:async()=>{const Re={};for(let Ye=0;Ye{try{const we=await de.getCloudSettingDetail(Fe.setting_id);return{id:Fe.setting_id,detail:we}}catch{return null}}))).forEach(Fe=>{Fe&&(Re[Fe.id]=Fe.detail)})}return Re},enabled:O.length>0,staleTime:1e3*60*10}),{data:ue,isLoading:I}=Xe({queryKey:["cloudSettingDetail",f],queryFn:()=>de.getCloudSettingDetail(f),enabled:!!f});w.useEffect(()=>{l!=="json"&&P(JSON.stringify(g,null,2))},[g,l]);const G=w.useMemo(()=>({filament:n.filament,print:n.process,printer:n.printer}[d]||[]).filter($e=>!Kw($e.setting_id)).sort(($e,Ye)=>$e.name.localeCompare(Ye.name)),[n,d]);w.useEffect(()=>{if(!f)return;const Re=G.find($e=>$e.setting_id===f);Re&&(b(Re.name),o||(_({inherits:Re.name}),P(JSON.stringify({inherits:Re.name},null,2))))},[f,G,o]);const X=w.useMemo(()=>{const Re=K?.fields||[],$e=new Set(Re.map(Fe=>Fe.key)),Ye=new Set,tt=new Set(["inherits","updated_time","compatible_printers","compatible_prints"]);U&&Object.values(U).forEach(Fe=>{Fe?.setting&&Object.keys(Fe.setting).forEach(we=>{!$e.has(we)&&!tt.has(we)&&Ye.add(we)})}),Object.keys(g).forEach(Fe=>{!$e.has(Fe)&&!tt.has(Fe)&&Ye.add(Fe)});const pe=Array.from(Ye).sort().map(Fe=>({key:Fe,label:Fe.replace(/_/g," ").replace(/\b\w/g,we=>we.toUpperCase()),type:"text",category:"discovered",description:r("profiles.presets.discoveredFromPresets")}));return[...Re,...pe]},[K,U,g,r]),V=X.filter(Re=>Re.label.toLowerCase().includes(T.toLowerCase())||Re.key.toLowerCase().includes(T.toLowerCase())),ee=()=>{if(H.trim()){const Re=H.trim().toLowerCase().replace(/\s+/g,"_");se(Re,""),z(""),L(!1),i(r("profiles.presets.toast.fieldAdded",{key:Re}))}},se=(Re,$e)=>{_(Ye=>{const tt={...Ye};return $e===""||$e===void 0?delete tt[Re]:tt[Re]=$e,tt})},ge=Re=>{_($e=>({...$e,...Re.settings})),q(Re.name),i(r("profiles.templates.toast.applied"))},he=()=>{if(!fe.trim())return;const Re={...g};if(delete Re.inherits,Object.keys(Re).length===0){i(r("profiles.presets.noOverridesToSave"),"error");return}const $e={id:Date.now().toString(),name:fe.trim(),description:W.trim()||r("profiles.presets.customTemplate"),type:d,settings:Re,showInModal:me},Ye=[...te,$e];ie(Ye),Ule(Ye),oe(!1),re(""),ne(""),be(!0),i(r("profiles.templates.toast.created"))},le=w.useMemo(()=>te.filter(Re=>Re.type===d&&Re.showInModal),[d,te]),B=Re=>{P(Re);try{const $e=JSON.parse(Re);_($e),A(null)}catch($e){A($e.message)}},R=Re=>{Re.preventDefault(),D(!1);const $e=Re.dataTransfer.files[0];if($e&&$e.name.endsWith(".json")){const Ye=new FileReader;Ye.onload=tt=>{try{const pe=tt.target?.result,Fe=JSON.parse(pe),we=Fe.setting||Fe;_(Ve=>({...Ve,...we})),P(JSON.stringify({...g,...we},null,2)),i(r("profiles.presets.fileImported"))}catch{i(r("profiles.presets.invalidJsonFile"),"error")}},Ye.readAsText($e)}},ae=it({mutationFn:()=>{const Re={...g},$e=d==="filament"?"filament_settings_id":d==="print"?"print_settings_id":"printer_settings_id";Re[$e]=`"${m}"`;const Ye={type:d,name:m,base_id:f,setting:Re};return de.createCloudSetting(Ye)},onSuccess:async()=>{i(r("profiles.presets.toast.created")),await s.refetchQueries({queryKey:["cloudSettings"]}),t()},onError:Re=>i(Re.message,"error")}),_e=it({mutationFn:()=>{if(!e?.setting_id)throw new Error(r("profiles.presets.noSettingId"));return de.updateCloudSetting(e.setting_id,{name:m,setting:g})},onSuccess:async()=>{i(r("profiles.presets.toast.updated")),s.removeQueries({queryKey:["cloudSettingDetail"]}),await s.refetchQueries({queryKey:["cloudSettings"]}),t()},onError:Re=>i(Re.message,"error")}),Se=o?_e:ae,ve=ue?.setting?.inherits,Te=ve?G.find(Re=>Re.name===ve):void 0,{data:ye}=Xe({queryKey:["cloudSettingDetail",Te?.setting_id],queryFn:()=>de.getCloudSettingDetail(Te.setting_id),enabled:!!Te?.setting_id}),Ae=w.useMemo(()=>{const Re=ye?.setting||{},$e=ue?.setting||{},Ye=f&&U?.[f]?.setting?U[f].setting:{};return{...Re,...$e,...Ye}},[f,ue,ye,U]),Le=Re=>{if(Re==null)return"";if(Array.isArray(Re)){const $e=[...new Set(Re.map(Ye=>String(Ye)))];return $e.length===1?$e[0]:Re.join(", ")}return String(Re)},Me=Re=>{const $e=g[Re.key],Ye=Ae[Re.key],tt=Le(Ye),pe=I?r("common.loading"):tt||"",Fe="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 we=$e==="1"||$e===void 0&&Ye==="1";return a.jsx("button",{type:"button",onClick:()=>se(Re.key,$e==="1"?"0":"1"),className:`w-8 h-5 rounded-full transition-colors ${we?"bg-bambu-green":"bg-bambu-dark-tertiary"}`,children:a.jsx("div",{className:`w-4 h-4 rounded-full bg-white shadow transition-transform ${we?"translate-x-3.5":"translate-x-0.5"}`})})}return Re.type==="select"?a.jsxs("select",{value:$e||"",onChange:we=>se(Re.key,we.target.value),className:Fe,children:[a.jsx("option",{value:"",children:pe}),Re.options?.map(we=>a.jsx("option",{value:we.value,children:we.label},we.value))]}):a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("input",{type:Re.type==="number"?"number":"text",value:$e!==void 0?String($e):"",onChange:we=>se(Re.key,we.target.value),step:Re.step,min:Re.min,max:Re.max,placeholder:pe,className:Fe}),Re.unit&&a.jsx("span",{className:"text-xs text-bambu-gray whitespace-nowrap",children:Re.unit})]})},Oe=w.useMemo(()=>ue?.setting?ue.setting:{},[ue]);return a.jsxs("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",onDragOver:Re=>{Re.preventDefault(),D(!0)},onDragLeave:()=>D(!1),onDrop:R,children:[Y&&f&&a.jsx(Ble,{onClose:()=>E(!1),leftPreset:Oe,rightPreset:g,leftLabel:r("profiles.presets.baseLabel",{name:v||f}),rightLabel:r("profiles.presets.currentLabel",{name:m||r("profiles.presets.newPreset")}),t:r}),a.jsx(Tt,{className:"w-full max-w-6xl max-h-[90vh] flex flex-col overflow-y-auto",children:a.jsxs(Mt,{className:"p-0 flex flex-col h-full",children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[a.jsxs("div",{children:[a.jsx("h2",{className:"text-xl font-semibold text-white",children:r(o?"profiles.presets.editPreset":e?"profiles.presets.duplicatePreset":"profiles.presets.createNewPreset")}),a.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:r("profiles.presets.customizeSettings")})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[f&&a.jsxs("button",{onClick:()=>E(!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:r("profiles.presets.compareWithBase"),children:[a.jsx(Cx,{className:"w-4 h-4"}),r("profiles.presets.compare")]}),a.jsx("button",{onClick:t,className:"p-2 text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary rounded-lg transition-colors",children:a.jsx(Ht,{className:"w-5 h-5"})})]})]}),k&&a.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:a.jsxs("div",{className:"text-center",children:[a.jsx(La,{className:"w-12 h-12 text-bambu-green mx-auto mb-2"}),a.jsx("p",{className:"text-bambu-green font-medium",children:r("profiles.presets.dropJsonToImport")})]})}),a.jsxs("div",{className:"p-4 border-b border-bambu-dark-tertiary space-y-3",children:[a.jsxs("div",{className:"grid grid-cols-3 gap-4 max-[640px]:grid-cols-1",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("common.type")}),a.jsxs("select",{value:d,onChange:Re=>{u(Re.target.value),y("")},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:[a.jsx("option",{value:"filament",children:r("profiles.presets.types.filament")}),a.jsx("option",{value:"print",children:r("profiles.presets.types.process")}),a.jsx("option",{value:"printer",children:r("profiles.presets.types.printer")})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("profiles.presets.basePreset")}),a.jsxs("select",{value:f,onChange:Re=>y(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:[a.jsx("option",{value:"",children:r("profiles.presets.selectBasePreset")}),G.map(Re=>a.jsx("option",{value:Re.setting_id,children:Re.name},Re.setting_id))]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("profiles.presets.presetName")}),a.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:r("profiles.presets.myCustomPreset")})]})]}),v&&a.jsx("div",{className:"text-xs text-bambu-gray",children:a.jsxs("p",{className:"flex items-center gap-1",children:[a.jsx(Ur,{className:"w-3 h-3 text-bambu-green"}),r("profiles.presets.inheritsFrom")," ",a.jsx("span",{className:"text-white",children:v}),I&&a.jsx(pt,{className:"w-3 h-3 animate-spin ml-1"})]})})]}),a.jsxs("div",{className:"flex border-b border-bambu-dark-tertiary max-[640px]:flex-wrap max-[640px]:items-center",children:[a.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:[a.jsx(PH,{className:"w-4 h-4"}),r("profiles.presets.tabs.common")]}),a.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:[a.jsx(tS,{className:"w-4 h-4"}),r("profiles.presets.tabs.allFields")]}),a.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:[a.jsx(wy,{className:"w-4 h-4"}),"JSON",N&&a.jsx(ei,{className:"w-3 h-3 text-red-400"})]}),a.jsx("div",{className:"flex-1 max-[640px]:hidden"}),a.jsxs("button",{onClick:()=>{const Re={name:m,type:d,base_id:f,setting:g},$e=new Blob([JSON.stringify(Re,null,2)],{type:"application/json"}),Ye=URL.createObjectURL($e),tt=document.createElement("a");tt.href=Ye,tt.download=`${m||"preset"}.json`,document.body.appendChild(tt),tt.click(),document.body.removeChild(tt),URL.revokeObjectURL(Ye),i(r("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:r("profiles.presets.exportToJson"),children:[a.jsx(ga,{className:"w-4 h-4"}),r("common.download")]}),a.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:r("profiles.presets.importFromJson"),children:[a.jsx(La,{className:"w-4 h-4"}),r("common.upload")]}),a.jsx("input",{id:"file-import",type:"file",accept:".json",className:"hidden",onChange:Re=>{const $e=Re.target.files?.[0];if($e){const Ye=new FileReader;Ye.onload=tt=>{try{const pe=JSON.parse(tt.target?.result),Fe=pe.setting||pe;_(we=>({...we,...Fe})),i(r("profiles.presets.fileImported"))}catch{i(r("profiles.presets.invalidJson"),"error")}},Ye.readAsText($e)}}})]}),a.jsxs("div",{className:"flex-1 p-4",children:[l==="common"&&a.jsxs("div",{className:"space-y-6",children:[a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center justify-between mb-3",children:[a.jsxs("h3",{className:"text-sm font-medium text-white flex items-center gap-2",children:[a.jsx($x,{className:"w-4 h-4 text-amber-400"}),r("profiles.templates.title")]}),Object.keys(g).filter(Re=>Re!=="inherits").length>0&&a.jsxs("button",{onClick:()=>oe(!J),className:"text-xs text-bambu-gray hover:text-white flex items-center gap-1 transition-colors",children:[a.jsx(_s,{className:"w-3 h-3"}),r("profiles.presets.saveAsTemplate")]})]}),J&&a.jsxs("div",{className:"mb-3 p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"grid grid-cols-2 gap-2 mb-2",children:[a.jsx("input",{type:"text",value:fe,onChange:Re=>re(Re.target.value),placeholder:r("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}),a.jsx("input",{type:"text",value:W,onChange:Re=>ne(Re.target.value),placeholder:r("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"})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex gap-2",children:[a.jsxs(De,{size:"sm",onClick:he,disabled:!fe.trim(),children:[a.jsx(_s,{className:"w-3 h-3"}),r("common.save")]}),a.jsx(De,{size:"sm",variant:"secondary",onClick:()=>oe(!1),children:r("common.cancel")})]}),a.jsxs("button",{onClick:()=>be(!me),className:`flex items-center gap-1.5 text-xs transition-colors ${me?"text-bambu-green":"text-bambu-gray hover:text-white"}`,children:[me?a.jsx(vl,{className:"w-3.5 h-3.5"}):a.jsx(Og,{className:"w-3.5 h-3.5"}),r(me?"profiles.templates.shownInModals":"profiles.templates.hiddenInModals")]})]})]}),Ce&&a.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:[a.jsx(Ur,{className:"w-4 h-4 text-bambu-green"}),a.jsxs("span",{className:"text-sm text-bambu-green",children:[r("profiles.presets.templateApplied")," ",a.jsx("span",{className:"font-medium",children:Ce})]}),a.jsx("button",{onClick:()=>q(null),className:"ml-auto text-bambu-green/70 hover:text-bambu-green",children:a.jsx(Ht,{className:"w-4 h-4"})})]}),a.jsxs("div",{className:"grid grid-cols-3 gap-2",children:[le.map(Re=>a.jsxs("button",{onClick:()=>ge(Re),className:"p-3 text-left bg-bambu-dark border border-bambu-dark-tertiary rounded-lg hover:border-bambu-gray-dark transition-colors",children:[a.jsx("p",{className:"text-sm font-medium text-white",children:Re.name}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:Re.description})]},Re.id)),le.length===0&&a.jsx("p",{className:"col-span-3 text-center text-bambu-gray text-sm py-4",children:r("profiles.presets.noTemplatesSelected")})]}),a.jsx("p",{className:"text-xs text-bambu-gray-dark mt-2 text-center",children:r("profiles.presets.manageTemplatesHint")})]}),a.jsxs("div",{children:[a.jsx("h3",{className:"text-sm font-medium text-white mb-3",children:r("profiles.presets.commonSettings")}),a.jsx("div",{className:"grid grid-cols-2 gap-x-6 gap-y-3",children:X.slice(0,10).map(Re=>a.jsxs("div",{className:"flex items-center justify-between gap-4 max-[640px]:flex-col max-[640px]:items-start",children:[a.jsx("label",{className:"text-sm text-bambu-gray flex-shrink-0",children:Re.label}),a.jsx("div",{className:"w-48 max-[640px]:w-full",children:Me(Re)})]},Re.key))})]}),Object.keys(g).length>1&&a.jsxs("div",{children:[a.jsx("h3",{className:"text-sm font-medium text-white mb-3",children:r("profiles.presets.currentOverrides")}),a.jsx("div",{className:"flex flex-wrap gap-2",children:Object.entries(g).filter(([Re])=>Re!=="inherits").map(([Re,$e])=>a.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($e).slice(0,20),a.jsx("button",{onClick:()=>se(Re,void 0),className:"hover:text-white",children:a.jsx(Ht,{className:"w-3 h-3"})})]},Re))})]})]}),l==="fields"&&a.jsxs("div",{className:"grid grid-cols-2 gap-6",style:{height:"400px"},children:[a.jsxs("div",{className:"flex flex-col h-full overflow-hidden",children:[a.jsxs("div",{className:"flex items-center justify-between mb-3 flex-shrink-0",children:[a.jsx("h3",{className:"text-sm font-medium text-white",children:r("profiles.presets.availableFields")}),a.jsx("span",{className:"text-xs text-bambu-gray",children:U?r("profiles.templates.fieldsCount",{count:X.length}):r("common.loading")})]}),a.jsxs("div",{className:"relative mb-3 flex-shrink-0",children:[a.jsx(Pr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),a.jsx("input",{type:"text",value:T,onChange:Re=>F(Re.target.value),placeholder:r("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"})]}),a.jsxs("div",{className:"flex-1 overflow-y-auto space-y-1 pr-2 min-h-0",children:[V.filter(Re=>!(Re.key in g)).map(Re=>{const $e=Ae[Re.key],Ye=Le($e);return a.jsxs("div",{onClick:()=>{_(tt=>({...tt,[Re.key]:Ye||""}))},className:"flex items-center justify-between gap-2 p-2 rounded-lg hover:bg-bambu-dark-tertiary transition-colors cursor-pointer group",children:[a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsx("p",{className:"text-sm text-white truncate",children:Re.label}),a.jsx("p",{className:"text-xs text-bambu-gray-dark truncate",children:Re.key})]}),a.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[Ye&&a.jsxs("span",{className:"text-xs text-bambu-gray bg-bambu-dark px-2 py-0.5 rounded max-w-32 truncate",title:Ye,children:[Ye.slice(0,20),Ye.length>20?"...":""]}),a.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:a.jsx(sr,{className:"w-4 h-4 text-bambu-gray group-hover:text-bambu-green transition-colors"})})]})]},Re.key)}),V.filter(Re=>!(Re.key in g)).length===0&&a.jsx("p",{className:"text-center text-bambu-gray py-4 text-sm",children:r(T?"profiles.presets.noMatchingFields":"profiles.presets.allFieldsAdded")})]}),a.jsx("div",{className:"pt-3 mt-3 border-t border-bambu-dark-tertiary flex-shrink-0",children:Q?a.jsxs("div",{className:"flex gap-2",children:[a.jsx("input",{type:"text",value:H,onChange:Re=>z(Re.target.value),onKeyDown:Re=>Re.key==="Enter"&&ee(),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}),a.jsx(De,{size:"sm",onClick:ee,disabled:!H.trim(),children:a.jsx(sr,{className:"w-4 h-4"})}),a.jsx(De,{size:"sm",variant:"secondary",onClick:()=>{L(!1),z("")},children:a.jsx(Ht,{className:"w-4 h-4"})})]}):a.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:[a.jsx(sr,{className:"w-4 h-4"}),r("profiles.presets.addCustomField")]})})]}),a.jsxs("div",{className:"flex flex-col h-full overflow-hidden",children:[a.jsxs("div",{className:"flex items-center justify-between mb-3 flex-shrink-0",children:[a.jsx("h3",{className:"text-sm font-medium text-white",children:r("profiles.presets.yourOverrides")}),a.jsx("span",{className:"text-xs text-bambu-gray",children:r("profiles.templates.fieldsCount",{count:Object.keys(g).filter(Re=>Re!=="inherits").length})})]}),a.jsxs("div",{className:"flex-1 overflow-y-auto space-y-2 pr-2 min-h-0",children:[Object.entries(g).filter(([Re])=>Re!=="inherits").map(([Re,$e])=>{const Ye=X.find(tt=>tt.key===Re);return a.jsxs("div",{className:"p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center justify-between mb-2",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm font-medium text-white",children:Ye?.label||Re}),a.jsx("p",{className:"text-xs text-bambu-gray-dark",children:Re})]}),a.jsx("button",{onClick:()=>se(Re,void 0),className:"p-1 text-bambu-gray hover:text-red-400 transition-colors",children:a.jsx(Ht,{className:"w-4 h-4"})})]}),Ye?Me(Ye):a.jsx("input",{type:"text",value:String($e),onChange:tt=>se(Re,tt.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(g).filter(Re=>Re!=="inherits").length===0&&a.jsxs("div",{className:"text-center py-8 text-bambu-gray",children:[a.jsx(PH,{className:"w-8 h-8 mx-auto mb-2 opacity-50"}),a.jsx("p",{className:"text-sm",children:r("profiles.presets.noOverridesYet")}),a.jsx("p",{className:"text-xs mt-1",children:r("profiles.presets.clickFieldsToAdd")})]})]}),Object.keys(g).filter(Re=>Re!=="inherits").length>0&&a.jsx("div",{className:"pt-3 mt-3 border-t border-bambu-dark-tertiary flex-shrink-0",children:a.jsxs("button",{onClick:()=>{oe(!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:[a.jsx(_s,{className:"w-4 h-4"}),r("profiles.presets.saveAsTemplate")]})})]})]}),l==="json"&&a.jsxs("div",{className:"space-y-2",children:[N&&a.jsxs("div",{className:"flex items-center gap-2 text-red-400 text-sm",children:[a.jsx(ei,{className:"w-4 h-4"}),N]}),a.jsx("textarea",{value:C,onChange:Re=>B(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 ${N?"border-red-500 focus:border-red-500":"border-bambu-dark-tertiary focus:border-bambu-green"}`,spellCheck:!1}),a.jsx("p",{className:"text-xs text-bambu-gray",children:r("profiles.presets.jsonTip")})]})]}),a.jsxs("div",{className:"p-4 border-t border-bambu-dark-tertiary flex gap-2",children:[a.jsx(De,{variant:"secondary",onClick:t,className:"flex-1",children:r("common.cancel")}),a.jsxs(De,{onClick:()=>Se.mutate(),disabled:Se.isPending||!m.trim()||!o&&!f||!!N,className:"flex-1",children:[Se.isPending?a.jsx(pt,{className:"w-4 h-4 animate-spin"}):o?a.jsx(_s,{className:"w-4 h-4"}):a.jsx(sr,{className:"w-4 h-4"}),r(o?"common.save":e?"common.duplicate":"common.create")]})]})]})})]})}function Wnt({settings:t,lastSyncTime:e,onRefresh:n,isRefreshing:r,printers:i,hasPermission:s,t:o}){const[l,c]=w.useState(""),[d,u]=w.useState("all"),[m,p]=w.useState("all"),[f,y]=w.useState("all"),[v,b]=w.useState("all"),[g,_]=w.useState("all"),[C,P]=w.useState("all"),[N,A]=w.useState(null),[T,F]=w.useState(!1),[k,D]=w.useState(!1),[H,z]=w.useState(null),[Q,L]=w.useState(null),[te,ie]=w.useState(null),[J,oe]=w.useState(!1),[fe,re]=w.useState([null,null]),[W,ne]=w.useState(!1),[me,be]=w.useState(null),Ce=nn(),q=w.useMemo(()=>[...t.filament.map(ee=>({...ee,type:"filament"})),...t.printer.map(ee=>({...ee,type:"printer"})),...t.process.map(ee=>({...ee,type:"process"}))].map(ee=>({...ee,meta:b5(ee.name)})),[t]),Y=w.useMemo(()=>{const V=new Set,ee=new Set,se=new Set;return q.forEach(ge=>{ge.meta.nozzle&&V.add(ge.meta.nozzle),ge.meta.filamentType&&ee.add(ge.meta.filamentType),ge.meta.layerHeight&&se.add(ge.meta.layerHeight)}),{printers:i.map(ge=>({id:ge.id.toString(),name:ge.name})),nozzles:Array.from(V).sort((ge,he)=>parseFloat(ge)-parseFloat(he)),filaments:Array.from(ee).sort(),layerHeights:Array.from(se).sort((ge,he)=>parseFloat(ge)-parseFloat(he))}},[q,i]),E=w.useMemo(()=>f==="all"?null:i.find(ee=>ee.id.toString()===f)?.model||null,[f,i]),j=w.useMemo(()=>q.filter(V=>d==="all"||V.type===d).filter(V=>{if(m==="all")return!0;const ee=Kw(V.setting_id);return m==="custom"?ee:!ee}).filter(V=>{if(f==="all"||!E)return!0;const ee=V.meta.printer?.toLowerCase()||"",se=E.toLowerCase();return ee.includes(se)||se.includes(ee)}).filter(V=>v==="all"||V.meta.nozzle===v).filter(V=>g==="all"||V.meta.filamentType===g).filter(V=>C==="all"||V.meta.layerHeight===C).filter(V=>l===""||V.name.toLowerCase().includes(l.toLowerCase())).sort((V,ee)=>V.name.localeCompare(ee.name)),[q,d,m,f,E,v,g,C,l]),O=V=>{if(J){const ee=fe[0]?.setting_id===V.setting_id,se=fe[1]?.setting_id===V.setting_id;if(ee)re([fe[1],null]);else if(se)re([fe[0],null]);else if(!fe[0])re([V,null]);else if(fe[1]){if(fe[0].type!==V.type)return;re([fe[0],V])}else{if(fe[0].type!==V.type)return;re([fe[0],V])}}else A(V)},K=V=>{if(fe[0]?.setting_id===V.setting_id)return 0;if(fe[1]?.setting_id===V.setting_id)return 1},U=async V=>{try{const ee=await de.getCloudSettingDetail(V.setting_id),se=V.type==="process"?"print":V.type;z({type:se,name:V.name,base_id:ee.base_id||"GFSA00",setting:ee.setting||{}}),A(null)}catch(ee){console.error("Failed to fetch preset details for duplication:",ee)}},ue=async V=>{try{Ce.removeQueries({queryKey:["cloudSettingDetail",V.setting_id]});const ee=await de.getCloudSettingDetail(V.setting_id),se=V.type==="process"?"print":V.type;L({type:se,name:V.name,base_id:ee.base_id||"GFSA00",setting:ee.setting||{},setting_id:V.setting_id}),A(null)}catch(ee){console.error("Failed to fetch preset details for editing:",ee)}},I=()=>{u("all"),p("all"),y("all"),b("all"),_("all"),P("all"),c("")},G=d!=="all"||m!=="all"||f!=="all"||v!=="all"||g!=="all"||C!=="all"||l!=="",X=t.filament.length+t.printer.length+t.process.length;return a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"space-y-4 mb-6",children:[a.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[a.jsxs("div",{className:"relative flex-1",children:[a.jsx(Pr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),a.jsx("input",{type:"text",value:l,onChange:V=>c(V.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"})]}),a.jsxs("div",{className:"flex gap-2 max-[550px]:flex-wrap max-[550px]:items-center",children:[a.jsxs(De,{variant:J?"primary":"secondary",onClick:()=>{J?(oe(!1),re([null,null])):oe(!0)},children:[a.jsx(Cx,{className:"w-4 h-4"}),o(J?"common.cancel":"profiles.presets.compare")]}),a.jsxs(De,{variant:"secondary",onClick:()=>D(!0),disabled:!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.cloudView.noTemplatesPermission"),children:[a.jsx($x,{className:"w-4 h-4"}),o("profiles.cloudView.templates")]}),a.jsxs(De,{variant:"secondary",onClick:n,disabled:r||!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.cloudView.noRefreshPermission"),children:[a.jsx(lr,{className:`w-4 h-4 ${r?"animate-spin":""}`}),o("profiles.cloudView.refresh")]}),a.jsxs(De,{onClick:()=>F(!0),disabled:!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.cloudView.noCreatePermission"),children:[a.jsx(sr,{className:"w-4 h-4"}),o("profiles.cloudView.newPreset")]})]})]}),a.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[a.jsx(VP,{className:"w-4 h-4 text-bambu-gray"}),a.jsx(cx,{label:o("profiles.cloudView.filters.type"),value:d,options:[{value:"all",label:o("profiles.cloudView.filters.all"),count:X},{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:V=>u(V)}),a.jsx(cx,{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:V=>p(V)}),Y.printers.length>0&&a.jsx(cx,{label:o("profiles.cloudView.filters.printer"),value:f,options:[{value:"all",label:o("profiles.cloudView.filters.all")},...Y.printers.map(V=>({value:V.id,label:V.name}))],onChange:y}),Y.nozzles.length>0&&a.jsx(cx,{label:o("profiles.cloudView.filters.nozzle"),value:v,options:[{value:"all",label:o("profiles.cloudView.filters.all")},...Y.nozzles.map(V=>({value:V,label:V}))],onChange:b}),Y.filaments.length>0&&(d==="all"||d==="filament")&&a.jsx(cx,{label:o("profiles.cloudView.filters.filament"),value:g,options:[{value:"all",label:o("profiles.cloudView.filters.all")},...Y.filaments.map(V=>({value:V,label:V}))],onChange:_}),Y.layerHeights.length>0&&(d==="all"||d==="process")&&a.jsx(cx,{label:o("profiles.cloudView.filters.layer"),value:C,options:[{value:"all",label:o("profiles.cloudView.filters.all")},...Y.layerHeights.map(V=>({value:V,label:V}))],onChange:P}),G&&a.jsx("button",{onClick:I,className:"px-3 py-2 text-sm text-bambu-gray hover:text-white transition-colors",children:o("profiles.cloudView.clearFilters")})]})]}),J&&a.jsx("div",{className:"mb-4 p-3 bg-blue-500/10 border border-blue-500/30 rounded-lg",children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-4",children:[a.jsx(Cx,{className:"w-5 h-5 text-blue-400"}),a.jsx("span",{className:"text-white font-medium",children:o("profiles.cloudView.compareMode")}),a.jsx("span",{className:"text-bambu-gray",children:fe[0]?o("profiles.cloudView.selectAnotherPreset",{type:fe[0].type}):o("profiles.cloudView.clickTwoPresets")})]}),a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:`px-2 py-1 text-sm rounded truncate max-w-[200px] ${fe[0]?"bg-blue-500/30 text-blue-700 dark:text-blue-300":"bg-bambu-dark text-bambu-gray"}`,children:fe[0]?fe[0].name:o("profiles.cloudView.selectFirst")}),a.jsx(rF,{className:"w-4 h-4 text-bambu-gray"}),a.jsx("span",{className:`px-2 py-1 text-sm rounded truncate max-w-[200px] ${fe[1]?"bg-blue-500/30 text-blue-700 dark:text-blue-300":"bg-bambu-dark text-bambu-gray"}`,children:fe[1]?fe[1].name:o("profiles.cloudView.selectSecond")})]}),fe[0]&&fe[1]&&a.jsxs(De,{size:"sm",onClick:async()=>{try{const[V,ee]=await Promise.all([de.getCloudSettingDetail(fe[0].setting_id),de.getCloudSettingDetail(fe[1].setting_id)]);be([V.setting||{},ee.setting||{}]),ne(!0)}catch{}},children:[a.jsx(Cx,{className:"w-4 h-4"}),o("profiles.cloudView.compareNow")]})]})]})}),a.jsxs("div",{className:"flex flex-wrap items-center gap-4 mb-4 text-sm text-bambu-gray",children:[e&&a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsx(Yn,{className:"w-3 h-3"}),o("profiles.cloudView.lastSynced")," ",ap(e.toISOString(),"system",o)]}),a.jsx("span",{children:o("profiles.cloudView.showingCount",{showing:j.length,total:X})}),a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-bambu-green"}),a.jsxs("span",{children:["= ",o("profiles.presets.myPreset")]})]})]}),j.length===0?a.jsxs("div",{className:"text-center py-16",children:[a.jsx(da,{className:"w-12 h-12 text-bambu-gray-dark mx-auto mb-4"}),a.jsx("p",{className:"text-bambu-gray",children:o("profiles.cloudView.noPresetsFound")}),G&&a.jsx("button",{onClick:I,className:"mt-2 text-sm text-bambu-green hover:text-bambu-green-light",children:o("profiles.cloudView.clearFilters")})]}):a.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-6",children:[a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center gap-2 mb-3 px-1",children:[a.jsx(qP,{className:"w-4 h-4 text-amber-400"}),a.jsx("h3",{className:"text-sm font-medium text-bambu-gray",children:o("profiles.cloudView.columns.filament")}),a.jsxs("span",{className:"text-xs text-bambu-gray-dark",children:["(",j.filter(V=>V.type==="filament").length,")"]})]}),a.jsxs("div",{className:"space-y-1 max-h-[calc(100vh-320px)] overflow-y-auto pr-1",children:[j.filter(V=>V.type==="filament").map(V=>a.jsx(j3,{setting:V,onClick:()=>O(V),onDuplicate:()=>U(V),compareMode:J,isCompareSelected:K(V)!==void 0,compareIndex:K(V),compareDisabled:J&&!!fe[0]&&fe[0].type!==V.type,t:o},V.setting_id)),j.filter(V=>V.type==="filament").length===0&&a.jsx("p",{className:"text-xs text-bambu-gray-dark px-3 py-2",children:o("profiles.cloudView.noFilamentPresets")})]})]}),a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center gap-2 mb-3 px-1",children:[a.jsx(Ud,{className:"w-4 h-4 text-blue-400"}),a.jsx("h3",{className:"text-sm font-medium text-bambu-gray",children:o("profiles.cloudView.columns.process")}),a.jsxs("span",{className:"text-xs text-bambu-gray-dark",children:["(",j.filter(V=>V.type==="process").length,")"]})]}),a.jsxs("div",{className:"space-y-1 max-h-[calc(100vh-320px)] overflow-y-auto pr-1",children:[j.filter(V=>V.type==="process").map(V=>a.jsx(j3,{setting:V,onClick:()=>O(V),onDuplicate:()=>U(V),compareMode:J,isCompareSelected:K(V)!==void 0,compareIndex:K(V),compareDisabled:J&&!!fe[0]&&fe[0].type!==V.type,t:o},V.setting_id)),j.filter(V=>V.type==="process").length===0&&a.jsx("p",{className:"text-xs text-bambu-gray-dark px-3 py-2",children:o("profiles.cloudView.noProcessPresets")})]})]}),a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center gap-2 mb-3 px-1",children:[a.jsx(Er,{className:"w-4 h-4 text-purple-400"}),a.jsx("h3",{className:"text-sm font-medium text-bambu-gray",children:o("profiles.cloudView.columns.printer")}),a.jsxs("span",{className:"text-xs text-bambu-gray-dark",children:["(",j.filter(V=>V.type==="printer").length,")"]})]}),a.jsxs("div",{className:"space-y-1 max-h-[calc(100vh-320px)] overflow-y-auto pr-1",children:[j.filter(V=>V.type==="printer").map(V=>a.jsx(j3,{setting:V,onClick:()=>O(V),onDuplicate:()=>U(V),compareMode:J,isCompareSelected:K(V)!==void 0,compareIndex:K(V),compareDisabled:J&&!!fe[0]&&fe[0].type!==V.type,t:o},V.setting_id)),j.filter(V=>V.type==="printer").length===0&&a.jsx("p",{className:"text-xs text-bambu-gray-dark px-3 py-2",children:o("profiles.cloudView.noPrinterPresets")})]})]})]}),N&&a.jsx($nt,{setting:N,onClose:()=>A(null),onDeleted:()=>A(null),onDuplicate:()=>U(N),onEdit:()=>ue(N),hasPermission:s,t:o}),(T||H||Q||te)&&a.jsx(Gnt,{onClose:()=>{F(!1),z(null),L(null),ie(null)},initialData:Q||H||(te?{type:te.type,name:"",base_id:"",setting:te.setting}:void 0),allPresets:t,t:o}),k&&a.jsx(Vnt,{onClose:()=>D(!1),onApply:V=>{ie({type:V.type,setting:V.settings}),D(!1)},t:o}),W&&me&&fe[0]&&fe[1]&&a.jsx(Ble,{onClose:()=>{ne(!1),be(null)},leftPreset:me[0],rightPreset:me[1],leftLabel:fe[0].name,rightLabel:fe[1].name,t:o})]})}function Knt(){const{t}=Ft(),e=nn(),{showToast:n}=hn(),{hasPermission:r}=Sr(),[i,s]=w.useState("cloud"),[o,l]=w.useState(),{data:c,isLoading:d}=Xe({queryKey:["cloudStatus"],queryFn:de.getCloudStatus}),{data:u=[]}=Xe({queryKey:["printers"],queryFn:de.getPrinters}),{data:m,isLoading:p,refetch:f,dataUpdatedAt:y}=Xe({queryKey:["cloudSettings"],queryFn:()=>de.getCloudSettings(),enabled:!!c?.is_authenticated,retry:!1,staleTime:1e3*60*5});w.useEffect(()=>{y&&l(new Date(y))},[y]);const v=it({mutationFn:de.cloudLogout,onSuccess:()=>{e.invalidateQueries({queryKey:["cloudStatus"]}),e.removeQueries({queryKey:["cloudSettings"]}),n(t("profiles.toast.loggedOut"))}}),b=()=>{e.invalidateQueries({queryKey:["cloudStatus"]})};return d?a.jsx("div",{className:"p-4 md:p-8 flex items-center justify-center min-h-[400px]",children:a.jsx(pt,{className:"w-8 h-8 text-bambu-green animate-spin"})}):a.jsxs("div",{className:"p-6 lg:p-8",children:[a.jsxs("div",{className:"mb-6",children:[a.jsx("h1",{className:"text-2xl font-bold text-white",children:t("profiles.title")}),a.jsx("p",{className:"text-bambu-gray",children:t("profiles.subtitle")})]}),a.jsxs("div",{className:"flex border-b border-bambu-dark-tertiary mb-6",children:[a.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:[a.jsx(vy,{className:"w-4 h-4"}),t("profiles.tabs.cloud")]}),a.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:[a.jsx(Ig,{className:"w-4 h-4"}),t("profiles.tabs.local")]}),a.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:[a.jsx(Zw,{className:"w-4 h-4"}),t("profiles.tabs.kprofiles")]})]}),i==="cloud"&&a.jsxs(a.Fragment,{children:[c?.is_authenticated&&a.jsxs("div",{className:"flex items-center justify-between p-3 mb-6 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:"w-2 h-2 rounded-full bg-bambu-green animate-pulse"}),a.jsxs("span",{className:"text-sm text-bambu-gray",children:[t("profiles.connectedAs")," ",a.jsx("span",{className:"text-white",children:c.email}),c.region&&a.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")})]})]}),a.jsxs(De,{variant:"secondary",size:"sm",onClick:()=>v.mutate(),disabled:v.isPending||!r("cloud:auth"),title:r("cloud:auth")?void 0:t("profiles.noLogoutPermission"),children:[a.jsx(oF,{className:"w-4 h-4"}),t("profiles.logout")]})]}),c?.is_authenticated?p?a.jsx("div",{className:"flex items-center justify-center py-16",children:a.jsx(pt,{className:"w-8 h-8 text-bambu-green animate-spin"})}):m?a.jsx(Wnt,{settings:m,lastSyncTime:o,onRefresh:()=>f(),isRefreshing:p,printers:u,hasPermission:r,t}):a.jsxs("div",{className:"text-center py-16",children:[a.jsx("p",{className:"text-bambu-gray mb-4",children:t("profiles.failedToLoad")}),a.jsx(De,{onClick:()=>f(),children:t("profiles.retry")})]}):a.jsx(Hnt,{onSuccess:b,t})]}),i==="local"&&a.jsx(Bnt,{}),i==="kprofiles"&&a.jsx(Ont,{}),a.jsx(qnt,{})]})}function Xnt(t,e){const n=(e||"").toUpperCase().replace(/[- ]/g,""),r=n.includes("X1"),i=n.includes("P1"),s=n.includes("A1MINI"),o=n.includes("A1")&&!s,l=n.includes("H2D"),c=n.includes("H2C"),d=n.includes("H2S"),u=l||c||d,m=n.includes("P2S"),p=n.includes("X2D"),f=m||p;switch(t){case"Lubricate Steel Rods":return f?"https://wiki.bambulab.com/en/p2s/maintenance/lubricate-x-y-z-axis":null;case"Clean Steel Rods":return f?"https://wiki.bambulab.com/en/p2s/maintenance/lubricate-x-y-z-axis":null;case"Lubricate Linear Rails":return s?"https://wiki.bambulab.com/en/a1-mini/maintenance/lubricate-y-axis":o?"https://wiki.bambulab.com/en/a1/maintenance/lubricate-y-axis":u?"https://wiki.bambulab.com/en/h2/maintenance/x-axis-lubrication":null;case"Clean Nozzle/Hotend":return r||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 r?"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 r||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 r||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 C0={Droplet:qP,Flame:Hu,Ruler:Ybe,Sparkles:$x,Square:uo,Cable:AO,Wrench:mg,Calendar:na,Timer:jd,Cog:Tfe,Fan:RQ,Zap:uc,Wind:YQ,Thermometer:oS,Layers:da,Box:vi,Target:GQ,RefreshCw:lr,Settings:sS,Filter:VP,CircleDot:cfe};function Z0(t){return t&&C0[t]||mg}function dx(t,e,n){if(e==="days"){if(t<1)return n?n("common.today"):"Today";if(t===1)return n?n("maintenance.day"):"1 day";if(t<7){const i=Math.round(t);return n?n("maintenance.days",{count:i}):`${i} days`}if(t<180){const i=Math.round(t/7);return i===1?n?n("maintenance.week"):"1 week":n?n("maintenance.weeks",{count:i}):`${i} weeks`}const r=Math.round(t/30);return r===1?n?n("maintenance.month"):"1 month":n?n("maintenance.months",{count:r}):`${r} 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 r=t/24;if(r<7)return`${r<2?r.toFixed(1):Math.round(r)}d`;const i=r/7;return i<12?`${i<2?i.toFixed(1):Math.round(i)}w`:`${Math.round(i/4)}mo`}}function M3(t,e,n){return e==="days"?t===1?n?n("maintenance.day"):"1 day":t===7?n?n("maintenance.week"):"1 week":t===14?n?n("maintenance.weeks",{count:2}):"2 weeks":t===30?n?n("maintenance.month"):"1 month":t===60?n?n("maintenance.months",{count:2}):"2 months":t===90?n?n("maintenance.months",{count:3}):"3 months":t===180?n?n("maintenance.months",{count:6}):"6 months":t===365?n?n("maintenance.year"):"1 year":n?n("maintenance.days",{count:t}):`${t} days`:`${t}h`}function Ynt({item:t,onPerform:e,onToggle:n,hasPermission:r,t:i}){const s=Z0(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:dx(Math.abs(f),"days",i)}):t.is_warning?i("maintenance.dueIn",{duration:dx(f,"days",i)}):i("maintenance.timeLeft",{duration:dx(f,"days",i)})}else return t.is_due?i("maintenance.overdueBy",{duration:dx(Math.abs(t.hours_until_due),"hours",i)}):t.is_warning?i("maintenance.dueIn",{duration:dx(t.hours_until_due,"hours",i)}):i("maintenance.timeLeft",{duration:dx(t.hours_until_due,"hours",i)})};return a.jsx("div",{className:`rounded-xl border p-4 transition-all ${m()}`,children:a.jsxs("div",{className:"flex items-start gap-3 max-[550px]:flex-wrap",children:[a.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:[a.jsx(s,{className:`w-5 h-5 ${d()}`}),t.enabled&&(t.is_due||t.is_warning)&&a.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`})]}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("h3",{className:`font-medium truncate ${t.enabled?"text-white":"text-bambu-gray"}`,children:t.maintenance_type_name}),o==="days"&&a.jsx("span",{title:i("maintenance.timeBasedInterval"),children:a.jsx(na,{className:"w-3.5 h-3.5 text-bambu-gray shrink-0"})}),(()=>{const f=t.maintenance_type_wiki_url||Xnt(t.maintenance_type_name,t.printer_model);return f?a.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:y=>y.stopPropagation(),children:a.jsx(la,{className:"w-3.5 h-3.5"})}):null})()]}),a.jsx("div",{className:"mt-2 mb-1.5",children:a.jsx("div",{className:"w-full h-1.5 bg-bambu-dark rounded-full overflow-hidden",children:a.jsx("div",{className:`h-full rounded-full transition-all duration-500 ${u()}`,style:{width:`${c}%`}})})}),a.jsxs("div",{className:`text-xs flex items-center gap-1 ${d()}`,children:[t.is_due&&a.jsx(Dn,{className:"w-3 h-3"}),t.is_warning&&!t.is_due&&a.jsx(Yn,{className:"w-3 h-3"}),!t.is_due&&!t.is_warning&&t.enabled&&a.jsx(Ur,{className:"w-3 h-3"}),p()]})]}),a.jsxs("div",{className:"flex items-center gap-2 shrink-0 max-[550px]:w-full max-[550px]:justify-end max-[550px]:mt-1",children:[a.jsx("span",{title:r("maintenance:update")?void 0:i("maintenance.noPermissionUpdate"),children:a.jsx(Ln,{checked:t.enabled,onChange:f=>n(t.id,f),disabled:!r("maintenance:update")})}),a.jsxs(De,{size:"sm",variant:t.is_due?"primary":"secondary",onClick:()=>e(t.id),disabled:!t.enabled||!r("maintenance:update"),title:r("maintenance:update")?void 0:i("maintenance.noPermissionPerform"),className:"!px-3",children:[a.jsx(co,{className:"w-3.5 h-3.5"}),i("common.reset")]})]})]})})}function Qnt({overview:t,onPerform:e,onToggle:n,onSetHours:r,hasPermission:i,t:s}){const[o,l]=w.useState(!1),[c,d]=w.useState(!1),[u,m]=w.useState(t.total_print_hours.toFixed(1)),p=[...t.maintenance_items].sort((v,b)=>v.is_due&&!b.is_due?-1:!v.is_due&&b.is_due?1:v.is_warning&&!b.is_warning?-1:!v.is_warning&&b.is_warning?1:v.maintenance_type_id-b.maintenance_type_id),f=p.find(v=>v.enabled&&(v.is_due||v.is_warning)),y=()=>{const v=parseFloat(u);!isNaN(v)&&v>=0&&(r(t.printer_id,v),d(!1))};return a.jsxs(Tt,{className:"overflow-hidden",children:[a.jsxs("div",{className:"p-5",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-4",children:[a.jsx("h2",{className:"text-xl font-semibold text-white",children:t.printer_name}),a.jsxs("div",{className:"flex items-center gap-2",children:[t.due_count>0&&a.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:[a.jsx(Dn,{className:"w-3 h-3"}),s("maintenance.overdueCount",{count:t.due_count})]}),t.warning_count>0&&a.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:[a.jsx(Yn,{className:"w-3 h-3"}),s("maintenance.dueSoonCount",{count:t.warning_count})]}),t.due_count===0&&t.warning_count===0&&a.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:[a.jsx(Ur,{className:"w-3 h-3"}),s("maintenance.allGood")]})]})]}),a.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?a.jsx(dc,{className:"w-4 h-4"}):a.jsx(On,{className:"w-4 h-4"}),s(o?"common.collapse":"common.expand")]})]}),a.jsxs("div",{className:"flex items-center gap-6 mt-4",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:"p-2 bg-bambu-dark/50 rounded-lg",children:a.jsx(jd,{className:"w-4 h-4 text-bambu-gray"})}),c?a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("input",{type:"number",value:u,onChange:v=>m(v.target.value),onKeyDown:v=>{v.key==="Enter"&&y(),v.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}),a.jsx("span",{className:"text-xs text-bambu-gray",children:s("common.hours")}),a.jsx(De,{size:"sm",onClick:y,children:s("common.save")}),a.jsx(De,{size:"sm",variant:"secondary",onClick:()=>d(!1),children:s("common.cancel")})]}):a.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:[a.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"),a.jsx(dg,{className:`w-3 h-3 text-bambu-gray ${i("maintenance:update")?"group-hover:text-bambu-green":""}`})]}),a.jsx("div",{className:"text-xs text-bambu-gray",children:s("maintenance.totalPrintTime")})]})]}),a.jsx("div",{className:"w-px h-10 bg-bambu-dark-tertiary"}),f&&a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:`p-2 rounded-lg ${f.is_due?"bg-red-500/20":"bg-amber-500/20"}`,children:(()=>{const v=Z0(f.maintenance_type_icon);return a.jsx(v,{className:`w-4 h-4 ${f.is_due?"text-red-400":"text-amber-400"}`})})()}),a.jsxs("div",{children:[a.jsx("div",{className:`text-sm font-medium ${f.is_due?"text-red-400":"text-amber-400"}`,children:f.maintenance_type_name}),a.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&&a.jsx(Mt,{className:"pt-0 border-t border-bambu-dark-tertiary",children:a.jsx("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-3 pt-4",children:p.map(v=>a.jsx(Ynt,{item:v,onPerform:e,onToggle:n,hasPermission:i,t:s},v.id))})})]})}function Znt({overview:t,types:e,onUpdateInterval:n,onAddType:r,onUpdateType:i,onDeleteType:s,onRestoreDefaults:o,isRestoringDefaults:l,onAssignType:c,onRemoveItem:d,hasPermission:u,t:m}){const[p,f]=w.useState(null),[y,v]=w.useState(""),[b,g]=w.useState("hours"),[_,C]=w.useState(!1),[P,N]=w.useState(""),[A,T]=w.useState("100"),[F,k]=w.useState("hours"),[D,H]=w.useState("Wrench"),[z,Q]=w.useState(""),[L,te]=w.useState(new Set),[ie,J]=w.useState(null),[oe,fe]=w.useState(null),re=w.useMemo(()=>t?t.map(B=>({id:B.printer_id,name:B.printer_name})):[],[t]),W=B=>t?t.filter(R=>R.maintenance_items.some(ae=>ae.maintenance_type_id===B)).map(R=>({printerId:R.printer_id,printerName:R.printer_name,itemId:R.maintenance_items.find(ae=>ae.maintenance_type_id===B)?.id})):[],ne=B=>{if(!t)return[];const R=new Set(W(B).map(ae=>ae.printerId));return re.filter(ae=>!R.has(ae.id))},[me,be]=w.useState(null),[Ce,q]=w.useState(""),[Y,E]=w.useState(""),[j,O]=w.useState("hours"),[K,U]=w.useState("Wrench"),[ue,I]=w.useState(""),G=B=>{be(B),q(B.name),E(B.default_interval_hours.toString()),O(B.interval_type||"hours"),U(B.icon||"Wrench"),I(B.wiki_url||"")},X=()=>{me&&Ce.trim()&&parseFloat(Y)>0&&(i(me.id,{name:Ce.trim(),default_interval_hours:parseFloat(Y),interval_type:j,icon:K,wiki_url:ue.trim()||null}),be(null))},V=(B,R,ae)=>{const _e=parseFloat(y);if(!isNaN(_e)&&_e>0){const Se=Math.abs(_e-R)<.01?null:_e;n(B,{custom_interval_hours:Se,custom_interval_type:b!==ae?b:null})}f(null)},ee=B=>{B.preventDefault(),P.trim()&&parseFloat(A)>0&&L.size>0&&(r({name:P.trim(),default_interval_hours:parseFloat(A),interval_type:F,icon:D,wiki_url:z.trim()||null},Array.from(L)),N(""),T("100"),k("hours"),Q(""),te(new Set),C(!1))},se=B=>{te(R=>{const ae=new Set(R);return ae.has(B)?ae.delete(B):ae.add(B),ae})},ge=t?.map(B=>({printerId:B.printer_id,printerName:B.printer_name,items:B.maintenance_items.sort((R,ae)=>R.maintenance_type_id-ae.maintenance_type_id)})).sort((B,R)=>B.printerName.localeCompare(R.printerName))||[],he=e.filter(B=>B.is_system),le=e.filter(B=>!B.is_system);return a.jsxs("div",{className:"space-y-8",children:[a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center justify-between mb-4",children:[a.jsxs("div",{children:[a.jsx("h2",{className:"text-lg font-semibold text-white",children:m("maintenance.maintenanceTypes")}),a.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:m("maintenance.maintenanceTypesDescription")})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(De,{variant:"secondary",onClick:o,disabled:!u("maintenance:delete")||l,title:u("maintenance:delete")?void 0:m("maintenance.noPermissionDeleteTypes"),children:m("maintenance.restoreDefaults")}),a.jsxs(De,{onClick:()=>C(!_),disabled:!u("maintenance:create"),title:u("maintenance:create")?void 0:m("maintenance.noPermissionEditTypes"),children:[a.jsx(sr,{className:"w-4 h-4"}),m("maintenance.addCustomType")]})]})]}),_&&a.jsx(Tt,{className:"mb-6",children:a.jsx(Mt,{className:"py-4",children:a.jsxs("form",{onSubmit:ee,children:[a.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4",children:[a.jsxs("div",{className:"lg:col-span-2",children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:m("common.name")}),a.jsx("input",{type:"text",value:P,onChange:B=>N(B.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})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:m("maintenance.intervalType")}),a.jsxs("select",{value:F,onChange:B=>{k(B.target.value),B.target.value==="days"?T("30"):T("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:[a.jsx("option",{value:"hours",children:m("maintenance.printHours")}),a.jsx("option",{value:"days",children:m("maintenance.calendarDays")})]})]}),a.jsxs("div",{children:[a.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")})}),a.jsx("input",{type:"number",value:A,onChange:B=>T(B.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"})]})]}),a.jsx("div",{className:"mt-4 flex items-end justify-between",children:a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:m("maintenance.icon")}),a.jsx("div",{className:"flex gap-1",children:Object.keys(C0).map(B=>{const R=C0[B];return a.jsx("button",{type:"button",onClick:()=>H(B),className:`p-2 rounded-lg transition-colors ${D===B?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary"}`,children:a.jsx(R,{className:"w-4 h-4"})},B)})})]})}),a.jsxs("div",{className:"mt-4",children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:m("maintenance.documentationLink")}),a.jsx("input",{type:"url",value:z,onChange:B=>Q(B.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/..."})]}),a.jsxs("div",{className:"mt-4",children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:m("maintenance.assignToPrinters")}),a.jsx("div",{className:"flex flex-wrap gap-2",children:re.map(B=>a.jsx("button",{type:"button",onClick:()=>se(B.id),className:`px-3 py-1.5 rounded-lg text-sm transition-colors ${L.has(B.id)?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary"}`,children:B.name},B.id))}),L.size===0&&a.jsx("p",{className:"text-xs text-orange-400 mt-1",children:m("maintenance.selectAtLeastOnePrinter")})]}),a.jsxs("div",{className:"mt-4 flex justify-end gap-2",children:[a.jsx(De,{type:"button",variant:"secondary",onClick:()=>{C(!1),te(new Set)},children:m("common.cancel")}),a.jsx(De,{type:"submit",disabled:!P.trim()||L.size===0,children:m("maintenance.addType")})]})]})})}),a.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3",children:[he.map(B=>{const R=Z0(B.icon),ae=B.interval_type||"hours";return a.jsx("div",{className:"bg-bambu-dark-secondary rounded-xl p-4 border border-bambu-dark-tertiary",children:a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:"p-2.5 bg-bambu-dark rounded-lg",children:a.jsx(R,{className:"w-5 h-5 text-bambu-gray"})}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("div",{className:"text-sm font-medium text-white truncate",children:B.name}),a.jsxs("div",{className:"text-xs text-bambu-gray mt-0.5 flex items-center gap-1",children:[ae==="days"?a.jsx(na,{className:"w-3 h-3"}):a.jsx(jd,{className:"w-3 h-3"}),M3(B.default_interval_hours,ae,m)]})]}),a.jsx("button",{onClick:()=>{u("maintenance:delete")&&fe(B)},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:a.jsx(en,{className:"w-4 h-4"})})]})},B.id)}),le.map(B=>{const R=Z0(B.icon),ae=B.interval_type||"hours";if(me?.id===B.id)return a.jsx("div",{className:"bg-bambu-dark-secondary rounded-xl p-4 border border-bambu-green",children:a.jsxs("div",{className:"space-y-3",children:[a.jsx("input",{type:"text",value:Ce,onChange:ye=>q(ye.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}),a.jsxs("div",{className:"flex gap-2",children:[a.jsxs("select",{value:j,onChange:ye=>O(ye.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:[a.jsx("option",{value:"hours",children:m("maintenance.printHours")}),a.jsx("option",{value:"days",children:m("maintenance.calendarDays")})]}),a.jsx("input",{type:"number",value:Y,onChange:ye=>E(ye.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"})]}),a.jsx("div",{className:"flex flex-wrap gap-1",children:Object.keys(C0).map(ye=>{const Ae=C0[ye];return a.jsx("button",{type:"button",onClick:()=>U(ye),className:`p-1.5 rounded transition-colors ${K===ye?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:a.jsx(Ae,{className:"w-3.5 h-3.5"})},ye)})}),a.jsx("input",{type:"url",value:ue,onChange:ye=>I(ye.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")}),a.jsxs("div",{className:"flex gap-2",children:[a.jsx(De,{size:"sm",onClick:X,disabled:!Ce.trim(),children:m("common.save")}),a.jsx(De,{size:"sm",variant:"secondary",onClick:()=>be(null),children:m("common.cancel")})]})]})},B.id);const Se=W(B.id),ve=ne(B.id),Te=ie===B.id;return a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-xl p-4 border border-bambu-green/30",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:"p-2.5 bg-bambu-green/20 rounded-lg",children:a.jsx(R,{className:"w-5 h-5 text-bambu-green"})}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:"text-sm font-medium text-white truncate",children:B.name}),a.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")})]}),a.jsxs("div",{className:"text-xs text-bambu-gray mt-0.5 flex items-center gap-1",children:[ae==="days"?a.jsx(na,{className:"w-3 h-3"}):a.jsx(jd,{className:"w-3 h-3"}),M3(B.default_interval_hours,ae,m)]})]}),a.jsxs("button",{onClick:()=>J(Te?null:B.id),className:`px-2 py-1 rounded-lg border transition-colors flex items-center gap-1 ${Se.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:Se.length}),children:[a.jsx(Er,{className:"w-3 h-3"}),a.jsx("span",{className:"text-xs font-medium",children:Se.length}),a.jsx(On,{className:`w-3 h-3 transition-transform ${Te?"rotate-180":""}`})]}),a.jsx("button",{onClick:()=>G(B),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:a.jsx(dg,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>{confirm(m("maintenance.deleteTypeConfirm",{name:B.name}))&&s(B.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:a.jsx(en,{className:"w-4 h-4"})})]}),Te&&a.jsxs("div",{className:"mt-3 pt-3 border-t border-bambu-dark-tertiary",children:[a.jsx("p",{className:"text-xs text-bambu-gray mb-2",children:m("maintenance.assignedToPrinters")}),Se.length===0?a.jsx("p",{className:"text-xs text-orange-400",children:m("maintenance.noPrintersAssigned")}):a.jsx("div",{className:"flex flex-wrap gap-1 mb-2",children:Se.map(ye=>a.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-1 bg-bambu-dark rounded text-xs text-white",children:[ye.printerName,a.jsx("button",{onClick:()=>ye.itemId&&d(ye.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:"×"})]},ye.printerId))}),ve.length>0&&a.jsxs("div",{className:"flex flex-wrap gap-1",children:[a.jsx("span",{className:"text-xs text-bambu-gray mr-1",children:m("maintenance.addPrinterShort")}),ve.map(ye=>a.jsxs("button",{onClick:()=>c(ye.id,B.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:["+ ",ye.name]},ye.id))]})]})]},B.id)})]})]}),ge.length>0&&a.jsxs("div",{children:[a.jsxs("div",{className:"mb-4",children:[a.jsx("h2",{className:"text-lg font-semibold text-white",children:m("maintenance.intervalOverrides")}),a.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:m("maintenance.intervalOverridesDescription")})]}),a.jsx("div",{className:"space-y-4",children:ge.map(B=>a.jsx(Tt,{children:a.jsxs(Mt,{className:"py-4",children:[a.jsx("h3",{className:"text-sm font-medium text-white mb-3",children:B.printerName}),a.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-2",children:B.items.map(R=>{const ae=Z0(R.maintenance_type_icon),_e=e.find(Ae=>Ae.id===R.maintenance_type_id),Se=_e?.default_interval_hours||R.interval_hours,ve=_e?.interval_type||"hours",Te=R.interval_type||"hours",ye=p===R.id;return a.jsxs("div",{className:"flex items-center gap-2 p-2.5 bg-bambu-dark rounded-lg",children:[a.jsx(ae,{className:"w-4 h-4 text-bambu-gray shrink-0"}),a.jsx("span",{className:"text-xs text-bambu-gray flex-1 truncate",children:R.maintenance_type_name}),ye?a.jsxs("div",{className:"flex items-center gap-1",children:[b==="days"?a.jsx(na,{className:"w-3.5 h-3.5 text-bambu-gray shrink-0"}):a.jsx(jd,{className:"w-3.5 h-3.5 text-bambu-gray shrink-0"}),a.jsxs("select",{value:b,onChange:Ae=>g(Ae.target.value),className:"px-1.5 py-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-xs",children:[a.jsx("option",{value:"hours",children:m("maintenance.printHours")}),a.jsx("option",{value:"days",children:m("maintenance.calendarDays")})]}),a.jsx("input",{type:"number",value:y,onChange:Ae=>v(Ae.target.value),onKeyDown:Ae=>{Ae.key==="Enter"&&V(R.id,Se,ve),Ae.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"}),a.jsx(De,{size:"sm",onClick:()=>V(R.id,Se,ve),children:"OK"})]}):a.jsxs("button",{onClick:()=>{u("maintenance:update")&&(f(R.id),v(R.interval_hours.toString()),g(Te))},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:[Te==="days"?a.jsx(na,{className:"w-3 h-3"}):a.jsx(jd,{className:"w-3 h-3"}),M3(R.interval_hours,Te,m),a.jsx(dg,{className:"w-3 h-3 text-bambu-gray"})]})]},R.id)})})]})},B.printerId))})]}),ge.length===0&&a.jsx(Tt,{children:a.jsxs(Mt,{className:"text-center py-12",children:[a.jsx(Yn,{className:"w-12 h-12 mx-auto mb-4 text-bambu-gray/30"}),a.jsx("p",{className:"text-bambu-gray",children:m("common.noPrinters")}),a.jsx("p",{className:"text-sm text-bambu-gray/70 mt-1",children:m("maintenance.intervalOverridesDescription")})]})}),oe&&a.jsx(yn,{title:m("maintenance.deleteSystemTypeTitle"),message:m("maintenance.deleteSystemTypeMessage",{name:oe.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(oe.id),fe(null)},onCancel:()=>fe(null)})]})}function Jnt(){const{t}=Ft(),e=nn(),{showToast:n}=hn(),{hasPermission:r}=Sr(),[i,s]=w.useState("status"),{data:o,isLoading:l}=Xe({queryKey:["maintenanceOverview"],queryFn:de.getMaintenanceOverview}),{data:c}=Xe({queryKey:["maintenanceTypes"],queryFn:de.getMaintenanceTypes}),d=it({mutationFn:({id:A,notes:T})=>de.performMaintenance(A,T),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]}),e.invalidateQueries({queryKey:["maintenanceSummary"]}),n(t("maintenance.maintenanceComplete"))},onError:A=>{n(A.message,"error")}}),u=it({mutationFn:({id:A,data:T})=>de.updateMaintenanceItem(A,T),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]})},onError:A=>{n(A.message,"error")}}),m=it({mutationFn:({id:A,data:T})=>de.updateMaintenanceType(A,T),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceTypes"]}),e.invalidateQueries({queryKey:["maintenanceOverview"]}),n(t("maintenance.typeUpdated"))},onError:A=>{n(A.message,"error")}}),p=it({mutationFn:de.deleteMaintenanceType,onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceTypes"]}),e.invalidateQueries({queryKey:["maintenanceOverview"]}),n(t("maintenance.typeDeleted"))},onError:A=>{n(A.message,"error")}}),f=it({mutationFn:de.restoreDefaultMaintenanceTypes,onSuccess:A=>{e.invalidateQueries({queryKey:["maintenanceTypes"]}),e.invalidateQueries({queryKey:["maintenanceOverview"]}),n(t("maintenance.defaultsRestored",{count:A.restored}))},onError:A=>{n(A.message,"error")}}),y=it({mutationFn:({printerId:A,hours:T})=>de.setPrinterHours(A,T),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]}),e.invalidateQueries({queryKey:["maintenanceSummary"]}),n(t("maintenance.printHoursUpdated"))},onError:A=>{n(A.message,"error")}}),v=it({mutationFn:({printerId:A,typeId:T})=>de.assignMaintenanceType(A,T),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]}),n(t("maintenance.printerAssigned"))},onError:A=>{n(A.message,"error")}}),b=it({mutationFn:de.removeMaintenanceItem,onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]}),n(t("maintenance.printerRemoved"))},onError:A=>{n(A.message,"error")}}),g=A=>{d.mutate({id:A})},_=(A,T)=>{u.mutate({id:A,data:{enabled:T}})},C=(A,T)=>{y.mutate({printerId:A,hours:T})};if(l)return a.jsx("div",{className:"p-4 md:p-8 flex justify-center",children:a.jsx(pt,{className:"w-8 h-8 text-bambu-green animate-spin"})});const P=o?.reduce((A,T)=>A+T.due_count,0)||0,N=o?.reduce((A,T)=>A+T.warning_count,0)||0;return a.jsxs("div",{className:"p-4 md:p-8",children:[a.jsxs("div",{className:"mb-6",children:[a.jsx("h1",{className:"text-2xl font-bold text-white",children:t("maintenance.title")}),a.jsx("p",{className:"text-bambu-gray text-sm mt-1",children:i==="status"?a.jsxs(a.Fragment,{children:[P>0&&a.jsx("span",{className:"text-red-400",children:t("maintenance.dueCount",{count:P})}),P>0&&N>0&&" · ",N>0&&a.jsx("span",{className:"text-amber-400",children:t("maintenance.warningCount",{count:N})}),P===0&&N===0&&a.jsx("span",{className:"text-bambu-green",children:t("maintenance.allOk")})]}):t("maintenance.configureSettings")})]}),a.jsxs("div",{className:"flex gap-1 mb-6 border-b border-bambu-dark-tertiary",children:[a.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")}),a.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"?a.jsx("div",{className:"space-y-6",children:o&&o.length>0?[...o].sort((A,T)=>{const F=A.due_count*10+A.warning_count,k=T.due_count*10+T.warning_count;return F!==k?k-F:A.printer_name.localeCompare(T.printer_name)}).map(A=>a.jsx(Qnt,{overview:A,onPerform:g,onToggle:_,onSetHours:C,hasPermission:r,t},A.printer_id)):a.jsx(Tt,{children:a.jsxs(Mt,{className:"text-center py-16",children:[a.jsx(mg,{className:"w-16 h-16 mx-auto mb-4 text-bambu-gray/30"}),a.jsx("p",{className:"text-lg font-medium text-white mb-2",children:t("common.noPrinters")}),a.jsx("p",{className:"text-bambu-gray",children:t("maintenance.configureSettings")})]})})}):a.jsx(Znt,{overview:o,types:c||[],onUpdateInterval:(A,T)=>u.mutate({id:A,data:T}),onAddType:async(A,T)=>{const F=await de.createMaintenanceType(A);for(const k of T)await de.assignMaintenanceType(k,F.id);e.invalidateQueries({queryKey:["maintenanceTypes"]}),e.invalidateQueries({queryKey:["maintenanceOverview"]}),n(t("maintenance.typeUpdated"))},onUpdateType:(A,T)=>m.mutate({id:A,data:T}),onDeleteType:A=>p.mutate(A),onRestoreDefaults:()=>f.mutate(),isRestoringDefaults:f.isPending,onAssignType:(A,T)=>v.mutate({printerId:A,typeId:T}),onRemoveItem:A=>b.mutate(A),hasPermission:r,t})]})}const _Y=["#ef4444","#f97316","#eab308","#22c55e","#06b6d4","#3b82f6","#8b5cf6","#ec4899","#6b7280"];function Hle({project:t,onClose:e,onSave:n,isLoading:r,currencySymbol:i,t:s}){const[o,l]=w.useState(t?.name||""),[c,d]=w.useState(t?.description||""),[u,m]=w.useState(t?.color||_Y[0]),[p,f]=w.useState(t?.target_count?.toString()||""),[y,v]=w.useState(t?.target_parts_count?.toString()||""),[b,g]=w.useState(t?.status||"active"),[_,C]=w.useState(t?.tags||""),[P,N]=w.useState(t?.due_date?.split("T")[0]||""),[A,T]=w.useState(t?.priority||"normal"),[F,k]=w.useState(t?.budget?.toString()||""),D=H=>{H.preventDefault(),n({name:o.trim(),description:c.trim()||void 0,color:u,target_count:p?parseInt(p,10):void 0,target_parts_count:y?parseInt(y,10):void 0,tags:_.trim()||void 0,due_date:P||void 0,priority:A,budget:F.trim()?parseFloat(F):null,...t&&{status:b}})};return a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-md border border-bambu-dark-tertiary",children:[a.jsx("div",{className:"p-4 border-b border-bambu-dark-tertiary",children:a.jsx("h2",{className:"text-lg font-semibold text-white",children:s(t?"projects.editProject":"projects.newProject")})}),a.jsxs("form",{onSubmit:D,className:"p-4 space-y-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("common.name")}),a.jsx("input",{type:"text",value:o,onChange:H=>l(H.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})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("common.description")}),a.jsx("textarea",{value:c,onChange:H=>d(H.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})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("projects.color")}),a.jsx("div",{className:"flex gap-2 flex-wrap",children:_Y.map(H=>a.jsx("button",{type:"button",onClick:()=>m(H),className:`w-8 h-8 rounded-full transition-transform ${u===H?"ring-2 ring-white ring-offset-2 ring-offset-bambu-dark-secondary scale-110":""}`,style:{backgroundColor:H}},H))})]}),a.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("projects.targetPlates")}),a.jsx("input",{type:"number",value:p,onChange:H=>f(H.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"}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:s("projects.targetPlatesHelp")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("projects.targetParts")}),a.jsx("input",{type:"number",value:y,onChange:H=>v(H.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"}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:s("projects.targetPartsHelp")})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("projects.tagsLabel")}),a.jsx("input",{type:"text",value:_,onChange:H=>C(H.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")})]}),a.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("projects.dueDate")}),a.jsx("input",{type:"date",value:P,onChange:H=>N(H.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"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("projects.priority")}),a.jsxs("select",{value:A,onChange:H=>T(H.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:[a.jsx("option",{value:"low",children:s("projects.priorityLow")}),a.jsx("option",{value:"normal",children:s("projects.priorityNormal")}),a.jsx("option",{value:"high",children:s("projects.priorityHigh")}),a.jsx("option",{value:"urgent",children:s("projects.priorityUrgent")})]})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("projectDetail.cost.budget")}),a.jsxs("div",{className:"relative",children:[a.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-bambu-gray pointer-events-none",children:i}),a.jsx("input",{type:"number",step:"0.01",min:"0",value:F,onChange:H=>k(H.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&&a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("common.status")}),a.jsxs("select",{value:b,onChange:H=>g(H.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:[a.jsx("option",{value:"active",children:s("projects.statusActive")}),a.jsx("option",{value:"completed",children:s("projects.statusCompleted")}),a.jsx("option",{value:"archived",children:s("projects.statusArchived")})]})]}),a.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[a.jsx(De,{type:"button",variant:"secondary",onClick:e,children:s("common.cancel")}),a.jsx(De,{type:"submit",disabled:!o.trim()||r,children:r?a.jsx(pt,{className:"w-4 h-4 animate-spin"}):s(t?"common.save":"projects.create")})]})]})]})})}function ert({project:t,onClick:e,onEdit:n,onDelete:r,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]=w.useState(!1),f=c?{icon:ul,color:"text-bambu-green",bg:"bg-bambu-green/10"}:d?{icon:so,color:"text-bambu-gray",bg:"bg-bambu-gray/10"}:t.queue_count>0?{icon:Yn,color:"text-blue-400",bg:"bg-blue-400/10"}:{icon:Bs,color:"text-bambu-gray",bg:"bg-bambu-gray/10"};return a.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:[a.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`}}),a.jsxs("div",{className:"p-5 pl-6",children:[a.jsxs("div",{className:"flex items-start justify-between mb-4",children:[a.jsxs("div",{className:"flex items-center gap-3 min-w-0 flex-1",children:[a.jsx("div",{className:`p-2 rounded-lg ${f.bg} flex-shrink-0`,children:a.jsx(f.icon,{className:`w-5 h-5 ${f.color}`})}),a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[a.jsx("h3",{className:"font-semibold text-white truncate",children:t.name}),t.target_parts_count?a.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?a.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?a.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&&a.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&&a.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&&a.jsx("p",{className:"text-sm text-bambu-gray/70 mt-1 line-clamp-1",children:t.description}),t.archives&&t.archives.length>0&&(()=>{const y=t.archives.map(_=>_.filament_type).filter(Boolean).flatMap(_=>_.split(",").map(C=>C.trim())).filter(Boolean),v=[...new Set(y)],b=t.archives.map(_=>_.filament_color).filter(Boolean).flatMap(_=>_.split(",").map(C=>C.trim())).filter(_=>_.startsWith("#")||/^[0-9A-Fa-f]{6}$/.test(_)),g=[...new Set(b)];return v.length===0&&g.length===0?null:a.jsxs("div",{className:"flex items-center gap-2 mt-1.5",children:[v.slice(0,3).map(_=>a.jsx("span",{className:"text-[10px] px-1.5 py-0.5 bg-bambu-dark text-bambu-gray rounded",children:_},_)),g.length>0&&a.jsxs("div",{className:"flex items-center gap-0.5",children:[g.slice(0,5).map(_=>a.jsx("div",{className:"w-3 h-3 rounded-full border border-black/20",style:{backgroundColor:_.startsWith("#")?_:`#${_}`},title:_},_)),g.length>5&&a.jsxs("span",{className:"text-[10px] text-bambu-gray ml-0.5",children:["+",g.length-5]})]})]})})()]})]}),a.jsxs("div",{className:"relative",onClick:y=>y.stopPropagation(),children:[a.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:a.jsx(Jh,{className:"w-4 h-4"})}),u&&a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>m(!1)}),a.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:[a.jsxs("button",{className:`w-full px-3 py-2 text-left text-sm flex items-center gap-2 ${i("projects:update")?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{i("projects:update")&&(n(),m(!1))},disabled:!i("projects:update"),title:i("projects:update")?void 0:s("projects.noEditPermission"),children:[a.jsx(dg,{className:"w-4 h-4"}),s("common.edit")]}),a.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")&&(r(),m(!1))},disabled:!i("projects:delete"),title:i("projects:delete")?void 0:s("projects.noDeletePermission"),children:[a.jsx(en,{className:"w-4 h-4"}),s("common.delete")]})]})]})]})]}),a.jsx("div",{className:"mb-4",children:t.target_count||t.target_parts_count?a.jsxs("div",{className:"space-y-3",children:[t.target_count&&a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center justify-between text-xs mb-1",children:[a.jsx("span",{className:"text-bambu-gray",children:s("projects.plates")}),a.jsxs("span",{className:o>=100?"text-bambu-green font-medium":"text-white",children:[t.archive_count," / ",t.target_count]})]}),a.jsx("div",{className:"h-2 bg-bambu-dark/80 rounded-full overflow-hidden backdrop-blur-sm",children:a.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&&a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center justify-between text-xs mb-1",children:[a.jsx("span",{className:"text-bambu-gray",children:s("projects.parts")}),a.jsxs("span",{className:l>=100?"text-bambu-green font-medium":"text-white",children:[t.completed_count," / ",t.target_parts_count]})]}),a.jsx("div",{className:"h-2 bg-bambu-dark/80 rounded-full overflow-hidden backdrop-blur-sm",children:a.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&&a.jsxs("div",{className:"text-xs text-red-400",children:[t.failed_count," ",s("projects.failed")]})]}):t.completed_count>0||t.failed_count>0?a.jsxs("div",{className:"flex items-center gap-4 text-xs",children:[t.completed_count>0&&a.jsxs("div",{className:"flex items-center gap-1.5 text-bambu-gray",children:[a.jsx(so,{className:"w-3.5 h-3.5"}),a.jsxs("span",{children:[t.completed_count," ",s("projects.completed")]})]}),t.failed_count>0&&a.jsxs("div",{className:"flex items-center gap-1.5 text-red-400",children:[a.jsx(Dn,{className:"w-3.5 h-3.5"}),a.jsxs("span",{children:[t.failed_count," ",s("projects.failed")]})]}),t.queue_count>0&&a.jsxs("div",{className:"flex items-center gap-1.5 text-blue-400",children:[a.jsx(Yn,{className:"w-3.5 h-3.5"}),a.jsxs("span",{children:[t.queue_count," ",s("projects.inQueue")]})]})]}):a.jsx("div",{className:"text-xs text-bambu-gray/60 italic",children:s("projects.noPrintsYet")})}),t.archives&&t.archives.length>0&&a.jsxs("div",{className:"mb-4",children:[a.jsx("div",{className:"grid grid-cols-4 gap-1.5",children:t.archives.slice(0,4).map(y=>a.jsxs("div",{className:"relative aspect-square rounded-lg bg-bambu-dark overflow-hidden border border-bambu-dark-tertiary",title:y.print_name||"Unknown",children:[y.thumbnail_path?a.jsx("img",{src:de.getArchiveThumbnail(y.id),alt:y.print_name||"",className:"w-full h-full object-cover"}):a.jsx("div",{className:"w-full h-full flex items-center justify-center text-bambu-gray/50",children:a.jsx(Ra,{className:"w-6 h-6"})}),y.status==="failed"&&a.jsx("div",{className:"absolute inset-0 bg-red-500/40 flex items-center justify-center",children:a.jsx(Dn,{className:"w-4 h-4 text-white"})})]},y.id))}),t.archive_count>4&&a.jsx("p",{className:"text-xs text-bambu-gray mt-1.5 text-center",children:s("common.more",{count:t.archive_count-4})})]}),a.jsxs("div",{className:"flex items-center justify-between pt-3 border-t border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-4 text-xs text-bambu-gray",children:[a.jsxs("div",{className:"flex items-center gap-1.5",title:s("projects.printJobs"),children:[a.jsx(da,{className:"w-3.5 h-3.5 text-blue-400"}),a.jsxs("span",{children:[t.archive_count," ",s("projects.plates")]})]}),a.jsxs("div",{className:"flex items-center gap-1.5",title:s("projects.partsPrinted"),children:[a.jsx(Ra,{className:"w-3.5 h-3.5 text-bambu-green"}),a.jsxs("span",{children:[t.completed_count," ",s("projects.parts")]})]}),t.failed_count>0&&a.jsxs("div",{className:"flex items-center gap-1.5 text-red-400",title:s("projects.failedParts"),children:[a.jsx(Dn,{className:"w-3.5 h-3.5"}),a.jsx("span",{children:t.failed_count})]}),t.queue_count>0&&a.jsxs("div",{className:"flex items-center gap-1.5 text-yellow-400",title:s("projects.inQueue"),children:[a.jsx(sF,{className:"w-3.5 h-3.5"}),a.jsx("span",{children:t.queue_count})]})]}),a.jsx(ti,{className:"w-4 h-4 text-bambu-gray/50 group-hover:text-bambu-gray transition-colors"})]})]})]})}function trt(){const{t}=Ft(),e=qo(),n=nn(),{showToast:r}=hn(),{hasPermission:i}=Sr(),[s,o]=w.useState(!1),[l,c]=w.useState(),[d,u]=w.useState("active"),[m,p]=w.useState(null),{data:f}=Xe({queryKey:["settings"],queryFn:de.getSettings}),y=Eo(f?.currency||"USD"),{data:v,isLoading:b}=Xe({queryKey:["projects",d==="all"?void 0:d],queryFn:()=>de.getProjects(d==="all"?void 0:d)}),g=it({mutationFn:te=>de.createProject(te),onSuccess:()=>{n.invalidateQueries({queryKey:["projects"]}),o(!1),r(t("projects.toast.created"),"success")},onError:te=>{r(te.message,"error")}}),_=it({mutationFn:({id:te,data:ie})=>de.updateProject(te,ie),onSuccess:()=>{n.invalidateQueries({queryKey:["projects"]}),o(!1),c(void 0),r(t("projects.toast.updated"),"success")},onError:te=>{r(te.message,"error")}}),C=it({mutationFn:te=>de.deleteProject(te),onSuccess:()=>{p(null),r(t("projects.toast.deleted"),"success"),setTimeout(()=>window.location.reload(),100)},onError:te=>{p(null),r(te.message,"error")}}),P=it({mutationFn:te=>de.importProject(te),onSuccess:()=>{n.invalidateQueries({queryKey:["projects"]}),r(t("projects.toast.imported"),"success")},onError:te=>{r(te.message,"error")}}),N=w.useRef(null),A=async()=>{try{const te=await de.getProjects(),ie=await Promise.all(te.map(async re=>await de.exportProjectJson(re.id))),J=new Blob([JSON.stringify(ie,null,2)],{type:"application/json"}),oe=URL.createObjectURL(J),fe=document.createElement("a");fe.href=oe,fe.download=`bambuddy_projects_${new Date().toISOString().split("T")[0]}.json`,fe.click(),URL.revokeObjectURL(oe),r(t("projects.toast.exported"),"success")}catch(te){r(te.message,"error")}},T=()=>{N.current?.click()},F=async te=>{const ie=te.target.files?.[0];if(ie){try{if(ie.name.toLowerCase().endsWith(".zip"))await de.importProjectFile(ie),n.invalidateQueries({queryKey:["projects"]}),r(t("projects.toast.imported"),"success");else{const oe=await ie.text(),fe=JSON.parse(oe),re=Array.isArray(fe)?fe:[fe];for(const W of re)await P.mutateAsync(W);re.length>1&&r(t("projects.toast.multipleImported",{count:re.length}),"success")}}catch(J){r(`${t("projects.toast.importFailed")}: ${J.message}`,"error")}te.target.value=""}},k=te=>{l?_.mutate({id:l.id,data:te}):g.mutate(te)},D=te=>{c(te),o(!0)},H=te=>{e(`/projects/${te.id}`)},z=te=>{p(te)},Q=()=>{m!==null&&C.mutate(m)},L=v?.reduce((te,ie)=>(te[ie.status]=(te[ie.status]||0)+1,te.all=(te.all||0)+1,te),{})||{};return a.jsxs("div",{className:"p-4 md:p-8 space-y-8",children:[a.jsx("input",{ref:N,type:"file",accept:".json,.zip",onChange:F,className:"hidden"}),a.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4",children:[a.jsxs("div",{children:[a.jsxs("h1",{className:"text-2xl font-bold text-white flex items-center gap-3",children:[a.jsx("div",{className:"p-2.5 bg-bambu-green/10 rounded-xl",children:a.jsx(Bs,{className:"w-6 h-6 text-bambu-green"})}),t("projects.title")]}),a.jsx("p",{className:"text-sm text-bambu-gray mt-2 ml-14",children:t("projects.subtitle")})]}),a.jsxs("div",{className:"flex gap-2",children:[a.jsxs(De,{variant:"secondary",onClick:T,disabled:!i("projects:create"),title:i("projects:create")?t("projects.importProject"):t("projects.noImportPermission"),children:[a.jsx(La,{className:"w-4 h-4 mr-2"}),t("projects.import")]}),a.jsxs(De,{variant:"secondary",onClick:A,disabled:!i("projects:read"),title:i("projects:read")?t("projects.exportAll"):t("projects.noExportPermission"),children:[a.jsx(ga,{className:"w-4 h-4 mr-2"}),t("projects.export")]}),a.jsxs(De,{onClick:()=>o(!0),className:"sm:w-auto w-full",disabled:!i("projects:create"),title:i("projects:create")?void 0:t("projects.noCreatePermission"),children:[a.jsx(sr,{className:"w-4 h-4 mr-2"}),t("projects.newProject")]})]})]}),a.jsx("div",{className:"flex gap-1 p-1 bg-bambu-dark rounded-xl w-fit",children:[{key:"active",label:t("projects.statusActive"),icon:Yn},{key:"completed",label:t("projects.statusCompleted"),icon:ul},{key:"archived",label:t("projects.statusArchived"),icon:so},{key:"all",label:t("common.all"),icon:Bs}].map(({key:te,label:ie,icon:J})=>a.jsxs("button",{onClick:()=>u(te),className:`flex items-center gap-2 px-4 py-2 text-sm rounded-lg transition-all ${d===te?"bg-bambu-card text-white shadow-sm":"text-bambu-gray hover:text-white"}`,children:[a.jsx(J,{className:"w-4 h-4"}),a.jsx("span",{children:ie}),L[te]>0&&a.jsx("span",{className:`text-xs px-1.5 py-0.5 rounded-full ${d===te?"bg-bambu-green/20 text-bambu-green":"bg-bambu-dark-tertiary"}`,children:L[te]})]},te))}),b?a.jsx("div",{className:"flex items-center justify-center py-20",children:a.jsxs("div",{className:"flex flex-col items-center gap-3",children:[a.jsx(pt,{className:"w-8 h-8 animate-spin text-bambu-green"}),a.jsx("p",{className:"text-sm text-bambu-gray",children:t("projects.loading")})]})}):v?.length===0?a.jsxs("div",{className:"flex flex-col items-center justify-center py-20 px-4",children:[a.jsx("div",{className:"p-4 bg-bambu-dark rounded-2xl mb-4",children:a.jsx(Bs,{className:"w-12 h-12 text-bambu-gray/50"})}),a.jsx("h3",{className:"text-lg font-medium text-white mb-2",children:d==="all"?t("projects.noProjects"):t("projects.noProjectsFiltered",{status:d})}),a.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"&&a.jsxs(De,{onClick:()=>o(!0),disabled:!i("projects:create"),title:i("projects:create")?void 0:t("projects.noCreatePermission"),children:[a.jsx(sr,{className:"w-4 h-4 mr-2"}),t("projects.createFirstButton")]})]}):a.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-8",children:v?.map(te=>a.jsx(ert,{project:te,onClick:()=>H(te),onEdit:()=>D(te),onDelete:()=>z(te.id),hasPermission:i,t},te.id))}),m!==null&&a.jsx(yn,{title:t("projects.deleteProject"),message:t("projects.deleteConfirm"),confirmText:t("projects.deleteProject"),variant:"danger",onConfirm:Q,onCancel:()=>p(null)}),s&&a.jsx(Hle,{project:l,onClose:()=>{o(!1),c(void 0)},onSave:k,isLoading:g.isPending||_.isPending,currencySymbol:y,t})]})}function nrt(t){const e=t.toLowerCase();return e.endsWith(".gcode")||e.endsWith(".gcode.3mf")}function rrt(t){return t>=1e3?`${(t/1e3).toFixed(2)}kg`:`${Math.round(t)}g`}function art({status:t,t:e}){const n={active:"bg-bambu-green/20 text-bambu-green",completed:"bg-blue-500/20 text-blue-400",archived:"bg-bambu-gray/20 text-bambu-gray"},r=n[t]||n.active,i={active:e("projectDetail.status.active"),completed:e("projectDetail.status.completed"),archived:e("projectDetail.status.archived")};return a.jsx("span",{className:`px-2 py-1 rounded text-sm font-medium ${r}`,children:i[t]||t.charAt(0).toUpperCase()+t.slice(1)})}function kY({icon:t,label:e,value:n,subValue:r,hint:i,color:s="text-bambu-gray"}){return a.jsx(Tt,{children:a.jsx(Mt,{className:"p-4",children:a.jsxs("div",{className:"flex items-center gap-3",title:i,children:[a.jsx("div",{className:`p-2 rounded-lg bg-bambu-dark ${s}`,children:a.jsx(t,{className:"w-5 h-5"})}),a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-bambu-gray",children:e}),a.jsx("p",{className:"text-xl font-semibold text-white",children:n}),r&&a.jsx("p",{className:"text-xs text-bambu-gray/70",children:r})]})]})})})}function irt({archives:t,t:e}){return t.length===0?a.jsxs("div",{className:"text-center py-8 text-bambu-gray",children:[a.jsx(Ra,{className:"w-12 h-12 mx-auto mb-2 opacity-50"}),a.jsx("p",{children:e("projectDetail.noPrints")})]}):a.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6 gap-3",children:t.map(n=>a.jsxs(Do,{to:`/archives?search=${encodeURIComponent(n.print_name||"")}`,className:"group relative aspect-square rounded-lg bg-bambu-dark border border-bambu-dark-tertiary overflow-hidden hover:border-bambu-green transition-colors",children:[n.thumbnail_path?a.jsx("img",{src:de.getArchiveThumbnail(n.id),alt:n.print_name||"Print",className:"w-full h-full object-cover"}):a.jsx("div",{className:"w-full h-full flex items-center justify-center text-bambu-gray",children:a.jsx(Ra,{className:"w-8 h-8"})}),n.status==="failed"&&a.jsx("div",{className:"absolute inset-0 bg-red-500/30 flex items-center justify-center",children:a.jsx(Ma,{className:"w-8 h-8 text-white"})}),n.status==="completed"&&a.jsx("div",{className:"absolute top-1 right-1",children:a.jsx(yr,{className:"w-4 h-4 text-bambu-green"})}),a.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:a.jsx("p",{className:"text-xs text-white truncate",children:n.print_name||"Unknown"})})]},n.id))})}function srt({priority:t,t:e}){const n={low:{color:"bg-gray-500/20 text-gray-400",label:e("projectDetail.priority.low")},normal:{color:"bg-blue-500/20 text-blue-400",label:e("projectDetail.priority.normal")},high:{color:"bg-orange-500/20 text-orange-400",label:e("projectDetail.priority.high")},urgent:{color:"bg-red-500/20 text-red-400",label:e("projectDetail.priority.urgent")}},{color:r,label:i}=n[t]||n.normal;return a.jsxs("span",{className:`px-2 py-1 rounded text-xs font-medium flex items-center gap-1 ${r}`,children:[t==="urgent"&&a.jsx(Dn,{className:"w-3 h-3"}),i]})}function E3(t,e){if(!t)return null;const n=Zn(t);if(!n)return null;const r=new Date,i=Math.ceil((n.getTime()-r.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 ort(){const{id:t}=Yw(),e=qo(),{t:n}=Ft(),r=nn(),{showToast:i}=hn(),{hasPermission:s}=Sr(),[o,l]=w.useState(!1),[c,d]=w.useState(!1),[u,m]=w.useState(""),[p,f]=w.useState(null),[y,v]=w.useState(null),b=parseInt(t||"0",10),{data:g,isLoading:_,error:C}=Xe({queryKey:["project",b],queryFn:()=>de.getProject(b),enabled:b>0}),{data:P,isLoading:N}=Xe({queryKey:["project-archives",b],queryFn:()=>de.getProjectArchives(b),enabled:b>0}),{data:A,isLoading:T}=Xe({queryKey:["project-bom",b],queryFn:()=>de.getProjectBOM(b),enabled:b>0}),{data:F,isLoading:k}=Xe({queryKey:["project-timeline",b],queryFn:()=>de.getProjectTimeline(b,20),enabled:b>0}),{data:D}=Xe({queryKey:["settings"],queryFn:de.getSettings}),{data:H}=Xe({queryKey:["project-folders",b],queryFn:()=>de.getLibraryFoldersByProject(b),enabled:b>0}),{data:z,isLoading:Q}=Xe({queryKey:["project-files",b],queryFn:()=>de.getLibraryFiles(null,!1,b),enabled:b>0}),L=w.useMemo(()=>{const ce=new Map;for(const xe of z??[])if(xe.folder_id!=null){const Be=ce.get(xe.folder_id)??[];Be.push(xe),ce.set(xe.folder_id,Be)}return ce},[z]),te=Eo(D?.currency||"USD"),ie=D?.time_format||"system",J=it({mutationFn:ce=>de.updateProject(b,ce),onSuccess:()=>{r.invalidateQueries({queryKey:["project",b]}),r.invalidateQueries({queryKey:["projects"]}),l(!1),d(!1),i(n("projectDetail.toast.projectUpdated"),"success")},onError:ce=>{i(ce.message,"error")}}),oe=()=>{m(g?.notes||""),d(!0)},fe=()=>{J.mutate({notes:u})},re=()=>{d(!1),m("")},[W,ne]=w.useState(""),[me,be]=w.useState(1),[Ce,q]=w.useState(""),[Y,E]=w.useState(""),[j,O]=w.useState(""),[K,U]=w.useState(!1),[ue,I]=w.useState(!1),[G,X]=w.useState(null),[V,ee]=w.useState(""),[se,ge]=w.useState(1),[he,le]=w.useState(""),[B,R]=w.useState(""),[ae,_e]=w.useState(""),[Se,ve]=w.useState({isOpen:!1,title:"",message:"",onConfirm:()=>{}}),Te=it({mutationFn:ce=>de.createBOMItem(b,ce),onSuccess:()=>{r.invalidateQueries({queryKey:["project-bom",b]}),r.invalidateQueries({queryKey:["project",b]}),ne(""),be(1),q(""),E(""),O(""),U(!1),i(n("projectDetail.toast.partAdded"),"success")},onError:ce=>i(ce.message,"error")}),ye=it({mutationFn:({itemId:ce,data:xe})=>de.updateBOMItem(b,ce,xe),onSuccess:()=>{r.invalidateQueries({queryKey:["project-bom",b]}),r.invalidateQueries({queryKey:["project",b]}),X(null)},onError:ce=>i(ce.message,"error")}),Ae=it({mutationFn:ce=>de.deleteBOMItem(b,ce),onSuccess:()=>{r.invalidateQueries({queryKey:["project-bom",b]}),r.invalidateQueries({queryKey:["project",b]}),i(n("projectDetail.toast.partRemoved"),"success")},onError:ce=>i(ce.message,"error")}),Le=ce=>{ce.preventDefault(),W.trim()&&Te.mutate({name:W.trim(),quantity_needed:me,unit_price:Ce?parseFloat(Ce):void 0,sourcing_url:Y.trim()||void 0,remarks:j.trim()||void 0})},Me=ce=>{const xe=ce.is_complete?0:ce.quantity_needed;ye.mutate({itemId:ce.id,data:{quantity_acquired:xe}})},Oe=(ce,xe)=>{ve({isOpen:!0,title:n("projectDetail.bom.deletePart"),message:n("projectDetail.bom.deleteConfirm",{name:xe}),onConfirm:()=>{ve(Be=>({...Be,isOpen:!1})),Ae.mutate(ce)}})},Re=ce=>{X(ce),ee(ce.name),ge(ce.quantity_needed),le(ce.unit_price?.toString()||""),R(ce.sourcing_url||""),_e(ce.remarks||"")},$e=ce=>{ce.preventDefault(),!(!G||!V.trim())&&ye.mutate({itemId:G.id,data:{name:V.trim(),quantity_needed:se,unit_price:he?parseFloat(he):void 0,sourcing_url:B.trim()||void 0,remarks:ae.trim()||void 0}})},Ye=()=>{X(null)},tt=async()=>{try{const{blob:ce,filename:xe}=await de.exportProjectZip(Number(b)),Be=URL.createObjectURL(ce),Qe=document.createElement("a");Qe.href=Be,Qe.download=xe||`${g?.name||"project"}_${new Date().toISOString().split("T")[0]}.zip`,Qe.click(),URL.revokeObjectURL(Be),i(n("projectDetail.toast.projectExported"),"success")}catch(ce){i(ce.message,"error")}},pe=it({mutationFn:()=>de.createTemplateFromProject(b),onSuccess:()=>{r.invalidateQueries({queryKey:["projects"]}),i(n("projectDetail.toast.templateCreated"),"success")},onError:ce=>i(ce.message,"error")}),Fe=ce=>pg(ce,ie,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"});if(_)return a.jsx("div",{className:"flex items-center justify-center py-24",children:a.jsx(pt,{className:"w-8 h-8 animate-spin text-bambu-green"})});if(C||!g)return a.jsxs("div",{className:"text-center py-24",children:[a.jsx("p",{className:"text-bambu-gray",children:C?`${n("common.error")}: ${C.message}`:n("projectDetail.notFound")}),a.jsx(De,{variant:"secondary",className:"mt-4",onClick:()=>e("/projects"),children:n("projectDetail.backToProjects")})]});const we=g.stats,Ve=we?.progress_percent??0,je=we?.parts_progress_percent??0;return a.jsxs("div",{className:"p-4 md:p-8 space-y-8",children:[a.jsxs("div",{className:"flex items-center gap-2 text-sm text-bambu-gray",children:[a.jsx(Do,{to:"/projects",className:"hover:text-white transition-colors",children:n("nav.projects")}),a.jsx(ti,{className:"w-4 h-4"}),a.jsx("span",{className:"text-white",children:g.name})]}),a.jsxs("div",{className:"flex items-start justify-between",children:[a.jsxs("div",{className:"flex items-center gap-4",children:[a.jsx("button",{onClick:()=>e("/projects"),className:"p-2 rounded-lg bg-bambu-card hover:bg-bambu-dark-tertiary transition-colors",children:a.jsx(DQ,{className:"w-5 h-5 text-bambu-gray"})}),a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:"w-4 h-4 rounded-full shrink-0",style:{backgroundColor:g.color||"#6b7280"}}),a.jsxs("div",{children:[a.jsx("h1",{className:"text-2xl font-bold text-white",children:g.name}),g.description&&a.jsx("p",{className:"text-bambu-gray mt-1",children:g.description})]})]}),a.jsx(art,{status:g.status,t:n})]}),a.jsxs("div",{className:"flex gap-2",children:[a.jsxs(De,{variant:"secondary",onClick:tt,disabled:!s("projects:read"),title:s("projects:read")?n("projectDetail.exportProject"):n("projectDetail.noExportPermission"),children:[a.jsx(ga,{className:"w-4 h-4 mr-2"}),n("projectDetail.export")]}),a.jsxs(De,{onClick:()=>l(!0),disabled:!s("projects:update"),title:s("projects:update")?void 0:n("projectDetail.noEditPermission"),children:[a.jsx(dg,{className:"w-4 h-4 mr-2"}),n("common.edit")]})]})]}),(g.target_count||g.target_parts_count)&&a.jsx(Tt,{children:a.jsxs(Mt,{className:"p-4 space-y-4",children:[g.target_count&&a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center justify-between mb-2",children:[a.jsx("span",{className:"text-sm text-bambu-gray",children:n("projectDetail.progress.platesProgress")}),a.jsxs("span",{className:"text-sm font-medium text-white",children:[we?.total_archives||0," / ",g.target_count," ",n("projectDetail.progress.printJobs")]})]}),a.jsx("div",{className:"h-3 bg-bambu-dark rounded-full overflow-hidden",children:a.jsx("div",{className:"h-full transition-all duration-500",style:{width:`${Math.min(Ve,100)}%`,backgroundColor:Ve>=100?"#22c55e":g.color||"#6b7280"}})}),a.jsxs("div",{className:"flex justify-between mt-1",children:[a.jsx("span",{className:"text-xs text-bambu-gray/70",children:n("projectDetail.progress.percentComplete",{percent:Ve.toFixed(0)})}),we?.remaining_prints!=null&&we.remaining_prints>0&&a.jsx("span",{className:"text-xs text-bambu-gray/70",children:n("projectDetail.progress.remaining",{count:we.remaining_prints})})]})]}),g.target_parts_count&&a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center justify-between mb-2",children:[a.jsx("span",{className:"text-sm text-bambu-gray",children:n("projectDetail.progress.partsProgress")}),a.jsxs("span",{className:"text-sm font-medium text-white",children:[we?.completed_prints||0," / ",g.target_parts_count," ",n("projectDetail.progress.parts")]})]}),a.jsx("div",{className:"h-3 bg-bambu-dark rounded-full overflow-hidden",children:a.jsx("div",{className:"h-full transition-all duration-500",style:{width:`${Math.min(je,100)}%`,backgroundColor:je>=100?"#22c55e":g.color||"#6b7280"}})}),a.jsxs("div",{className:"flex justify-between mt-1",children:[a.jsx("span",{className:"text-xs text-bambu-gray/70",children:n("projectDetail.progress.percentComplete",{percent:je.toFixed(0)})}),we?.remaining_parts!=null&&we.remaining_parts>0&&a.jsx("span",{className:"text-xs text-bambu-gray/70",children:n("projectDetail.progress.remaining",{count:we.remaining_parts})})]})]})]})}),we&&a.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[a.jsx(Tt,{children:a.jsx(Mt,{className:"p-4",children:a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:"p-2 rounded-lg bg-bambu-dark text-bambu-green",children:a.jsx(Ra,{className:"w-5 h-5"})}),a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-bambu-gray",children:n("projectDetail.stats.printJobs")}),a.jsxs("p",{className:"text-xl font-semibold text-white",children:[we.total_archives," ",a.jsx("span",{className:"text-sm font-normal text-bambu-gray",children:n("projectDetail.stats.total")})]}),we.failed_prints>0&&a.jsx("p",{className:"text-sm text-status-error",children:n("projectDetail.stats.failed",{count:we.failed_prints})}),a.jsx("p",{className:"text-sm text-bambu-gray",children:n("projectDetail.stats.partsPrinted",{count:we.completed_prints})})]})]})})}),a.jsx(kY,{icon:Yn,label:n("projectDetail.stats.printTime"),value:Dye(we.total_print_time_hours),color:"text-yellow-400"}),a.jsx(kY,{icon:Er,label:n("projectDetail.stats.filamentUsed"),value:rrt(we.total_filament_grams),color:"text-purple-400"})]}),we&&(()=>{const ce=we.estimated_cost+we.total_energy_cost+we.bom_cost;return we.estimated_cost>0||ce>0||g.budget!==null})()&&a.jsx(Tt,{children:a.jsxs(Mt,{className:"p-4",children:[a.jsx("h2",{className:"text-lg font-semibold text-white mb-3",children:n("projectDetail.cost.title")}),a.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-xs text-bambu-gray uppercase",children:n("projectDetail.cost.filamentCost")}),a.jsxs("p",{className:"text-lg font-semibold text-white",children:[te,we.estimated_cost.toFixed(2)]})]}),we.total_energy_kwh>0&&a.jsxs("div",{children:[a.jsx("p",{className:"text-xs text-bambu-gray uppercase",children:n("projectDetail.cost.energy")}),a.jsxs("p",{className:"text-lg font-semibold text-white",children:[we.total_energy_kwh.toFixed(3)," kWh",we.total_energy_cost>0&&a.jsxs("span",{className:"text-sm text-bambu-gray ml-1",children:["(",te,we.total_energy_cost.toFixed(2),")"]})]})]}),(()=>{const ce=we.estimated_cost+we.total_energy_cost+we.bom_cost;return ce<=0?null:a.jsxs("div",{children:[a.jsx("p",{className:"text-xs text-bambu-gray uppercase",children:n("projectDetail.cost.totalCost")}),a.jsxs("p",{className:"text-lg font-semibold text-bambu-green",children:[te,ce.toFixed(2)]}),we.bom_cost>0&&a.jsx("p",{className:"text-xs text-bambu-gray/70",children:n("projectDetail.cost.includesBom")})]})})(),g.budget!==null&&(()=>{const ce=we.estimated_cost+we.total_energy_cost+we.bom_cost,xe=g.budget-ce;return a.jsxs("div",{children:[a.jsx("p",{className:"text-xs text-bambu-gray uppercase",children:n("projectDetail.cost.budget")}),a.jsxs("p",{className:"text-sm text-bambu-gray",children:[n("projectDetail.cost.total"),": ",a.jsxs("span",{className:"text-white font-semibold",children:[te,g.budget.toFixed(2)]})]}),a.jsxs("p",{className:`text-sm ${xe>=0?"text-bambu-green":"text-red-400"}`,children:[n("projectDetail.cost.remaining"),": ",a.jsxs("span",{className:"font-semibold",children:[te,xe.toFixed(2)]})]})]})})()]})]})}),g.children&&g.children.length>0&&a.jsx(Tt,{children:a.jsxs(Mt,{className:"p-4",children:[a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2 mb-3",children:[a.jsx(yge,{className:"w-5 h-5"}),n("projectDetail.subProjects.title",{count:g.children.length})]}),a.jsx("div",{className:"space-y-2",children:g.children.map(ce=>a.jsxs(Do,{to:`/projects/${ce.id}`,className:"flex items-center justify-between p-3 bg-bambu-dark rounded-lg hover:bg-bambu-dark-tertiary transition-colors",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:"w-3 h-3 rounded-full",style:{backgroundColor:ce.color||"#6b7280"}}),a.jsx("span",{className:"text-white",children:ce.name}),a.jsx("span",{className:`text-xs px-2 py-0.5 rounded ${ce.status==="completed"?"bg-status-ok/20 text-status-ok":ce.status==="archived"?"bg-bambu-gray/20 text-bambu-gray":"bg-blue-500/20 text-blue-400"}`,children:ce.status})]}),ce.progress_percent!==null&&a.jsxs("span",{className:"text-sm text-bambu-gray",children:[ce.progress_percent.toFixed(0),"%"]})]},ce.id))})]})}),g.parent_id&&g.parent_name&&a.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[a.jsx(da,{className:"w-4 h-4 text-bambu-gray"}),a.jsx("span",{className:"text-bambu-gray",children:n("projectDetail.partOf")}),a.jsx(Do,{to:`/projects/${g.parent_id}`,className:"text-bambu-green hover:underline",children:g.parent_name})]}),(g.tags||g.due_date||g.priority!=="normal")&&a.jsxs("div",{className:"flex flex-wrap items-center gap-4",children:[g.priority&&g.priority!=="normal"&&a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:"text-xs text-bambu-gray uppercase",children:n("projectDetail.priorityLabel")}),a.jsx(srt,{priority:g.priority,t:n})]}),g.due_date&&a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(na,{className:"w-4 h-4 text-bambu-gray"}),a.jsx("span",{className:"text-sm text-white",children:hg(g.due_date,{year:"numeric",month:"short",day:"numeric"})}),E3(g.due_date,n)&&a.jsxs("span",{className:`text-xs ${E3(g.due_date,n).color}`,children:["(",E3(g.due_date,n).label,")"]})]}),g.tags&&a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(xm,{className:"w-4 h-4 text-bambu-gray"}),a.jsx("div",{className:"flex flex-wrap gap-1",children:g.tags.split(",").map((ce,xe)=>a.jsx("span",{className:"px-2 py-0.5 bg-bambu-dark-tertiary text-bambu-gray text-xs rounded",children:ce.trim()},xe))})]})]}),a.jsx(Tt,{children:a.jsxs(Mt,{className:"p-4",children:[a.jsxs("div",{className:"flex items-center justify-between mb-3",children:[a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(Us,{className:"w-5 h-5"}),n("projectDetail.notes.title")]}),c?a.jsxs("div",{className:"flex gap-2",children:[a.jsxs(De,{variant:"secondary",size:"sm",onClick:re,disabled:J.isPending,children:[a.jsx(Ht,{className:"w-4 h-4 mr-1"}),n("common.cancel")]}),a.jsxs(De,{size:"sm",onClick:fe,disabled:J.isPending,children:[J.isPending?a.jsx(pt,{className:"w-4 h-4 animate-spin mr-1"}):a.jsx(_s,{className:"w-4 h-4 mr-1"}),n("common.save")]})]}):a.jsxs(De,{variant:"secondary",size:"sm",onClick:oe,disabled:!s("projects:update"),title:s("projects:update")?void 0:n("projectDetail.notes.noEditPermission"),children:[a.jsx(dg,{className:"w-4 h-4 mr-1"}),n("common.edit")]})]}),c?a.jsx(tO,{content:u,onChange:m,placeholder:n("projectDetail.notes.placeholder")}):g.notes?a.jsx("div",{className:"prose prose-invert prose-sm max-w-none",dangerouslySetInnerHTML:{__html:hie.sanitize(g.notes)}}):a.jsx("p",{className:"text-bambu-gray/70 text-sm italic",children:n("projectDetail.notes.empty")})]})}),a.jsx(Tt,{children:a.jsxs(Mt,{className:"p-4",children:[a.jsx("div",{className:"flex items-center justify-between mb-3",children:a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(Qc,{className:"w-5 h-5"}),n("projectDetail.files.title")]})}),a.jsxs("p",{className:"text-xs text-bambu-gray mb-3",children:[a.jsx(Do,{to:"/files",className:"text-bambu-green hover:underline",children:n("projectDetail.files.linkFolders")})," ",n("projectDetail.files.forQuickAccess")]}),H&&H.length>0?a.jsx("div",{className:"space-y-4",children:H.map(ce=>{const xe=L.get(ce.id)??[],Be=Q;return a.jsxs("div",{children:[a.jsxs(Do,{to:`/files?folder=${ce.id}`,className:"flex items-center justify-between p-3 bg-bambu-dark rounded-lg hover:bg-bambu-dark-tertiary transition-colors mb-2",children:[a.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[a.jsx(Qc,{className:"w-5 h-5 text-bambu-green shrink-0"}),a.jsxs("div",{className:"min-w-0",children:[a.jsx("p",{className:"text-sm text-white truncate",children:ce.name}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("projectDetail.files.fileCount",{count:ce.file_count})})]})]}),a.jsx(ti,{className:"w-4 h-4 text-bambu-gray shrink-0"})]}),Be?a.jsx("div",{className:"flex items-center gap-2 px-3 py-2 text-bambu-gray text-sm",children:a.jsx(pt,{className:"w-4 h-4 animate-spin"})}):xe.length===0?a.jsx("p",{className:"text-bambu-gray/60 text-xs italic px-3",children:n("projectDetail.files.noFiles")}):a.jsx("div",{className:"space-y-1 pl-3",children:xe.map(Qe=>{const ht=nrt(Qe.filename);return a.jsxs("div",{className:"flex items-center gap-3 p-2 rounded-lg hover:bg-bambu-dark-tertiary transition-colors",children:[a.jsx("div",{className:"w-10 h-10 shrink-0 rounded bg-bambu-dark overflow-hidden flex items-center justify-center",children:Qe.thumbnail_path?a.jsx("img",{src:de.getLibraryFileThumbnailUrl(Qe.id),alt:Qe.print_name||Qe.filename,className:"w-full h-full object-cover"}):a.jsx(ep,{className:"w-5 h-5 text-bambu-gray/40"})}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("p",{className:"text-sm text-white truncate",title:Qe.print_name||Qe.filename,children:Qe.print_name||Qe.filename}),a.jsx("span",{className:`text-xs px-1.5 py-0.5 rounded font-medium ${Qe.file_type==="3mf"?"bg-bambu-green/20 text-bambu-green":Qe.file_type==="gcode"?"bg-blue-500/20 text-blue-400":"bg-bambu-gray/20 text-bambu-gray"}`,children:Qe.file_type.toUpperCase()})]}),ht&&a.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[a.jsx("button",{onClick:()=>f(Qe),title:n("projectDetail.files.print"),className:"p-1.5 rounded hover:bg-bambu-green/20 text-bambu-green transition-colors",children:a.jsx(es,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>v(Qe),title:n("projectDetail.files.addToQueue"),className:"p-1.5 rounded hover:bg-blue-500/20 text-blue-400 transition-colors",children:a.jsx($pe,{className:"w-4 h-4"})})]})]},Qe.id)})})]},ce.id)})}):a.jsx("p",{className:"text-bambu-gray/70 text-sm italic",children:n("projectDetail.files.empty")})]})}),a.jsx(Tt,{children:a.jsxs(Mt,{className:"p-4",children:[a.jsxs("div",{className:"flex items-center justify-between mb-4",children:[a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(qQ,{className:"w-5 h-5"}),n("projectDetail.bom.title"),we&&we.bom_total_items>0&&a.jsxs("span",{className:"text-sm font-normal text-bambu-gray",children:["(",n("projectDetail.bom.acquired",{completed:we.bom_completed_items,total:we.bom_total_items}),")"]})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[A&&A.some(ce=>ce.is_complete)&&a.jsx("button",{onClick:()=>I(!ue),className:`text-xs px-2 py-1 rounded transition-colors ${ue?"bg-bambu-green/20 text-bambu-green":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:n(ue?"projectDetail.bom.showAll":"projectDetail.bom.hideDone")}),!K&&a.jsxs(De,{variant:"secondary",size:"sm",onClick:()=>U(!0),disabled:!s("projects:update"),title:s("projects:update")?void 0:n("projectDetail.bom.noAddPermission"),children:[a.jsx(sr,{className:"w-4 h-4 mr-1"}),n("projectDetail.bom.addPart")]})]})]}),K&&a.jsxs("form",{onSubmit:Le,className:"bg-bambu-dark rounded-lg p-4 mb-4 space-y-3",children:[a.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[a.jsx("input",{type:"text",value:W,onChange:ce=>ne(ce.target.value),className:"bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:n("projectDetail.bom.partNamePlaceholder"),autoFocus:!0}),a.jsxs("div",{className:"flex gap-2",children:[a.jsx("input",{type:"number",value:me,onChange:ce=>be(parseInt(ce.target.value)||1),className:"w-20 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white focus:outline-none focus:border-bambu-green",min:"1",placeholder:n("projectDetail.bom.qty")}),a.jsx("input",{type:"number",step:"0.01",value:Ce,onChange:ce=>q(ce.target.value),className:"flex-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:n("projectDetail.bom.price",{currency:te})})]})]}),a.jsx("input",{type:"url",value:Y,onChange:ce=>E(ce.target.value),className:"w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:n("projectDetail.bom.sourcingUrlPlaceholder")}),a.jsx("input",{type:"text",value:j,onChange:ce=>O(ce.target.value),className:"w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:n("projectDetail.bom.remarksPlaceholder")}),a.jsxs("div",{className:"flex justify-end gap-2",children:[a.jsx(De,{type:"button",variant:"secondary",size:"sm",onClick:()=>U(!1),children:n("common.cancel")}),a.jsx(De,{type:"submit",size:"sm",disabled:!W.trim()||Te.isPending,children:Te.isPending?a.jsx(pt,{className:"w-4 h-4 animate-spin"}):n("projectDetail.bom.addPart")})]})]}),T?a.jsx("div",{className:"flex items-center justify-center py-4",children:a.jsx(pt,{className:"w-6 h-6 animate-spin text-bambu-green"})}):A&&A.length>0?a.jsxs("div",{className:"space-y-2",children:[A.filter(ce=>!ue||!ce.is_complete).map(ce=>a.jsx("div",{className:`p-3 rounded-lg transition-colors ${ce.is_complete?"bg-status-ok/10":"bg-bambu-dark"}`,children:G?.id===ce.id?a.jsxs("form",{onSubmit:$e,className:"space-y-3",children:[a.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[a.jsx("input",{type:"text",value:V,onChange:xe=>ee(xe.target.value),className:"bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:n("projectDetail.bom.partName"),autoFocus:!0}),a.jsxs("div",{className:"flex gap-2",children:[a.jsx("input",{type:"number",value:se,onChange:xe=>ge(parseInt(xe.target.value)||1),className:"w-20 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white focus:outline-none focus:border-bambu-green",min:"1",placeholder:n("projectDetail.bom.qty")}),a.jsx("input",{type:"number",step:"0.01",value:he,onChange:xe=>le(xe.target.value),className:"flex-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:n("projectDetail.bom.price",{currency:te})})]})]}),a.jsx("input",{type:"url",value:B,onChange:xe=>R(xe.target.value),className:"w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:n("projectDetail.bom.sourcingUrlPlaceholder")}),a.jsx("input",{type:"text",value:ae,onChange:xe=>_e(xe.target.value),className:"w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:n("projectDetail.bom.remarksPlaceholder")}),a.jsxs("div",{className:"flex justify-end gap-2",children:[a.jsx(De,{type:"button",variant:"secondary",size:"sm",onClick:Ye,children:n("common.cancel")}),a.jsx(De,{type:"submit",size:"sm",disabled:!V.trim()||ye.isPending,children:ye.isPending?a.jsx(pt,{className:"w-4 h-4 animate-spin"}):n("common.save")})]})]}):a.jsxs("div",{className:"flex items-start gap-3",children:[a.jsx("button",{onClick:()=>s("projects:update")&&Me(ce),disabled:ye.isPending||!s("projects:update"),title:s("projects:update")?void 0:n("projectDetail.bom.noUpdatePermission"),className:`w-5 h-5 mt-0.5 rounded border-2 flex items-center justify-center transition-colors shrink-0 ${ce.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:ce.is_complete&&a.jsx(yr,{className:"w-3 h-3"})}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsxs("div",{className:"flex items-center justify-between gap-2",children:[a.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[a.jsxs("p",{className:`text-sm font-medium ${ce.is_complete?"text-bambu-gray line-through":"text-white"}`,children:[ce.name,a.jsxs("span",{className:"text-bambu-gray font-normal ml-2",children:["x",ce.quantity_needed]})]}),ce.unit_price!==null&&a.jsxs("span",{className:"text-xs text-bambu-green whitespace-nowrap",children:[te,(ce.unit_price*ce.quantity_needed).toFixed(2)]})]}),a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsx("button",{onClick:()=>s("projects:update")&&Re(ce),disabled:!s("projects:update"),className:`p-1 rounded transition-colors shrink-0 ${s("projects:update")?"hover:bg-bambu-dark-tertiary text-bambu-gray hover:text-white":"text-bambu-gray/50 cursor-not-allowed"}`,title:s("projects:update")?n("common.edit"):n("projectDetail.bom.noEditPermission"),children:a.jsx(ci,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>s("projects:update")&&Oe(ce.id,ce.name),disabled:!s("projects:update"),className:`p-1 rounded transition-colors shrink-0 ${s("projects:update")?"hover:bg-bambu-dark-tertiary text-bambu-gray hover:text-red-400":"text-bambu-gray/50 cursor-not-allowed"}`,title:s("projects:update")?n("common.delete"):n("projectDetail.bom.noDeletePermission"),children:a.jsx(en,{className:"w-4 h-4"})})]})]}),ce.sourcing_url&&a.jsxs("a",{href:ce.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:xe=>xe.stopPropagation(),children:[a.jsx(la,{className:"w-3 h-3 shrink-0"}),a.jsx("span",{className:"truncate",children:(()=>{try{return new URL(ce.sourcing_url).hostname.replace("www.","")}catch{return ce.sourcing_url}})()})]}),ce.remarks&&a.jsx("p",{className:"mt-1 text-xs text-bambu-gray/80 italic",children:ce.remarks})]})]})},ce.id)),we&&we.bom_cost>0&&a.jsxs("div",{className:"pt-2 mt-2 border-t border-bambu-dark-tertiary flex justify-between text-sm",children:[a.jsx("span",{className:"text-bambu-gray",children:n("projectDetail.bom.totalCost")}),a.jsxs("span",{className:"text-white font-medium",children:[te,we.bom_cost.toFixed(2)]})]})]}):a.jsx("p",{className:"text-bambu-gray/70 text-sm italic",children:n("projectDetail.bom.empty")})]})}),a.jsx(Tt,{children:a.jsxs(Mt,{className:"p-4",children:[a.jsx("div",{className:"flex items-center justify-between mb-3",children:a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(iw,{className:"w-5 h-5"}),n("projectDetail.timeline.title")]})}),k?a.jsx("div",{className:"flex items-center justify-center py-4",children:a.jsx(pt,{className:"w-6 h-6 animate-spin text-bambu-green"})}):F&&F.length>0?a.jsx("div",{className:"space-y-3",children:F.slice(0,10).map((ce,xe)=>a.jsxs("div",{className:"flex gap-3",children:[a.jsxs("div",{className:`w-8 h-8 rounded-full flex items-center justify-center shrink-0 ${ce.event_type==="print_completed"?"bg-status-ok/20 text-status-ok":ce.event_type==="print_failed"?"bg-status-error/20 text-status-error":ce.event_type==="print_started"?"bg-yellow-500/20 text-yellow-400":"bg-bambu-dark-tertiary text-bambu-gray"}`,children:[ce.event_type==="print_completed"&&a.jsx(yr,{className:"w-4 h-4"}),ce.event_type==="print_failed"&&a.jsx(Ma,{className:"w-4 h-4"}),ce.event_type==="print_started"&&a.jsx(Er,{className:"w-4 h-4"}),ce.event_type==="queued"&&a.jsx(sF,{className:"w-4 h-4"}),ce.event_type==="project_created"&&a.jsx(sr,{className:"w-4 h-4"})]}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("p",{className:"text-sm text-white",children:ce.title}),ce.description&&a.jsx("p",{className:"text-xs text-bambu-gray truncate",children:ce.description}),a.jsx("p",{className:"text-xs text-bambu-gray/70",children:Fe(ce.timestamp)})]})]},xe))}):a.jsx("p",{className:"text-bambu-gray/70 text-sm italic",children:n("projectDetail.timeline.empty")})]})}),!g.is_template&&a.jsx("div",{className:"flex justify-end",children:a.jsxs(De,{variant:"secondary",size:"sm",onClick:()=>pe.mutate(),disabled:pe.isPending||!s("projects:create"),title:s("projects:create")?void 0:n("projectDetail.template.noCreatePermission"),children:[pe.isPending?a.jsx(pt,{className:"w-4 h-4 animate-spin mr-2"}):a.jsx(qs,{className:"w-4 h-4 mr-2"}),n("projectDetail.template.saveAsTemplate")]})}),we&&(we.queued_prints>0||we.in_progress_prints>0)&&a.jsx(Tt,{children:a.jsxs(Mt,{className:"p-4",children:[a.jsxs("div",{className:"flex items-center justify-between mb-3",children:[a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(sF,{className:"w-5 h-5"}),n("projectDetail.queue.title")]}),a.jsx(Do,{to:`/queue?project=${b}`,className:"text-sm text-bambu-green hover:underline",children:n("projectDetail.queue.viewAll")})]}),a.jsxs("div",{className:"flex items-center gap-4 text-sm",children:[we.in_progress_prints>0&&a.jsx("span",{className:"text-yellow-400",children:n("projectDetail.queue.printing",{count:we.in_progress_prints})}),we.queued_prints>0&&a.jsx("span",{className:"text-bambu-gray",children:n("projectDetail.queue.queued",{count:we.queued_prints})})]})]})}),a.jsxs("div",{children:[a.jsx("div",{className:"flex items-center justify-between mb-4",children:a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(Ra,{className:"w-5 h-5"}),n("projectDetail.prints.title",{count:P?.length||0})]})}),N?a.jsx("div",{className:"flex items-center justify-center py-8",children:a.jsx(pt,{className:"w-6 h-6 animate-spin text-bambu-green"})}):a.jsx(irt,{archives:P||[],t:n})]}),o&&a.jsx(Hle,{t:n,currencySymbol:te,project:{...g,archive_count:we?.total_archives||0,total_items:we?.total_items||0,completed_count:we?.completed_prints||0,failed_count:we?.failed_prints||0,queue_count:we?.queued_prints||0,progress_percent:we?.progress_percent||null,archives:[]},onClose:()=>l(!1),onSave:ce=>J.mutate(ce),isLoading:J.isPending}),Se.isOpen&&a.jsx(yn,{title:Se.title,message:Se.message,confirmText:n("common.delete"),variant:"danger",onConfirm:Se.onConfirm,onCancel:()=>ve(ce=>({...ce,isOpen:!1}))}),p&&a.jsx(sc,{mode:"reprint",libraryFileId:p.id,archiveName:p.print_name||p.filename,projectId:b,onClose:()=>f(null),onSuccess:()=>{f(null),r.invalidateQueries({queryKey:["archives"]})}}),y&&a.jsx(sc,{mode:"add-to-queue",libraryFileId:y.id,archiveName:y.print_name||y.filename,projectId:b,onClose:()=>v(null),onSuccess:()=>{v(null),r.invalidateQueries({queryKey:["queue"]})}})]})}function lrt({parentId:t,onClose:e,onSave:n,isLoading:r,t:i}){const[s,o]=w.useState(""),l=c=>{c.preventDefault(),n({name:s.trim(),parent_id:t})};return a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-sm border border-bambu-dark-tertiary",children:[a.jsx("div",{className:"p-4 border-b border-bambu-dark-tertiary",children:a.jsx("h2",{className:"text-lg font-semibold text-white",children:i("fileManager.newFolder")})}),a.jsxs("form",{onSubmit:l,className:"p-4 space-y-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:i("fileManager.folderName")}),a.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})]}),a.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[a.jsx(De,{type:"button",variant:"secondary",onClick:e,children:i("common.cancel")}),a.jsx(De,{type:"submit",disabled:!s.trim()||r,children:r?a.jsx(pt,{className:"w-4 h-4 animate-spin"}):i("common.create")})]})]})]})})}function crt({onClose:t,onSave:e,isLoading:n,t:r}){const[i,s]=w.useState(""),[o,l]=w.useState(""),[c,d]=w.useState(!0),[u,m]=w.useState(!1),p=f=>{f.preventDefault(),e({name:i.trim(),external_path:o.trim(),readonly:c,show_hidden:u})};return a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-md border border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"p-4 border-b border-bambu-dark-tertiary",children:[a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(SN,{className:"w-5 h-5 text-bambu-green"}),r("fileManager.linkExternalFolder")]}),a.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:r("fileManager.linkExternalFolderDescription")})]}),a.jsxs("form",{onSubmit:p,className:"p-4 space-y-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:r("fileManager.folderName")}),a.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:r("fileManager.externalFolderNamePlaceholder"),autoFocus:!0,required:!0})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:r("fileManager.externalPath")}),a.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}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:r("fileManager.externalPathHelp")})]}),a.jsxs("div",{className:"space-y-2",children:[a.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[a.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"}),a.jsx("span",{className:"text-sm text-white",children:r("fileManager.readOnly")}),a.jsxs("span",{className:"text-xs text-bambu-gray",children:["(",r("fileManager.readOnlyHelp"),")"]})]}),a.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[a.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"}),a.jsx("span",{className:"text-sm text-white",children:r("fileManager.showHiddenFiles")})]})]}),a.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[a.jsx(De,{type:"button",variant:"secondary",onClick:t,children:r("common.cancel")}),a.jsx(De,{type:"submit",disabled:!i.trim()||!o.trim()||n,children:n?a.jsx(pt,{className:"w-4 h-4 animate-spin"}):r("fileManager.linkFolder")})]})]})]})})}function drt({type:t,currentName:e,onClose:n,onSave:r,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]=w.useState(l),u=m=>{m.preventDefault();const p=t==="file"?c.trim()+o:c.trim();c.trim()&&p!==e&&r(p)};return a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-sm border border-bambu-dark-tertiary",children:[a.jsx("div",{className:"p-4 border-b border-bambu-dark-tertiary",children:a.jsx("h2",{className:"text-lg font-semibold text-white",children:s(t==="file"?"fileManager.renameFile":"fileManager.renameFolder")})}),a.jsxs("form",{onSubmit:u,className:"p-4 space-y-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("common.name")}),a.jsxs("div",{className:"flex items-center bg-bambu-dark border border-bambu-dark-tertiary rounded focus-within:border-bambu-green",children:[a.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&&a.jsx("span",{className:"pr-3 text-bambu-gray text-sm select-none whitespace-nowrap",children:o})]})]}),a.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[a.jsx(De,{type:"button",variant:"secondary",onClick:n,children:s("common.cancel")}),a.jsx(De,{type:"submit",disabled:!c.trim()||c.trim()===l||i,children:i?a.jsx(pt,{className:"w-4 h-4 animate-spin"}):s("common.rename")})]})]})]})})}function urt({folders:t,selectedFiles:e,currentFolderId:n,onClose:r,onMove:i,isLoading:s,t:o}){const[l,c]=w.useState(null),d=(m,p=0)=>{const f=[];for(const y of m)f.push({id:y.id,name:y.name,depth:p}),y.children.length>0&&f.push(...d(y.children,p+1));return f},u=[{id:null,name:o("fileManager.rootNoFolder"),depth:0},...d(t)];return a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-sm border border-bambu-dark-tertiary",children:[a.jsx("div",{className:"p-4 border-b border-bambu-dark-tertiary",children:a.jsx("h2",{className:"text-lg font-semibold text-white",children:o("fileManager.moveFiles",{count:e.length})})}),a.jsxs("div",{className:"p-4 space-y-4",children:[a.jsx("div",{className:"max-h-64 overflow-y-auto space-y-1",children:u.map(m=>a.jsxs("button",{onClick:()=>c(m.id),disabled:m.id===n,className:`w-full text-left px-3 py-2 rounded transition-colors flex items-center gap-2 ${l===m.id?"bg-bambu-green/20 text-bambu-green":m.id===n?"opacity-50 cursor-not-allowed text-bambu-gray":"hover:bg-bambu-dark text-white"}`,style:{paddingLeft:`${12+m.depth*16}px`},children:[a.jsx(Qc,{className:"w-4 h-4"}),m.name,m.id===n&&a.jsxs("span",{className:"text-xs text-bambu-gray ml-auto",children:["(",o("fileManager.current"),")"]})]},m.id??"root"))}),a.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[a.jsx(De,{type:"button",variant:"secondary",onClick:r,children:o("common.cancel")}),a.jsx(De,{onClick:()=>i(l),disabled:s,children:s?a.jsx(pt,{className:"w-4 h-4 animate-spin"}):o("common.move")})]})]})]})})}function mrt({folder:t,onClose:e,onLink:n,isLoading:r,t:i}){const[s,o]=w.useState("project"),[l,c]=w.useState(t.project_id||t.archive_id||null);w.useState(()=>{t.archive_id&&o("archive")});const{data:d}=Xe({queryKey:["projects"],queryFn:()=>de.getProjects()}),{data:u}=Xe({queryKey:["archives-for-link"],queryFn:()=>de.getArchives(void 0,void 0,100)}),m=()=>{n(s==="project"?{project_id:l,archive_id:0}:{project_id:0,archive_id:l})},p=()=>{n({project_id:0,archive_id:0})},f=t.project_id||t.archive_id;return a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-md border border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"p-4 border-b border-bambu-dark-tertiary flex items-center justify-between",children:[a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(sm,{className:"w-5 h-5 text-bambu-green"}),i("fileManager.linkFolder")]}),a.jsx("button",{onClick:e,className:"p-1 hover:bg-bambu-dark rounded",children:a.jsx(Ht,{className:"w-5 h-5 text-bambu-gray"})})]}),a.jsxs("div",{className:"p-4 space-y-4",children:[a.jsx("p",{className:"text-sm text-bambu-gray",children:i("fileManager.linkFolderDescription",{name:t.name})}),a.jsxs("div",{className:"flex gap-2",children:[a.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:[a.jsx(FQ,{className:"w-4 h-4"}),i("fileManager.project")]}),a.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:[a.jsx(so,{className:"w-4 h-4"}),i("fileManager.archive")]})]}),a.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(y=>a.jsxs("button",{onClick:()=>c(y.id),className:`w-full text-left px-3 py-2 rounded transition-colors flex items-center gap-2 ${l===y.id?"bg-bambu-green/20 text-bambu-green":"hover:bg-bambu-dark-tertiary text-white"}`,children:[a.jsx("div",{className:"w-3 h-3 rounded-full flex-shrink-0",style:{backgroundColor:y.color||"#00ae42"}}),a.jsx("span",{className:"truncate",children:y.name})]},y.id)):a.jsx("p",{className:"text-sm text-bambu-gray text-center py-4",children:i("fileManager.noProjectsFound")}):u&&u.length>0?u.map(y=>a.jsxs("button",{onClick:()=>c(y.id),className:`w-full text-left px-3 py-2 rounded transition-colors flex items-center gap-2 ${l===y.id?"bg-bambu-green/20 text-bambu-green":"hover:bg-bambu-dark-tertiary text-white"}`,children:[a.jsx(ep,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"}),a.jsx("span",{className:"truncate",children:y.print_name||y.filename})]},y.id)):a.jsx("p",{className:"text-sm text-bambu-gray text-center py-4",children:i("fileManager.noArchivesFound")})})]}),a.jsxs("div",{className:"p-4 border-t border-bambu-dark-tertiary flex justify-between",children:[f&&a.jsxs(De,{variant:"danger",onClick:p,disabled:r,children:[a.jsx(gp,{className:"w-4 h-4 mr-2"}),i("fileManager.unlink")]}),a.jsxs("div",{className:`flex gap-2 ${f?"":"ml-auto"}`,children:[a.jsx(De,{variant:"secondary",onClick:e,children:i("common.cancel")}),a.jsx(De,{onClick:m,disabled:!l||r,children:r?a.jsx(pt,{className:"w-4 h-4 animate-spin"}):i("fileManager.link")})]})]})]})})}function qle({folder:t,selectedFolderId:e,onSelect:n,onDelete:r,onLink:i,onRename:s,depth:o=0,wrapNames:l=!1,defaultExpanded:c=!0,hasPermission:d,t:u}){const[m,p]=w.useState(c),[f,y]=w.useState(!1),v=t.children.length>0,b=t.project_id||t.archive_id,g=t.is_external;return a.jsxs("div",{children:[a.jsxs("div",{className:`group flex items-center gap-1 px-2 py-1.5 rounded cursor-pointer transition-colors ${e===t.id?"bg-bambu-green/20 text-bambu-green":"hover:bg-bambu-dark text-white"}`,style:{paddingLeft:`${8+o*12}px`},onClick:()=>n(t.id),children:[v?a.jsx("button",{onClick:_=>{_.stopPropagation(),p(!m)},className:"p-0.5 hover:bg-bambu-dark-tertiary rounded",children:a.jsx(ti,{className:`w-3.5 h-3.5 transition-transform ${m?"rotate-90":""}`})}):a.jsx("div",{className:"w-4.5"}),g?a.jsx(SN,{className:"w-4 h-4 text-purple-400 flex-shrink-0"}):a.jsx(Qc,{className:"w-4 h-4 text-bambu-green flex-shrink-0"}),a.jsx("span",{className:`text-sm flex-1 min-w-0 ${l?"break-all":"truncate"}`,title:t.name,children:t.name}),b&&a.jsxs("button",{onClick:_=>{_.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:[a.jsx(sm,{className:"w-3 h-3"}),t.project_name?a.jsx(FQ,{className:"w-3 h-3"}):a.jsx(so,{className:"w-3 h-3"})]}),g&&t.external_readonly&&a.jsx("span",{title:u("fileManager.readOnly"),children:a.jsx(kd,{className:"w-3 h-3 text-amber-400 flex-shrink-0"})}),t.file_count>0&&a.jsx("span",{className:"flex-shrink-0 text-xs text-bambu-gray",children:t.file_count}),!b&&!g&&a.jsx("button",{onClick:_=>{_.stopPropagation(),i(t)},className:"flex-shrink-0 p-1 rounded hover:bg-bambu-dark-tertiary",title:u("fileManager.linkToProjectOrArchive"),children:a.jsx(sm,{className:"w-3.5 h-3.5 text-bambu-gray hover:text-bambu-green"})}),a.jsx("div",{className:`flex-shrink-0 flex items-center gap-0.5 transition-opacity ${l?"":"opacity-0 group-hover:opacity-100"}`,onClick:_=>_.stopPropagation(),children:a.jsxs("div",{className:"relative",children:[a.jsx("button",{onClick:()=>y(!f),className:"p-1 rounded hover:bg-bambu-dark-tertiary",children:a.jsx(Jh,{className:"w-3.5 h-3.5 text-bambu-gray"})}),f&&a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>y(!1)}),a.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:[a.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),y(!1))},disabled:!d("library:update_all"),title:d("library:update_all")?void 0:u("fileManager.noPermissionRenameFolder"),children:[a.jsx(ci,{className:"w-3.5 h-3.5"}),u("common.rename")]}),a.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),y(!1))},disabled:!d("library:update_all"),title:d("library:update_all")?void 0:u("fileManager.noPermissionLinkFolder"),children:[a.jsx(sm,{className:"w-3.5 h-3.5"}),u(b?"fileManager.changeLink":"fileManager.linkTo")]}),a.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")&&(r(t.id),y(!1))},disabled:!d("library:delete_all"),title:d("library:delete_all")?void 0:u("fileManager.noPermissionDeleteFolder"),children:[a.jsx(en,{className:"w-3.5 h-3.5"}),u("common.delete")]})]})]})]})})]}),v&&m&&a.jsx("div",{children:t.children.map(_=>a.jsx(qle,{folder:_,selectedFolderId:e,onSelect:n,onDelete:r,onLink:i,onRename:s,depth:o+1,wrapNames:l,defaultExpanded:c,hasPermission:d,t:u},_.id))})]})}function cO(t){const e=t.toLowerCase();return e.endsWith(".gcode")||e.endsWith(".gcode.3mf")}function hrt({file:t,isSelected:e,isMobile:n,onSelect:r,onDelete:i,onDownload:s,onAddToQueue:o,onPrint:l,onPreview3d:c,onRename:d,onGenerateThumbnail:u,thumbnailVersion:m,hasPermission:p,canModify:f,authEnabled:y,t:v}){const[b,g]=w.useState(!1);return a.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:()=>r(t.id),children:[a.jsxs("div",{className:"aspect-square bg-bambu-dark flex items-center justify-center overflow-hidden",children:[t.thumbnail_path?a.jsx("img",{src:`${de.getLibraryFileThumbnailUrl(t.id)}${m?(de.getLibraryFileThumbnailUrl(t.id).includes("?")?"&":"?")+`v=${m}`:""}`,alt:t.filename,className:"w-full h-full object-cover"}):a.jsx(ep,{className:"w-12 h-12 text-bambu-gray/30"}),a.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()})]}),a.jsxs("div",{className:"p-3",children:[a.jsx("h3",{className:"text-sm font-medium text-white truncate",title:t.print_name||t.filename,children:t.print_name||t.filename}),a.jsxs("div",{className:"flex items-center gap-3 mt-1 text-xs text-bambu-gray",children:[a.jsx("span",{children:Lo(t.file_size)}),t.print_time_seconds&&a.jsxs("span",{className:"flex items-center gap-1",children:[a.jsx(Yn,{className:"w-3 h-3"}),ws(t.print_time_seconds)]})]}),t.sliced_for_model&&a.jsxs("div",{className:"mt-1 text-xs text-bambu-gray flex items-center gap-1",children:[a.jsx(Er,{className:"w-3 h-3"}),t.sliced_for_model]}),t.print_count>0&&a.jsx("div",{className:"mt-1 text-xs text-bambu-green",children:v("fileManager.printedCount",{count:t.print_count})}),y&&t.created_by_username&&a.jsxs("div",{className:"mt-1 text-xs text-bambu-gray flex items-center gap-1",children:[a.jsx(ym,{className:"w-3 h-3"}),t.created_by_username]})]}),a.jsxs("div",{className:`absolute bottom-2 right-2 transition-opacity ${n?"opacity-100":"opacity-0 group-hover:opacity-100"}`,onClick:_=>_.stopPropagation(),children:[a.jsx("button",{onClick:()=>g(!b),className:"p-1.5 rounded bg-bambu-dark-secondary/90 hover:bg-bambu-dark-tertiary",children:a.jsx(Jh,{className:"w-4 h-4 text-bambu-gray"})}),b&&a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>g(!1)}),a.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&&cO(t.filename)&&a.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${p("printers:control")?"text-bambu-green hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{p("printers:control")&&(l(t),g(!1))},disabled:!p("printers:control"),title:p("printers:control")?void 0:v("fileManager.noPermissionPrint"),children:[a.jsx(Er,{className:"w-3.5 h-3.5"}),v("common.print")]}),o&&cO(t.filename)&&a.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${p("queue:create")?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{p("queue:create")&&(o(t.id),g(!1))},disabled:!p("queue:create"),title:p("queue:create")?void 0:v("fileManager.noPermissionAddToQueue"),children:[a.jsx(Yn,{className:"w-3.5 h-3.5"}),v("fileManager.schedulePrint")]}),c&&(t.file_type==="3mf"||t.file_type==="gcode"||t.file_type==="stl")&&a.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${p("library:read")?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{p("library:read")&&(c(t),g(!1))},disabled:!p("library:read"),title:p("library:read")?void 0:"You do not have permission to preview files",children:[a.jsx(vi,{className:"w-3.5 h-3.5"}),"3D Preview"]}),a.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${p("library:read")?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{p("library:read")&&(s(t.id),g(!1))},disabled:!p("library:read"),title:p("library:read")?void 0:v("fileManager.noPermissionDownload"),children:[a.jsx(ga,{className:"w-3.5 h-3.5"}),v("common.download")]}),d&&a.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${f("library","update",t.created_by_id)?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{f("library","update",t.created_by_id)&&(d(t),g(!1))},disabled:!f("library","update",t.created_by_id),title:f("library","update",t.created_by_id)?void 0:v("fileManager.noPermissionRenameFile"),children:[a.jsx(ci,{className:"w-3.5 h-3.5"}),v("common.rename")]}),u&&t.file_type==="stl"&&a.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${f("library","update",t.created_by_id)?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{f("library","update",t.created_by_id)&&(u(t),g(!1))},disabled:!f("library","update",t.created_by_id),title:f("library","update",t.created_by_id)?void 0:v("fileManager.noPermissionGenerateThumbnail"),children:[a.jsx(gm,{className:"w-3.5 h-3.5"}),v("fileManager.generateThumbnail")]}),a.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${f("library","delete",t.created_by_id)?"text-red-400 hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{f("library","delete",t.created_by_id)&&(i(t.id),g(!1))},disabled:!f("library","delete",t.created_by_id),title:f("library","delete",t.created_by_id)?void 0:v("fileManager.noPermissionDeleteFile"),children:[a.jsx(en,{className:"w-3.5 h-3.5"}),v("common.delete")]})]})]})]}),a.jsx("div",{className:`absolute top-2 left-2 w-5 h-5 rounded border-2 flex items-center justify-center transition-all ${e?"bg-bambu-green border-bambu-green":`border-white/30 bg-black/30 ${n?"opacity-100":"opacity-0 group-hover:opacity-100"}`}`,children:e&&a.jsx("div",{className:"w-2 h-2 bg-white rounded-sm"})})]})}function prt(){const{t}=Ft(),e=nn(),{showToast:n}=hn(),{hasPermission:r,hasAnyPermission:i,canModify:s,authEnabled:o}=Sr(),[l]=HP(),c=l.get("folder"),d=c?parseInt(c,10):null,[u,m]=w.useState(d),[p,f]=w.useState([]),[y,v]=w.useState(!1),[b,g]=w.useState(!1),[_,C]=w.useState(!1),[P,N]=w.useState(!1),[A,T]=w.useState(null),[F,k]=w.useState(null),[D,H]=w.useState(null),[z,Q]=w.useState(null),[L,te]=w.useState(null),[ie,J]=w.useState(null),[oe,fe]=w.useState({}),[re,W]=w.useState(null),[ne,me]=w.useState(()=>localStorage.getItem("library-view-mode")||"grid"),[be,Ce]=w.useState(()=>localStorage.getItem("library-wrap-folders")==="true"),[q,Y]=w.useState(()=>localStorage.getItem("library-collapse-folders")==="true"),[E,j]=w.useState(()=>{const Ke=localStorage.getItem("library-sidebar-width");return Ke?parseInt(Ke,10):256}),[O,K]=w.useState(!1),U=w.useRef(null);w.useEffect(()=>{if(!O)return;document.body.style.userSelect="none",document.body.style.cursor="col-resize";const Ke=Lt=>{if(!U.current)return;const Et=U.current.parentElement?.getBoundingClientRect();if(!Et)return;const At=Lt.clientX-Et.left,Ie=Math.min(500,Math.max(200,At));j(Ie)},at=()=>{K(!1),document.body.style.userSelect="",document.body.style.cursor="",localStorage.setItem("library-sidebar-width",String(E))};return document.addEventListener("mousemove",Ke),document.addEventListener("mouseup",at),()=>{document.removeEventListener("mousemove",Ke),document.removeEventListener("mouseup",at),document.body.style.userSelect="",document.body.style.cursor=""}},[O,E]);const[ue,I]=w.useState(""),[G,X]=w.useState("all"),[V,ee]=w.useState(""),[se,ge]=w.useState(()=>localStorage.getItem("library-sort-field")||"name"),[he,le]=w.useState(()=>localStorage.getItem("library-sort-direction")||"asc"),B=aie();w.useEffect(()=>{const Ke=l.get("folder");if(Ke){const at=parseInt(Ke,10);m(at)}},[l]);const{data:R}=Xe({queryKey:["settings"],queryFn:()=>de.getSettings()}),{data:ae,isLoading:_e}=Xe({queryKey:["library-folders"],queryFn:()=>de.getLibraryFolders()}),{data:Se,isLoading:ve}=Xe({queryKey:["library-files",u],queryFn:()=>de.getLibraryFiles(u,u===null)}),{data:Te}=Xe({queryKey:["library-stats"],queryFn:()=>de.getLibraryStats()}),{data:ye}=Xe({queryKey:["users"],queryFn:()=>de.getUsers()}),Ae=w.useMemo(()=>{if(!Se)return[];const Ke=new Set(Se.map(at=>at.file_type));return Array.from(Ke).sort()},[Se]),Le=w.useMemo(()=>{if(!Se)return[];let Ke=[...Se];if(ue.trim()){const at=ue.toLowerCase();Ke=Ke.filter(Lt=>Lt.filename.toLowerCase().includes(at)||Lt.print_name&&Lt.print_name.toLowerCase().includes(at))}if(G!=="all"&&(Ke=Ke.filter(at=>at.file_type===G)),V.trim()){const at=V.toLowerCase();Ke=Ke.filter(Lt=>Lt.created_by_username&&Lt.created_by_username.toLowerCase().includes(at))}return Ke.sort((at,Lt)=>{let Et=0;switch(se){case"name":Et=(at.print_name||at.filename).localeCompare(Lt.print_name||Lt.filename);break;case"date":Et=(Zn(at.created_at)?.getTime()??0)-(Zn(Lt.created_at)?.getTime()??0);break;case"size":Et=at.file_size-Lt.file_size;break;case"type":Et=at.file_type.localeCompare(Lt.file_type);break;case"prints":Et=at.print_count-Lt.print_count;break}return he==="asc"?Et:-Et}),Ke},[Se,ue,G,V,se,he]),Me=w.useMemo(()=>{if(!Te||!R)return!1;const Ke=(R.library_disk_warning_gb||5)*1024*1024*1024;return Te.disk_free_bytesde.createLibraryFolder(Ke),onSuccess:()=>{e.invalidateQueries({queryKey:["library-folders"]}),v(!1),n(t("fileManager.toast.folderCreated"),"success")},onError:Ke=>n(Ke.message,"error")}),Re=it({mutationFn:async Ke=>{const at=await de.createExternalFolder(Ke);return await de.scanExternalFolder(at.id),at},onSuccess:Ke=>{e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-stats"]}),g(!1),m(Ke.id),n(t("fileManager.toast.externalFolderLinked"),"success")},onError:Ke=>n(Ke.message,"error")}),$e=it({mutationFn:Ke=>de.scanExternalFolder(Ke),onSuccess:Ke=>{e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-stats"]}),n(t("fileManager.toast.folderScanned",{added:Ke.added,removed:Ke.removed}),"success")},onError:Ke=>n(Ke.message,"error")}),Ye=it({mutationFn:Ke=>de.deleteLibraryFolder(Ke),onSuccess:()=>{e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-stats"]}),u===F?.id&&m(null),k(null),n(t("fileManager.toast.folderDeleted"),"success")},onError:Ke=>{k(null),n(Ke.message,"error")}}),tt=it({mutationFn:Ke=>de.deleteLibraryFile(Ke),onSuccess:()=>{e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-stats"]}),f(Ke=>Ke.filter(at=>at!==F?.id)),k(null),n(t("fileManager.toast.fileDeleted"),"success")},onError:Ke=>{k(null),n(Ke.message,"error")}}),pe=it({mutationFn:Ke=>de.bulkDeleteLibrary(Ke,[]),onSuccess:(Ke,at)=>{e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-stats"]}),n(t("fileManager.toast.filesDeleted",{count:at.length}),"success"),f([]),k(null)},onError:Ke=>{k(null),n(Ke.message,"error")}}),Fe=it({mutationFn:({fileIds:Ke,folderId:at})=>de.moveLibraryFiles(Ke,at),onSuccess:()=>{e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-folders"]}),f([]),C(!1),n(t("fileManager.toast.filesMoved"),"success")},onError:Ke=>n(Ke.message,"error")}),we=it({mutationFn:({id:Ke,data:at})=>de.updateLibraryFolder(Ke,at),onSuccess:(Ke,at)=>{e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["project-folders"]}),e.invalidateQueries({queryKey:["archive-folders"]}),T(null);const Lt=at.data.project_id===0&&at.data.archive_id===0;n(t(Lt?"fileManager.toast.folderUnlinked":"fileManager.toast.folderLinked"),"success")},onError:Ke=>n(Ke.message,"error")}),Ve=it({mutationFn:({id:Ke,filename:at})=>de.updateLibraryFile(Ke,{filename:at}),onSuccess:()=>{e.invalidateQueries({queryKey:["library-files"]}),J(null),n(t("fileManager.toast.fileRenamed"),"success")},onError:Ke=>{J(null),n(Ke.message,"error")}}),je=it({mutationFn:({id:Ke,name:at})=>de.updateLibraryFolder(Ke,{name:at}),onSuccess:()=>{e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-files"]}),J(null),n(t("fileManager.toast.folderRenamed"),"success")},onError:Ke=>{J(null),n(Ke.message,"error")}}),ce=it({mutationFn:()=>de.batchGenerateStlThumbnails({all_missing:!0}),onSuccess:Ke=>{if(e.invalidateQueries({queryKey:["library-files"]}),Ke.succeeded>0){const at=Date.now(),Lt={};Ke.results.forEach(Et=>{Et.success&&(Lt[Et.file_id]=at)}),fe(Et=>({...Et,...Lt}))}Ke.succeeded>0&&Ke.failed===0?n(t("fileManager.toast.thumbnailsGenerated",{count:Ke.succeeded}),"success"):Ke.succeeded>0&&Ke.failed>0?n(t("fileManager.toast.thumbnailsGeneratedPartial",{succeeded:Ke.succeeded,failed:Ke.failed}),"success"):Ke.processed===0?n(t("fileManager.toast.noStlMissingThumbnails"),"info"):n(t("fileManager.toast.failedToGenerateThumbnails",{error:Ke.results[0]?.error||"Unknown error"}),"error")},onError:Ke=>n(Ke.message,"error")}),xe=it({mutationFn:Ke=>de.batchGenerateStlThumbnails({file_ids:[Ke]}),onSuccess:Ke=>{if(e.invalidateQueries({queryKey:["library-files"]}),Ke.succeeded>0){const at=Ke.results[0]?.file_id;at&&fe(Lt=>({...Lt,[at]:Date.now()})),n(t("fileManager.toast.thumbnailGenerated"),"success")}else n(t("fileManager.toast.failedToGenerateThumbnail",{error:Ke.results[0]?.error||"Unknown error"}),"error")},onError:Ke=>n(Ke.message,"error")}),Be=w.useCallback(Ke=>{const at=Ke.toLowerCase();return at.endsWith(".gcode")||at.includes(".gcode.")},[]),Qe=w.useMemo(()=>Se?Se.filter(Ke=>p.includes(Ke.id)&&Be(Ke.filename)):[],[Se,p,Be]),ht=w.useCallback(Ke=>{f(at=>at.includes(Ke)?at.filter(Lt=>Lt!==Ke):[...at,Ke])},[]),xt=w.useCallback(()=>{Le.length>0&&f(Le.map(Ke=>Ke.id))},[Le]),gt=w.useCallback(()=>{f([])},[]),Ut=()=>{e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-stats"]})},Wt=Ke=>{de.downloadLibraryFile(Ke).catch(at=>{console.error("Library file download failed:",at)})},Zt=()=>{F&&(F.type==="file"?tt.mutate(F.id):F.type==="folder"?Ye.mutate(F.id):F.type==="bulk"&&pe.mutate(p))},Kt=Ye.isPending||tt.isPending||pe.isPending,Xt=Ke=>{me(Ke),localStorage.setItem("library-view-mode",Ke)},ln=_e||ve,vn=w.useMemo(()=>{if(!u||!ae)return null;const Ke=at=>{for(const Lt of at){if(Lt.id===u)return Lt;const Et=Ke(Lt.children);if(Et)return Et}return null};return Ke(ae)},[u,ae]);return a.jsxs("div",{className:"p-4 md:p-8 min-h-[calc(100vh-64px)] lg:h-[calc(100vh-64px)] flex flex-col",children:[a.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4 mb-6",children:[a.jsxs("div",{children:[a.jsxs("h1",{className:"text-2xl font-bold text-white flex items-center gap-3",children:[a.jsx("div",{className:"p-2.5 bg-bambu-green/10 rounded-xl",children:a.jsx(Qc,{className:"w-6 h-6 text-bambu-green"})}),t("fileManager.title")]}),a.jsx("p",{className:"text-sm text-bambu-gray mt-2 ml-14",children:t("fileManager.subtitle")})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs("div",{className:"flex items-center bg-bambu-dark rounded-lg p-1",children:[a.jsx("button",{onClick:()=>Xt("grid"),className:`p-1.5 rounded transition-colors ${ne==="grid"?"bg-bambu-dark-secondary text-white":"text-bambu-gray hover:text-white"}`,title:t("fileManager.gridView"),children:a.jsx(eS,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>Xt("list"),className:`p-1.5 rounded transition-colors ${ne==="list"?"bg-bambu-dark-secondary text-white":"text-bambu-gray hover:text-white"}`,title:t("fileManager.listView"),children:a.jsx(tS,{className:"w-4 h-4"})})]}),a.jsxs(De,{variant:"secondary",onClick:()=>ce.mutate(),disabled:ce.isPending||!i("library:update_own","library:update_all"),title:i("library:update_own","library:update_all")?t("fileManager.generateThumbnailsForMissing"):t("fileManager.noPermissionGenerateThumbnail"),children:[ce.isPending?a.jsx(pt,{className:"w-4 h-4 mr-2 animate-spin"}):a.jsx(gm,{className:"w-4 h-4 mr-2"}),t("fileManager.generateThumbnails")]}),a.jsxs(De,{variant:"secondary",onClick:()=>g(!0),disabled:!r("library:upload"),title:r("library:upload")?t("fileManager.linkExternalFolder"):t("fileManager.noPermissionCreateFolder"),children:[a.jsx(SN,{className:"w-4 h-4 mr-2"}),t("fileManager.linkExternal")]}),a.jsxs(De,{variant:"secondary",onClick:()=>v(!0),disabled:!r("library:upload"),title:r("library:upload")?void 0:t("fileManager.noPermissionCreateFolder"),children:[a.jsx(gge,{className:"w-4 h-4 mr-2"}),t("fileManager.newFolder")]}),a.jsxs(De,{onClick:()=>N(!0),disabled:!r("library:upload"),title:r("library:upload")?void 0:t("fileManager.noPermissionUpload"),children:[a.jsx(La,{className:"w-4 h-4 mr-2"}),t("common.upload")]})]})]}),Me&&Te&&R&&a.jsxs("div",{className:"flex items-center gap-3 mb-4 p-3 bg-amber-500/10 border border-amber-500/30 rounded-lg",children:[a.jsx(Dn,{className:"w-5 h-5 text-amber-500 flex-shrink-0"}),a.jsxs("div",{className:"flex-1",children:[a.jsx("p",{className:"text-sm text-amber-500 font-medium",children:t("fileManager.lowDiskSpaceWarning")}),a.jsx("p",{className:"text-xs text-amber-500/80",children:t("fileManager.lowDiskSpaceDetails",{free:Lo(Te.disk_free_bytes),total:Lo(Te.disk_total_bytes),threshold:R.library_disk_warning_gb})})]})]}),Te&&a.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:[a.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[a.jsx($P,{className:"w-4 h-4 text-bambu-green"}),a.jsxs("span",{className:"text-bambu-gray",children:[t("fileManager.files"),":"]}),a.jsx("span",{className:"text-white font-medium",children:Te.total_files})]}),a.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[a.jsx(Qc,{className:"w-4 h-4 text-blue-400"}),a.jsxs("span",{className:"text-bambu-gray",children:[t("fileManager.folders"),":"]}),a.jsx("span",{className:"text-white font-medium",children:Te.total_folders})]}),a.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[a.jsx(Ig,{className:"w-4 h-4 text-amber-400"}),a.jsxs("span",{className:"text-bambu-gray",children:[t("fileManager.size"),":"]}),a.jsx("span",{className:"text-white font-medium",children:Lo(Te.total_size_bytes)})]}),a.jsxs("div",{className:"flex items-center gap-2 text-sm sm:ml-auto",children:[a.jsxs("span",{className:"text-bambu-gray",children:[t("fileManager.free"),":"]}),a.jsx("span",{className:`font-medium ${Me?"text-amber-500":"text-white"}`,children:Lo(Te.disk_free_bytes)})]})]}),a.jsxs("div",{className:"flex-1 flex flex-col lg:flex-row gap-4 lg:gap-6 min-h-0",children:[a.jsx("div",{className:"lg:hidden",children:a.jsxs("select",{value:u??"",onChange:Ke=>m(Ke.target.value?parseInt(Ke.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:[a.jsxs("option",{value:"",children:["📁 ",t("fileManager.allFiles")]}),ae&&(()=>{const Ke=(at,Lt=0)=>{const Et=[];for(const At of at)Et.push({id:At.id,name:At.name,fileCount:At.file_count,depth:Lt}),At.children.length>0&&Et.push(...Ke(At.children,Lt+1));return Et};return Ke(ae).map(at=>a.jsxs("option",{value:at.id,children:["│ ".repeat(at.depth),"📂 ",at.name," ",at.fileCount>0?`(${at.fileCount})`:""]},at.id))})()]})}),a.jsxs("div",{ref:U,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:`${E}px`},children:[a.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 ${O?"bg-bambu-green":"hover:bg-bambu-green/50"}`,onMouseDown:Ke=>{Ke.preventDefault(),K(!0)},onDoubleClick:()=>{j(256),localStorage.setItem("library-sidebar-width","256")},title:t("fileManager.dragToResizeTooltip"),children:a.jsxs("div",{className:`flex flex-col gap-1 opacity-0 group-hover/resize:opacity-100 transition-opacity ${O?"opacity-100":""}`,children:[a.jsx("div",{className:"w-0.5 h-0.5 rounded-full bg-white/70"}),a.jsx("div",{className:"w-0.5 h-0.5 rounded-full bg-white/70"}),a.jsx("div",{className:"w-0.5 h-0.5 rounded-full bg-white/70"})]})}),a.jsxs("div",{className:"p-3 border-b border-bambu-dark-tertiary flex items-center justify-between",children:[a.jsx("h2",{className:"text-sm font-medium text-white",children:t("fileManager.folders")}),a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsx("button",{onClick:()=>{const Ke=!q;Y(Ke),localStorage.setItem("library-collapse-folders",String(Ke))},className:`text-xs px-1.5 py-0.5 rounded transition-colors ${q?"bg-bambu-green/20 text-bambu-green":"text-bambu-gray hover:text-white hover:bg-bambu-dark"}`,title:t(q?"fileManager.expandFoldersByDefault":"fileManager.collapseFoldersByDefault"),children:t("fileManager.collapse")}),a.jsx("button",{onClick:()=>{const Ke=!be;Ce(Ke),localStorage.setItem("library-wrap-folders",String(Ke))},className:`text-xs px-1.5 py-0.5 rounded transition-colors ${be?"bg-bambu-green/20 text-bambu-green":"text-bambu-gray hover:text-white hover:bg-bambu-dark"}`,title:t(be?"fileManager.disableTextWrapping":"fileManager.enableTextWrapping"),children:t("fileManager.wrap")})]})]}),a.jsxs("div",{className:"flex-1 overflow-y-auto p-2",children:[a.jsxs("div",{className:`flex items-center gap-2 px-2 py-1.5 rounded cursor-pointer transition-colors ${u===null?"bg-bambu-green/20 text-bambu-green":"hover:bg-bambu-dark text-white"}`,onClick:()=>m(null),children:[a.jsx(ep,{className:"w-4 h-4"}),a.jsx("span",{className:"text-sm",children:t("fileManager.allFiles")})]}),ae?.map(Ke=>a.jsx(qle,{folder:Ke,selectedFolderId:u,onSelect:m,onDelete:at=>k({type:"folder",id:at}),onLink:T,onRename:at=>J({type:"folder",id:at.id,name:at.name}),wrapNames:be,defaultExpanded:!q,hasPermission:r,t},`${Ke.id}-${q?"c":"e"}`))]})]}),a.jsxs("div",{className:"flex-1 flex flex-col min-w-0 min-h-0",children:[vn?.is_external&&a.jsxs("div",{className:"flex items-center gap-3 mb-4 p-3 bg-purple-500/10 border border-purple-500/30 rounded-lg",children:[a.jsx(SN,{className:"w-5 h-5 text-purple-400 flex-shrink-0"}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:"text-sm font-medium text-purple-300",children:t("fileManager.externalFolder")}),vn.external_readonly&&a.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:[a.jsx(kd,{className:"w-3 h-3"}),t("fileManager.readOnly")]})]}),a.jsx("p",{className:"text-xs text-bambu-gray truncate font-mono",title:vn.external_path||"",children:vn.external_path})]}),a.jsxs(De,{variant:"secondary",size:"sm",onClick:()=>u&&$e.mutate(u),disabled:$e.isPending,title:t("fileManager.scanFolder"),children:[$e.isPending?a.jsx(pt,{className:"w-4 h-4 animate-spin"}):a.jsx(lr,{className:"w-4 h-4"}),a.jsx("span",{className:"ml-1.5",children:t("fileManager.scanFolder")})]})]}),Se&&Se.length>0&&a.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:[a.jsxs("div",{className:"relative w-full sm:w-auto sm:flex-1 sm:max-w-xs",children:[a.jsx(Pr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),a.jsx("input",{type:"text",placeholder:t("fileManager.searchFiles"),value:ue,onChange:Ke=>I(Ke.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"})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(VP,{className:"w-4 h-4 text-bambu-gray hidden sm:block"}),a.jsxs("select",{value:G,onChange:Ke=>X(Ke.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:[a.jsx("option",{value:"all",children:t("fileManager.allTypes")}),Ae.map(Ke=>a.jsx("option",{value:Ke,children:Ke.toUpperCase()},Ke))]})]}),o&&a.jsxs("div",{className:"relative",children:[a.jsx("input",{type:"text",placeholder:t("fileManager.filterByUser",{defaultValue:"Filter by user"}),value:V,onChange:Ke=>ee(Ke.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 ${V?"pr-7":""}`,style:V?{WebkitAppearance:"none",MozAppearance:"textfield"}:void 0}),V&&a.jsx("button",{onClick:()=>ee(""),className:"absolute right-2 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white z-10",children:a.jsx(Ht,{className:"w-3 h-3"})}),a.jsx("datalist",{id:"usernames-list",children:ye?.map(Ke=>a.jsx("option",{value:Ke.username},Ke.id))})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs("select",{value:se,onChange:Ke=>{const at=Ke.target.value;ge(at),localStorage.setItem("library-sort-field",at)},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:[a.jsx("option",{value:"name",children:t("common.name")}),a.jsx("option",{value:"date",children:t("common.date")}),a.jsx("option",{value:"size",children:t("fileManager.size")}),a.jsx("option",{value:"type",children:t("common.type")}),a.jsx("option",{value:"prints",children:t("fileManager.prints")})]}),a.jsx("button",{onClick:()=>le(Ke=>{const at=Ke==="asc"?"desc":"asc";return localStorage.setItem("library-sort-direction",at),at}),className:"p-1.5 rounded bg-bambu-dark border border-bambu-dark-tertiary hover:border-bambu-green transition-colors",title:t(he==="asc"?"fileManager.ascending":"fileManager.descending"),children:he==="asc"?a.jsx(Spe,{className:"w-4 h-4 text-white"}):a.jsx(fpe,{className:"w-4 h-4 text-white"})})]}),(ue||G!=="all"||V)&&a.jsx("span",{className:"text-sm text-bambu-gray hidden sm:inline",children:t("fileManager.resultsCount",{showing:Le.length,total:Se.length})})]}),Le.length>0&&a.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:[p.length===Le.length&&p.length>0?a.jsxs(De,{variant:"secondary",size:"sm",onClick:gt,children:[a.jsx(uo,{className:"w-4 h-4 sm:mr-1"}),a.jsx("span",{className:"hidden sm:inline",children:t("fileManager.deselectAll")})]}):a.jsxs(De,{variant:"secondary",size:"sm",onClick:xt,children:[a.jsx(Ns,{className:"w-4 h-4 sm:mr-1"}),a.jsx("span",{className:"hidden sm:inline",children:t("fileManager.selectAll")})]}),p.length>0&&a.jsxs(a.Fragment,{children:[a.jsx("span",{className:"text-sm text-bambu-gray ml-2",children:t("fileManager.selected",{count:p.length})}),a.jsx("div",{className:"hidden sm:block flex-1"}),a.jsxs("div",{className:"w-full sm:w-auto flex flex-wrap items-center gap-2 mt-2 sm:mt-0",children:[Qe.length===1&&a.jsxs(De,{variant:"primary",size:"sm",onClick:()=>Q(Qe[0]),disabled:!r("printers:control"),title:r("printers:control")?void 0:t("fileManager.noPermissionPrint"),children:[a.jsx(es,{className:"w-4 h-4 sm:mr-1"}),a.jsx("span",{className:"hidden sm:inline",children:t("common.print")})]}),Qe.length===1&&a.jsxs(De,{variant:"secondary",size:"sm",onClick:()=>te(Qe[0]),disabled:!r("queue:create"),title:r("queue:create")?void 0:t("fileManager.noPermissionAddToQueue"),children:[a.jsx(Yn,{className:"w-4 h-4 sm:mr-1"}),a.jsx("span",{className:"hidden sm:inline",children:t("fileManager.schedulePrint")})]}),a.jsxs(De,{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:[a.jsx(Cbe,{className:"w-4 h-4 sm:mr-1"}),a.jsx("span",{className:"hidden sm:inline",children:t("common.move")})]}),a.jsxs(De,{variant:"danger",size:"sm",onClick:()=>{p.length===1?k({type:"file",id:p[0]}):k({type:"bulk",id:0,count:p.length})},disabled:!i("library:delete_own","library:delete_all"),title:i("library:delete_own","library:delete_all")?void 0:t("fileManager.noPermissionDeleteFiles"),children:[a.jsx(en,{className:"w-4 h-4 sm:mr-1"}),a.jsx("span",{className:"hidden sm:inline",children:t("common.delete")})]}),a.jsxs(De,{variant:"secondary",size:"sm",onClick:gt,children:[a.jsx(Ht,{className:"w-4 h-4 sm:mr-1"}),a.jsx("span",{className:"hidden sm:inline",children:t("common.clear")})]})]})]})]}),ln?a.jsx("div",{className:"flex-1 flex items-center justify-center",children:a.jsxs("div",{className:"flex flex-col items-center gap-3",children:[a.jsx(pt,{className:"w-8 h-8 animate-spin text-bambu-green"}),a.jsx("p",{className:"text-sm text-bambu-gray",children:t("fileManager.loadingFiles")})]})}):Se?.length===0?a.jsxs("div",{className:"flex-1 flex flex-col items-center justify-center",children:[a.jsx("div",{className:"p-4 bg-bambu-dark rounded-2xl mb-4",children:a.jsx(ep,{className:"w-12 h-12 text-bambu-gray/50"})}),a.jsx("h3",{className:"text-lg font-medium text-white mb-2",children:t(u!==null?"fileManager.folderIsEmpty":"fileManager.noFilesYet")}),a.jsx("p",{className:"text-bambu-gray text-center max-w-md mb-6",children:t(u!==null?"fileManager.folderEmptyDescription":"fileManager.noFilesDescription")}),a.jsxs(De,{onClick:()=>N(!0),disabled:!r("library:upload"),title:r("library:upload")?void 0:t("fileManager.noPermissionUpload"),children:[a.jsx(sr,{className:"w-4 h-4 mr-2"}),t("fileManager.uploadFiles")]})]}):Le.length===0?a.jsxs("div",{className:"flex-1 flex flex-col items-center justify-center",children:[a.jsx("div",{className:"p-4 bg-bambu-dark rounded-2xl mb-4",children:a.jsx(Pr,{className:"w-12 h-12 text-bambu-gray/50"})}),a.jsx("h3",{className:"text-lg font-medium text-white mb-2",children:t("fileManager.noMatchingFiles")}),a.jsx("p",{className:"text-bambu-gray text-center max-w-md mb-6",children:t("fileManager.noMatchingFilesDescription")}),a.jsx(De,{variant:"secondary",onClick:()=>{I(""),X("all")},children:t("fileManager.clearFilters")})]}):ne==="grid"?a.jsx("div",{className:"flex-1 lg:overflow-y-auto",children:a.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:Le.map(Ke=>a.jsx(hrt,{file:Ke,isSelected:p.includes(Ke.id),isMobile:B,t,onSelect:ht,onDelete:at=>k({type:"file",id:at}),onDownload:Wt,onAddToQueue:at=>{const Lt=Se?.find(Et=>Et.id===at);Lt&&te(Lt)},onPrint:H,onPreview3d:W,onRename:at=>J({type:"file",id:at.id,name:at.filename}),onGenerateThumbnail:at=>xe.mutate(at.id),thumbnailVersion:oe[Ke.id],hasPermission:r,canModify:s,authEnabled:o},Ke.id))})}):a.jsx("div",{className:"flex-1 lg:overflow-y-auto",children:a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg border border-bambu-dark-tertiary overflow-hidden",children:[a.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:[a.jsx("div",{className:"w-6"}),a.jsx("div",{children:t("common.name")}),o&&a.jsx("div",{children:t("fileManager.uploadedBy",{defaultValue:"Uploaded By"})}),a.jsx("div",{children:t("common.type")}),a.jsx("div",{children:t("fileManager.size")}),a.jsx("div",{children:t("fileManager.prints")}),a.jsx("div",{})]}),Le.map(Ke=>a.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 ${p.includes(Ke.id)?"bg-bambu-green/10":""}`,onClick:()=>ht(Ke.id),children:[a.jsx("div",{className:`w-5 h-5 rounded border-2 flex items-center justify-center ${p.includes(Ke.id)?"bg-bambu-green border-bambu-green":"border-bambu-gray/50"}`,children:p.includes(Ke.id)&&a.jsx("div",{className:"w-2 h-2 bg-white rounded-sm"})}),a.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[a.jsxs("div",{className:"relative group/thumb",children:[a.jsx("div",{className:"w-10 h-10 rounded bg-bambu-dark flex-shrink-0 overflow-hidden",children:Ke.thumbnail_path?a.jsx("img",{src:`${de.getLibraryFileThumbnailUrl(Ke.id)}${oe[Ke.id]?(de.getLibraryFileThumbnailUrl(Ke.id).includes("?")?"&":"?")+`v=${oe[Ke.id]}`:""}`,alt:"",className:"w-full h-full object-cover"}):a.jsx("div",{className:"w-full h-full flex items-center justify-center",children:a.jsx(ep,{className:"w-5 h-5 text-bambu-gray/50"})})}),Ke.thumbnail_path&&a.jsx("div",{className:"absolute left-0 top-full mt-2 z-50 hidden group-hover/thumb:block",children:a.jsx("div",{className:"w-48 h-48 rounded-lg bg-bambu-dark-secondary border border-bambu-dark-tertiary shadow-xl overflow-hidden",children:a.jsx("img",{src:`${de.getLibraryFileThumbnailUrl(Ke.id)}${oe[Ke.id]?(de.getLibraryFileThumbnailUrl(Ke.id).includes("?")?"&":"?")+`v=${oe[Ke.id]}`:""}`,alt:Ke.filename,className:"w-full h-full object-contain"})})})]}),a.jsx("div",{className:"min-w-0",children:a.jsx("div",{className:"text-sm text-white truncate",children:Ke.print_name||Ke.filename})})]}),o&&a.jsx("div",{className:"text-sm text-bambu-gray flex items-center gap-1",children:Ke.created_by_username?a.jsxs(a.Fragment,{children:[a.jsx(ym,{className:"w-3 h-3"}),a.jsx("span",{className:"truncate",children:Ke.created_by_username})]}):"-"}),a.jsx("div",{children:a.jsx("span",{className:`text-xs px-1.5 py-0.5 rounded font-medium ${Ke.file_type==="3mf"?"bg-bambu-green/20 text-bambu-green":Ke.file_type==="gcode"?"bg-blue-500/20 text-blue-400":Ke.file_type==="stl"?"bg-purple-500/20 text-purple-400":"bg-bambu-gray/20 text-bambu-gray"}`,children:Ke.file_type.toUpperCase()})}),a.jsx("div",{className:"text-sm text-bambu-gray",children:Lo(Ke.file_size)}),a.jsx("div",{className:"text-sm text-bambu-gray",children:Ke.print_count>0?`${Ke.print_count}x`:"-"}),a.jsxs("div",{className:"flex items-center gap-1",onClick:at=>at.stopPropagation(),children:[cO(Ke.filename)&&a.jsxs(a.Fragment,{children:[a.jsx("button",{onClick:()=>r("printers:control")&&H(Ke),className:`p-1.5 rounded transition-colors ${r("printers:control")?"hover:bg-bambu-dark text-bambu-gray hover:text-bambu-green":"text-bambu-gray/50 cursor-not-allowed"}`,title:r("printers:control")?t("common.print"):t("fileManager.noPermissionPrint"),disabled:!r("printers:control"),children:a.jsx(Er,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>{r("queue:create")&&te(Ke)},className:`p-1.5 rounded transition-colors ${r("queue:create")?"hover:bg-bambu-dark text-bambu-gray hover:text-white":"text-bambu-gray/50 cursor-not-allowed"}`,title:r("queue:create")?t("fileManager.schedulePrint"):t("fileManager.noPermissionAddToQueue"),disabled:!r("queue:create"),children:a.jsx(Yn,{className:"w-4 h-4"})})]}),(Ke.file_type==="3mf"||Ke.file_type==="gcode"||Ke.file_type==="stl")&&a.jsx("button",{onClick:()=>r("library:read")&&W(Ke),className:`p-1.5 rounded transition-colors ${r("library:read")?"hover:bg-bambu-dark text-bambu-gray hover:text-bambu-green":"text-bambu-gray/50 cursor-not-allowed"}`,title:r("library:read")?"3D Preview":"You do not have permission to preview files",disabled:!r("library:read"),children:a.jsx(vi,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>r("library:read")&&Wt(Ke.id),className:`p-1.5 rounded transition-colors ${r("library:read")?"hover:bg-bambu-dark text-bambu-gray hover:text-white":"text-bambu-gray/50 cursor-not-allowed"}`,title:r("library:read")?t("common.download"):t("fileManager.noPermissionDownload"),disabled:!r("library:read"),children:a.jsx(ga,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>s("library","update",Ke.created_by_id)&&J({type:"file",id:Ke.id,name:Ke.filename}),className:`p-1.5 rounded transition-colors ${s("library","update",Ke.created_by_id)?"hover:bg-bambu-dark text-bambu-gray hover:text-white":"text-bambu-gray/50 cursor-not-allowed"}`,title:s("library","update",Ke.created_by_id)?t("common.rename"):t("fileManager.noPermissionRenameFile"),disabled:!s("library","update",Ke.created_by_id),children:a.jsx(ci,{className:"w-4 h-4"})}),Ke.file_type==="stl"&&a.jsx("button",{onClick:()=>s("library","update",Ke.created_by_id)&&xe.mutate(Ke.id),className:`p-1.5 rounded transition-colors ${s("library","update",Ke.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",Ke.created_by_id)?t("fileManager.generateThumbnail"):t("fileManager.noPermissionGenerateThumbnail"),disabled:xe.isPending||!s("library","update",Ke.created_by_id),children:a.jsx(gm,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>s("library","delete",Ke.created_by_id)&&k({type:"file",id:Ke.id}),className:`p-1.5 rounded transition-colors ${s("library","delete",Ke.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",Ke.created_by_id)?t("common.delete"):t("fileManager.noPermissionDeleteFile"),disabled:!s("library","delete",Ke.created_by_id),children:a.jsx(en,{className:"w-4 h-4"})})]})]},Ke.id))]})})]})]}),y&&a.jsx(lrt,{parentId:u,onClose:()=>v(!1),onSave:Ke=>Oe.mutate(Ke),isLoading:Oe.isPending,t}),b&&a.jsx(crt,{onClose:()=>g(!1),onSave:Ke=>Re.mutate(Ke),isLoading:Re.isPending,t}),_&&ae&&a.jsx(urt,{folders:ae,selectedFiles:p,currentFolderId:u,onClose:()=>C(!1),onMove:Ke=>Fe.mutate({fileIds:p,folderId:Ke}),isLoading:Fe.isPending,t}),P&&a.jsx(Yae,{folderId:u,onClose:()=>N(!1),onUploadComplete:Ut}),A&&a.jsx(mrt,{folder:A,onClose:()=>T(null),onLink:Ke=>we.mutate({id:A.id,data:Ke}),isLoading:we.isPending,t}),F&&a.jsx(yn,{title:F.type==="folder"?t("fileManager.deleteFolder"):F.type==="bulk"?t("fileManager.deleteFilesCount",{count:F.count}):t("fileManager.deleteFile"),message:F.type==="folder"?t("fileManager.deleteFolderConfirm"):F.type==="bulk"?t("fileManager.deleteFilesConfirm",{count:F.count}):t("fileManager.deleteFileConfirm"),confirmText:t("common.delete"),variant:"danger",isLoading:Kt,loadingText:t("fileManager.deleting"),onConfirm:Zt,onCancel:()=>k(null)}),D&&a.jsx(sc,{mode:"reprint",libraryFileId:D.id,archiveName:D.print_name||D.filename,onClose:()=>H(null),onSuccess:()=>{H(null),e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["archives"]})}}),z&&a.jsx(sc,{mode:"reprint",libraryFileId:z.id,archiveName:z.print_name||z.filename,onClose:()=>Q(null),onSuccess:()=>{Q(null),f([]),e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["archives"]})}}),L&&a.jsx(sc,{mode:"add-to-queue",libraryFileId:L.id,archiveName:L.print_name||L.filename,onClose:()=>te(null),onSuccess:()=>{te(null),f([]),e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["queue"]}),e.invalidateQueries({queryKey:["archives"]})}}),re&&a.jsx(_z,{libraryFileId:re.id,title:re.print_name||re.filename,fileType:re.file_type,onClose:()=>W(null)}),ie&&a.jsx(drt,{type:ie.type,currentName:ie.name,onClose:()=>J(null),onSave:Ke=>{ie.type==="file"?Ve.mutate({id:ie.id,filename:Ke}):je.mutate({id:ie.id,name:Ke})},isLoading:Ve.isPending||je.isPending,t})]})}function frt(t,e){const n=`token=${encodeURIComponent(e)}`;let r=0;return t.querySelectorAll('img[src*="/api/v1/"], video[src*="/api/v1/"]').forEach(i=>{const s=i.getAttribute("src")||"";if(s.includes(n))return;const o=s.replace(/([?&])token=[^&]*(&|$)/,(c,d,u)=>u==="&"?d:""),l=o.includes("?")?"&":"?";i.src=`${o}${l}${n}`,r+=1}),r}function $le(){const{authEnabled:t,user:e}=Sr(),n=nn(),r=w.useRef(!1),{data:i}=Xe({queryKey:["camera-stream-token",e?.id??null],queryFn:()=>de.getCameraStreamToken(),enabled:t?!!e:!0,staleTime:3e3*1e3,refetchInterval:3e3*1e3});w.useEffect(()=>{const s=i?.token??null;return jH(s),s&&frt(document,s),()=>jH(null)},[i?.token]),w.useEffect(()=>{if(!t)return;const s=o=>{const l=o.target;if(!(l instanceof HTMLImageElement||l instanceof HTMLVideoElement))return;const c=l.src||"",d=QQ();!d||!c.includes(`token=${encodeURIComponent(d)}`)||r.current||(r.current=!0,n.invalidateQueries({queryKey:["camera-stream-token"]}),setTimeout(()=>{r.current=!1},5e3))};return document.addEventListener("error",s,!0),()=>document.removeEventListener("error",s,!0)},[t,n])}const Lk=5,grt=2e3,brt=3e4,xrt=5e3;function yrt(){const{t}=Ft(),e=nn(),{showToast:n}=hn(),{hasPermission:r,authEnabled:i,user:s}=Sr(),{printerId:o}=Yw(),l=parseInt(o||"0",10);$le();const{data:c}=Xe({queryKey:["camera-stream-token",s?.id??null],queryFn:()=>de.getCameraStreamToken(),enabled:i?!!s:!0,staleTime:3e3*1e3}),d=c?.token??QQ(),[u,m]=w.useState("stream"),[p,f]=w.useState(!1),[y,v]=w.useState(!1),[b,g]=w.useState(!0),[_,C]=w.useState(Date.now()),[P,N]=w.useState(!1),[A,T]=w.useState(!1),[F,k]=w.useState(0),[D,H]=w.useState(!1),[z,Q]=w.useState(0),[L,te]=w.useState(1),[ie,J]=w.useState({x:0,y:0}),[oe,fe]=w.useState(!1),[re,W]=w.useState({x:0,y:0}),[ne,me]=w.useState(null),[be,Ce]=w.useState(null),q=w.useRef(null),Y=w.useRef(null),E=w.useRef(null),j=w.useRef(null),O=w.useRef(null),{data:K}=Xe({queryKey:["printer",l],queryFn:()=>de.getPrinter(l),enabled:l>0}),{data:U}=Xe({queryKey:["printerStatus",l],queryFn:()=>de.getPrinterStatus(l),refetchInterval:3e4,enabled:l>0}),ue=it({mutationFn:Fe=>de.setChamberLight(l,Fe),onMutate:async Fe=>{await e.cancelQueries({queryKey:["printerStatus",l]});const we=e.getQueryData(["printerStatus",l]);return e.setQueryData(["printerStatus",l],Ve=>({...Ve,chamber_light:Fe})),{previousStatus:we}},onSuccess:(Fe,we)=>{n(`Chamber light ${we?"on":"off"}`)},onError:(Fe,we,Ve)=>{Ve?.previousStatus&&e.setQueryData(["printerStatus",l],Ve.previousStatus),n(Fe.message||t("printers.toast.failedToControlChamberLight"),"error")}}),I=(U?.state==="RUNNING"||U?.state==="PAUSE")&&(U?.printable_objects_count??0)>=2;w.useEffect(()=>(K&&(document.title=`${K.name} - Camera`),()=>{document.title="Bambuddy"}),[K]);const G=w.useRef(!1);w.useEffect(()=>{const Fe=`/api/v1/printers/${l}/camera/stop`;G.current=!1;const we=()=>{if(l>0&&!G.current){G.current=!0;const ce={},xe=vm();xe&&(ce.Authorization=`Bearer ${xe}`),fetch(Fe,{method:"POST",keepalive:!0,headers:ce}).catch(()=>{})}},Ve=()=>{we()};window.addEventListener("beforeunload",Ve);const je=q.current;return()=>{window.removeEventListener("beforeunload",Ve),je&&(je.src=""),we()}},[l]),w.useEffect(()=>{if(b&&!P){const we=setTimeout(()=>{g(!1)},u==="stream"?3e3:2e4);return()=>clearTimeout(we)}},[u,b,_,P]),w.useEffect(()=>{const Fe=()=>{const we=!!document.fullscreenElement;T(we),te(1),J({x:0,y:0}),u==="stream"&&!P&&(q.current&&(q.current.src=""),setTimeout(()=>{g(!0),C(Date.now())},200))};return document.addEventListener("fullscreenchange",Fe),()=>document.removeEventListener("fullscreenchange",Fe)},[u,P]),w.useEffect(()=>{let Fe;const we=()=>{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",we),()=>{clearTimeout(Fe),window.removeEventListener("resize",we)}},[]),w.useEffect(()=>()=>{E.current&&clearTimeout(E.current),j.current&&clearInterval(j.current),O.current&&clearInterval(O.current)},[]);const X=w.useCallback(()=>{if(F>=Lk){H(!1),v(!0);return}const Fe=Math.min(grt*Math.pow(2,F),brt);H(!0),Q(Math.ceil(Fe/1e3)),j.current=setInterval(()=>{Q(we=>we<=1?(j.current&&clearInterval(j.current),0):we-1)},1e3),E.current=setTimeout(()=>{k(we=>we+1),H(!1),g(!0),v(!1),q.current&&(q.current.src=""),C(Date.now())},Fe)},[F]);w.useEffect(()=>{if(u!=="stream"||b||D||P){O.current&&(clearInterval(O.current),O.current=null);return}return O.current=setInterval(async()=>{try{const Fe=await de.getCameraStatus(l);(Fe.stalled||!Fe.active&&!y)&&(console.log(`Stream issue detected: stalled=${Fe.stalled}, active=${Fe.active}, reconnecting...`),O.current&&(clearInterval(O.current),O.current=null),g(!1),X())}catch{}},xrt),()=>{O.current&&(clearInterval(O.current),O.current=null)}},[u,b,y,D,P,l,X]);const V=()=>{g(!1),u==="stream"&&F{if(g(!1),v(!1),k(0),H(!1),E.current&&clearTimeout(E.current),j.current&&clearInterval(j.current),q.current&&!localStorage.getItem("cameraWindowState")){const Fe=q.current,we=Fe.naturalWidth,Ve=Fe.naturalHeight;if(we>0&&Ve>0){const xe=window.outerWidth-window.innerWidth,Be=window.outerHeight-window.innerHeight,Qe=we+16+xe,ht=Ve+45+16+Be;try{window.resizeTo(Qe,ht)}catch{}}}},se=()=>{if(l>0){const Fe={},we=vm();we&&(Fe.Authorization=`Bearer ${we}`),fetch(`/api/v1/printers/${l}/camera/stop`,{method:"POST",headers:Fe}).catch(()=>{})}},ge=Fe=>{u===Fe||P||(N(!0),g(!0),v(!1),k(0),H(!1),te(1),J({x:0,y:0}),E.current&&clearTimeout(E.current),j.current&&clearInterval(j.current),q.current&&(q.current.src=""),u==="stream"&&se(),setTimeout(()=>{m(Fe),C(Date.now()),N(!1)},100))},he=()=>{P||(N(!0),g(!0),v(!1),k(0),H(!1),E.current&&clearTimeout(E.current),j.current&&clearInterval(j.current),q.current&&(q.current.src=""),u==="stream"&&se(),setTimeout(()=>{C(Date.now()),N(!1)},100))},le=()=>{Y.current&&(document.fullscreenElement?document.exitFullscreen():Y.current.requestFullscreen())},B=()=>{te(Fe=>Math.min(Fe+.5,4))},R=()=>{te(Fe=>{const we=Math.max(Fe-.5,1);return we===1&&J({x:0,y:0}),we})},ae=Fe=>{Fe.preventDefault(),Fe.deltaY<0?B():R()},_e=Fe=>{L>1&&(Fe.preventDefault(),fe(!0),W({x:Fe.clientX-ie.x,y:Fe.clientY-ie.y}))},Se=w.useCallback(()=>{if(!Y.current)return{x:300,y:200};const Fe=Y.current.getBoundingClientRect(),we=Fe.width*(L-1)/2,Ve=Fe.height*(L-1)/2;return{x:Math.max(50,we),y:Math.max(50,Ve)}},[L]),ve=Fe=>{if(oe&&L>1){const we=Fe.clientX-re.x,Ve=Fe.clientY-re.y,je=Se();J({x:Math.max(-je.x,Math.min(je.x,we)),y:Math.max(-je.y,Math.min(je.y,Ve))})}},Te=()=>{fe(!1)},ye=Fe=>{if(Fe.length<2)return 0;const we=Fe[0].clientX-Fe[1].clientX,Ve=Fe[0].clientY-Fe[1].clientY;return Math.sqrt(we*we+Ve*Ve)},Ae=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},Le=Fe=>{Fe.touches.length===2?(Fe.preventDefault(),me(ye(Fe.touches)),Ce(Ae(Fe.touches))):Fe.touches.length===1&&L>1&&(Fe.preventDefault(),fe(!0),W({x:Fe.touches[0].clientX-ie.x,y:Fe.touches[0].clientY-ie.y}))},Me=Fe=>{if(Fe.touches.length===2&&ne!==null){Fe.preventDefault();const we=ye(Fe.touches),Ve=we/ne;te(ce=>{const xe=Math.max(1,Math.min(4,ce*Ve));return xe===1&&J({x:0,y:0}),xe}),me(we);const je=Ae(Fe.touches);if(be){const ce=Se();J(xe=>({x:Math.max(-ce.x,Math.min(ce.x,xe.x+(je.x-be.x))),y:Math.max(-ce.y,Math.min(ce.y,xe.y+(je.y-be.y)))}))}Ce(je)}else if(Fe.touches.length===1&&oe&&L>1){Fe.preventDefault();const we=Fe.touches[0].clientX-re.x,Ve=Fe.touches[0].clientY-re.y,je=Se();J({x:Math.max(-je.x,Math.min(je.x,we)),y:Math.max(-je.y,Math.min(je.y,Ve))})}},Oe=Fe=>{Fe.touches.length<2&&(me(null),Ce(null)),Fe.touches.length===0&&fe(!1)},Re=()=>{te(1),J({x:0,y:0})},$e=i&&!d,Ye=Fe=>d?`${Fe}&token=${encodeURIComponent(d)}`:Ga(Fe),tt=P||$e?"":Ye(u==="stream"?`/api/v1/printers/${l}/camera/stream?fps=15&t=${_}`:`/api/v1/printers/${l}/camera/snapshot?t=${_}`),pe=b||P||D;return l?a.jsxs("div",{ref:Y,className:"min-h-screen bg-black flex flex-col",children:[a.jsxs("div",{className:"flex items-center justify-between px-4 py-2 bg-bambu-dark-secondary border-b border-bambu-dark-tertiary",children:[a.jsxs("h1",{className:"text-sm font-medium text-white flex items-center gap-2",children:[a.jsx(qx,{className:"w-4 h-4"}),K?.name||`Printer ${l}`]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs("div",{className:"flex bg-bambu-dark rounded p-0.5",children:[a.jsx("button",{onClick:()=>ge("stream"),disabled:pe,className:`px-3 py-1 text-xs rounded transition-colors ${u==="stream"?"bg-bambu-green text-white":"text-bambu-gray hover:text-white disabled:opacity-50"}`,children:t("camera.live")}),a.jsx("button",{onClick:()=>ge("snapshot"),disabled:pe,className:`px-3 py-1 text-xs rounded transition-colors ${u==="snapshot"?"bg-bambu-green text-white":"text-bambu-gray hover:text-white disabled:opacity-50"}`,children:t("camera.snapshot")})]}),a.jsx("button",{onClick:()=>ue.mutate(!U?.chamber_light),disabled:!U?.connected||ue.isPending||!r("printers:control"),className:`p-1.5 rounded disabled:opacity-50 ${U?.chamber_light?"bg-yellow-500/20 hover:bg-yellow-500/30":"hover:bg-bambu-dark-tertiary"}`,title:r("printers:control")?t("camera.chamberLight"):t("printers.permission.noControl"),children:a.jsx(xI,{on:U?.chamber_light??!1,className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>f(!0),disabled:!I||!r("printers:control"),className:`p-1.5 rounded disabled:opacity-50 ${I&&r("printers:control")?"hover:bg-bambu-dark-tertiary":""}`,title:r("printers:control")?t(I?"printers.skipObjects.tooltip":"printers.skipObjects.onlyWhilePrinting"):t("printers.permission.noControl"),children:a.jsx(sT,{className:"w-4 h-4 text-bambu-gray"})}),a.jsx("button",{onClick:he,disabled:pe,className:"p-1.5 hover:bg-bambu-dark-tertiary rounded disabled:opacity-50",title:t(u==="stream"?"camera.restartStream":"camera.refreshSnapshot"),children:a.jsx(lr,{className:`w-4 h-4 text-bambu-gray ${pe?"animate-spin":""}`})}),a.jsx("button",{onClick:le,className:"p-1.5 hover:bg-bambu-dark-tertiary rounded",title:t(A?"camera.exitFullscreen":"camera.fullscreen"),children:A?a.jsx(zQ,{className:"w-4 h-4 text-bambu-gray"}):a.jsx(fbe,{className:"w-4 h-4 text-bambu-gray"})})]})]}),a.jsx("div",{className:"flex-1 flex items-center justify-center p-2 overflow-hidden",onWheel:ae,onMouseMove:ve,onMouseUp:Te,onMouseLeave:Te,onTouchStart:Le,onTouchMove:Me,onTouchEnd:Oe,style:{touchAction:"none"},children:a.jsxs("div",{className:"relative w-full h-full flex items-center justify-center",children:[(b||P)&&!D&&a.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/50 z-10",children:a.jsxs("div",{className:"text-center",children:[a.jsx(lr,{className:"w-8 h-8 text-bambu-gray animate-spin mx-auto mb-2"}),a.jsx("p",{className:"text-sm text-bambu-gray",children:t(u==="stream"?"camera.connectingToCamera":"camera.capturingSnapshot")})]})}),D&&a.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/80 z-10",children:a.jsxs("div",{className:"text-center p-4",children:[a.jsx(Bd,{className:"w-10 h-10 text-orange-400 mx-auto mb-3"}),a.jsx("p",{className:"text-white mb-2",children:t("camera.connectionLost")}),a.jsx("p",{className:"text-sm text-bambu-gray mb-3",children:t("camera.reconnecting",{countdown:z,attempt:Math.min(F+1,Lk),max:Lk})}),a.jsx("button",{onClick:he,className:"px-4 py-2 bg-bambu-green text-white text-sm rounded hover:bg-bambu-green/80 transition-colors",children:t("camera.reconnectNow")})]})}),y&&!D&&a.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black z-10",children:a.jsxs("div",{className:"text-center p-4",children:[a.jsx(Dn,{className:"w-12 h-12 text-orange-400 mx-auto mb-3"}),a.jsx("p",{className:"text-white mb-2",children:t("camera.cameraUnavailable")}),a.jsx("p",{className:"text-xs text-bambu-gray mb-4 max-w-md",children:t("camera.cameraUnavailableDesc")}),a.jsx("button",{onClick:he,className:"px-4 py-2 bg-bambu-green text-white rounded hover:bg-bambu-green/80 transition-colors",children:t("camera.retry")})]})}),a.jsx("img",{ref:q,src:tt,alt:t("camera.cameraStream"),className:"max-w-full max-h-full object-contain select-none",style:{transform:`scale(${L}) translate(${ie.x/L}px, ${ie.y/L}px) rotate(${K?.camera_rotation||0}deg)`,...K?.camera_rotation===90||K?.camera_rotation===270?{maxWidth:"100vh",maxHeight:"100vw"}:{},cursor:L>1?oe?"grabbing":"grab":"default"},onError:tt?V:void 0,onLoad:tt?ee:void 0,onMouseDown:_e,draggable:!1},_),a.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:[a.jsx("button",{onClick:R,disabled:L<=1,className:"p-1.5 hover:bg-white/10 rounded disabled:opacity-30",title:t("camera.zoomOut"),children:a.jsx(zO,{className:"w-4 h-4 text-white"})}),a.jsxs("button",{onClick:Re,className:"px-2 py-1 text-sm text-white hover:bg-white/10 rounded min-w-[48px]",title:t("camera.resetZoom"),children:[Math.round(L*100),"%"]}),a.jsx("button",{onClick:B,disabled:L>=4,className:"p-1.5 hover:bg-white/10 rounded disabled:opacity-30",title:t("camera.zoomIn"),children:a.jsx(IO,{className:"w-4 h-4 text-white"})})]})]})}),a.jsx(yI,{printerId:l,isOpen:p,onClose:()=>f(!1)})]}):a.jsx("div",{className:"min-h-screen bg-black flex items-center justify-center",children:a.jsx("p",{className:"text-white",children:t("camera.invalidPrinterId")})})}function vrt(t,e,n){if(!t)return"";if(!e)return t;const r=e.match(/plate_(\d+)\.gcode/);return r&&parseInt(r[1],10)>1?`${t} — ${n("printers.plateNumber","Plate {{number}}",{number:r[1]})}`:t}function wrt(t){const e=t.get("show")?.split(",")||["progress","layers","eta","filename","status"],n=parseInt(t.get("fps")||"15",10),r=Math.min(Math.max(isNaN(n)?15:n,1),30),i=t.get("camera"),s=i!=="false"&&i!=="0";return{size:t.get("size")||"medium",fps:r,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 Srt(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 _rt(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 krt(){const{printerId:t}=Yw(),[e]=HP(),{t:n}=Ft(),r=nn(),i=parseInt(t||"0",10),[s,o]=w.useState(Date.now()),l=w.useMemo(()=>wrt(e),[e]),c=_rt(l.size),{data:d}=Xe({queryKey:["printer",i],queryFn:()=>de.getPrinter(i),enabled:i>0}),{data:u}=Xe({queryKey:["printerStatus",i],queryFn:()=>de.getPrinterStatus(i),enabled:i>0,refetchInterval:2e3}),{data:m}=Xe({queryKey:["settings"],queryFn:de.getSettings}),p=m?.time_format||"system";w.useEffect(()=>{if(!i)return;const _=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/api/v1/ws`,C=new WebSocket(_);return C.onmessage=P=>{try{const N=JSON.parse(P.data);N.type==="printer_status"&&N.printer_id===i&&r.setQueryData(["printerStatus",i],N.status)}catch{}},C.onerror=()=>{},()=>{C.close()}},[i,r]),w.useEffect(()=>(document.title=d?`${d.name} - ${n("streamOverlay.title")}`:n("streamOverlay.title"),()=>{document.title="Bambuddy"}),[d,n]);const f=()=>{setTimeout(()=>{o(Date.now())},3e3)};if(!i)return a.jsx("div",{className:"min-h-screen bg-black flex items-center justify-center",children:a.jsx("p",{className:"text-white",children:n("streamOverlay.invalidPrinterId")})});if(!u)return a.jsx("div",{className:"min-h-screen bg-black flex items-center justify-center",children:a.jsx("p",{className:"text-gray-400",children:n("common.loading")})});const y=u.state==="RUNNING"||u.state==="PAUSE",v=u.progress||0,b=Ga(`/api/v1/printers/${i}/camera/stream?fps=${l.fps}&t=${s}`);return a.jsxs("div",{className:"min-h-screen bg-black relative overflow-hidden",children:[l.showCamera&&a.jsx("img",{src:b,alt:n("streamOverlay.cameraStream"),className:"absolute inset-0 w-full h-full object-contain",style:d?.camera_rotation?{transform:`rotate(${d.camera_rotation}deg)`}:void 0,onError:f},s),a.jsx("a",{href:"https://github.com/maziggy/bambuddy",target:"_blank",rel:"noopener noreferrer",className:"absolute top-4 right-4 z-10",children:a.jsx("img",{src:"/img/bambuddy_logo_dark_transparent.png",alt:"Bambuddy",className:`${c.logoHeight} object-contain drop-shadow-lg hover:scale-105 transition-transform`})}),a.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:a.jsxs("div",{className:`${c.container}`,children:[l.showPrinter&&d&&a.jsxs("div",{className:`flex items-center ${c.gap} mb-2`,children:[a.jsx(Er,{className:`${c.icon} text-white/70`}),a.jsx("span",{className:`${c.text} text-white font-medium`,children:d.name})]}),l.showFilename&&u.current_print&&a.jsx("div",{className:`${c.textLarge} text-white font-semibold mb-2 truncate drop-shadow-md`,children:vrt(u.current_print.replace(/\.gcode\.3mf$|\.3mf$|\.gcode$/i,""),u.gcode_file,n)}),l.showStatus&&a.jsx("div",{className:`${c.text} text-white/70 mb-2`,children:Srt(u,n)}),l.showProgress&&y&&a.jsxs("div",{className:"mb-3",children:[a.jsxs("div",{className:`flex items-center justify-between mb-1 ${c.text}`,children:[a.jsx("span",{className:"text-white/70",children:n("streamOverlay.progress")}),a.jsxs("span",{className:"text-white font-bold",children:[Math.round(v),"%"]})]}),a.jsx("div",{className:`w-full bg-white/20 rounded-full ${c.progressHeight}`,children:a.jsx("div",{className:`bg-bambu-green ${c.progressHeight} rounded-full transition-all duration-500`,style:{width:`${v}%`}})})]}),y&&(l.showLayers||l.showEta)&&a.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&&a.jsxs("div",{className:`flex items-center ${c.gap} text-white/70`,children:[a.jsx(da,{className:c.icon}),a.jsxs("span",{className:c.text,children:[a.jsx("span",{className:"text-white",children:u.layer_num}),a.jsx("span",{className:"mx-1",children:"/"}),a.jsx("span",{children:u.total_layers})]})]}),l.showEta&&u.remaining_time!=null&&u.remaining_time>0&&a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:`flex items-center ${c.gap} text-white/70`,children:[a.jsx(jd,{className:c.icon}),a.jsx("span",{className:`${c.text} text-white`,children:ws(u.remaining_time*60)})]}),a.jsxs("div",{className:`flex items-center ${c.gap} text-white/70`,children:[a.jsx(Yn,{className:c.icon}),a.jsxs("span",{className:`${c.text} text-white`,children:[n("streamOverlay.eta")," ",qO(u.remaining_time,p,n)]})]})]})]}),!y&&a.jsx("div",{className:`${c.text} text-white/70 py-2`,children:u.connected?n("streamOverlay.printerIdle"):n("streamOverlay.printerOffline")})]})})]})}function Nrt(){const{t}=Ft(),{id:e}=Yw(),{mode:n}=zg(),{data:r,isLoading:i,error:s}=Xe({queryKey:["external-link",e],queryFn:()=>de.getExternalLink(Number(e)),enabled:!!e});return i?a.jsx("div",{className:"flex items-center justify-center h-full",children:a.jsx(pt,{className:"w-8 h-8 text-bambu-green animate-spin"})}):s||!r?a.jsxs("div",{className:"flex flex-col items-center justify-center h-full gap-4 text-bambu-gray",children:[a.jsx(Dn,{className:"w-12 h-12"}),a.jsx("p",{children:t("common.linkNotFound")})]}):a.jsx("iframe",{src:r.url,className:"h-full w-full border-0",style:{colorScheme:n},title:r.name,sandbox:"allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox"})}function NY(){const{id:t}=Yw(),e=qo(),n=nn(),{t:r}=Ft(),{showToast:i}=hn(),s=!!t,[o,l]=w.useState(""),[c,d]=w.useState(""),[u,m]=w.useState([]),[p,f]=w.useState(""),[y,v]=w.useState(!1),{data:b,isLoading:g}=Xe({queryKey:["group",t],queryFn:()=>de.getGroup(Number(t)),enabled:s}),{data:_,isLoading:C}=Xe({queryKey:["permissions"],queryFn:()=>de.getPermissions()});s&&b&&!y&&(l(b.name),d(b.description||""),m(b.permissions),v(!0));const P=it({mutationFn:J=>de.createGroup(J),onSuccess:()=>{n.invalidateQueries({queryKey:["groups"]}),i(r("groups.toast.created")),e("/settings?tab=users")},onError:J=>{i(J.message,"error")}}),N=it({mutationFn:J=>de.updateGroup(Number(t),J),onSuccess:()=>{n.invalidateQueries({queryKey:["groups"]}),i(r("groups.toast.updated")),e("/settings?tab=users")},onError:J=>{i(J.message,"error")}}),A=P.isPending||N.isPending,T=()=>{if(!o.trim()){i(r("groups.toast.enterGroupName"),"error");return}s?N.mutate({name:o!==b?.name?o:void 0,description:c,permissions:u}):P.mutate({name:o,description:c||void 0,permissions:u})},F=J=>{m(oe=>oe.includes(J)?oe.filter(fe=>fe!==J):[...oe,J])},k=(J,oe)=>{const fe=J.permissions.map(re=>re.value);m(re=>{const W=re.filter(ne=>!fe.includes(ne));return oe?[...W,...fe]:W})},D=J=>J.permissions.every(oe=>u.includes(oe.value)),H=J=>{const oe=J.permissions.filter(fe=>u.includes(fe.value)).length;return oe>0&&oe{_&&m(_.all_permissions)},Q=()=>{m([])},L=p.toLowerCase(),te=w.useMemo(()=>_?L?_.categories.map(J=>({...J,permissions:J.permissions.filter(oe=>oe.label.toLowerCase().includes(L))})).filter(J=>J.permissions.length>0):_.categories:[],[_,L]),ie=_?.all_permissions.length??0;return g||C?a.jsx("div",{className:"flex items-center justify-center py-16",children:a.jsx(pt,{className:"w-8 h-8 text-bambu-green animate-spin"})}):a.jsxs("div",{className:"space-y-6 max-w-5xl mx-auto",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.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:a.jsx(DQ,{className:"w-5 h-5"})}),a.jsx("h1",{className:"text-xl font-bold text-white",children:r(s?"groups.editor.title":"groups.editor.createTitle")})]}),s&&b?.is_system&&a.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:[a.jsx(Dn,{className:"w-4 h-4 shrink-0"}),r("groups.form.systemGroupWarning")]}),a.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:r("groups.form.groupName")}),a.jsx("input",{type:"text",value:o,onChange:J=>l(J.target.value),disabled:s&&b?.is_system,className:"w-full px-4 py-3 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors disabled:opacity-50",placeholder:r("groups.form.groupNamePlaceholder")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:r("groups.form.description")}),a.jsx("input",{type:"text",value:c,onChange:J=>d(J.target.value),className:"w-full px-4 py-3 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors",placeholder:r("groups.form.descriptionPlaceholder")})]})]}),a.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-3",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsxs("span",{className:"text-sm text-bambu-gray",children:[r("groups.editor.permissionsSelected",{count:u.length})," / ",ie]}),a.jsx(De,{size:"sm",variant:"ghost",onClick:z,children:r("groups.editor.selectAll")}),a.jsx(De,{size:"sm",variant:"ghost",onClick:Q,children:r("groups.editor.clearAll")})]}),a.jsxs("div",{className:"relative",children:[a.jsx(Pr,{className:"w-4 h-4 absolute left-3 top-1/2 -translate-y-1/2 text-bambu-gray"}),a.jsx("input",{type:"text",value:p,onChange:J=>f(J.target.value),placeholder:r("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"})]})]}),te.length===0?a.jsx("div",{className:"text-center py-12 text-bambu-gray",children:r("groups.editor.noResults")}):a.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:te.map(J=>{const oe=_.categories.find(me=>me.name===J.name),fe=oe.permissions.filter(me=>u.includes(me.value)).length,re=oe.permissions.length,W=D(oe),ne=H(oe);return a.jsxs(Tt,{children:[a.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:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsxs("button",{type:"button",onClick:()=>k(oe,!W),className:`w-5 h-5 rounded border flex items-center justify-center transition-colors shrink-0 ${W?"bg-bambu-green border-bambu-green":ne?"bg-bambu-green/50 border-bambu-green":"border-bambu-gray hover:border-white"}`,children:[W&&a.jsx(Ur,{className:"w-3 h-3 text-white"}),ne&&!W&&a.jsx(kN,{className:"w-3 h-3 text-white"})]}),a.jsx(Gu,{className:"w-4 h-4 text-bambu-gray shrink-0"}),a.jsx("span",{className:"text-white font-medium text-sm",children:J.name})]}),a.jsxs("span",{className:"text-xs text-bambu-gray tabular-nums",children:[fe,"/",re]})]}),a.jsx("div",{className:"p-3 space-y-1",children:J.permissions.map(me=>a.jsxs("label",{className:"flex items-center gap-3 px-2 py-1.5 rounded hover:bg-bambu-dark-secondary cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:u.includes(me.value),onChange:()=>F(me.value),className:"w-4 h-4 rounded border-bambu-gray text-bambu-green focus:ring-bambu-green focus:ring-offset-0 bg-bambu-dark-secondary"}),a.jsx("span",{className:"text-sm text-bambu-gray",children:me.label})]},me.value))})]},J.name)})}),a.jsx("div",{className:"h-16"}),a.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:[a.jsx(De,{variant:"secondary",onClick:()=>e("/settings?tab=users"),children:r("common.cancel")}),a.jsx(De,{onClick:T,disabled:A||!o.trim(),children:A?a.jsxs(a.Fragment,{children:[a.jsx(pt,{className:"w-4 h-4 animate-spin"}),r("common.saving")]}):a.jsxs(a.Fragment,{children:[a.jsx(_s,{className:"w-4 h-4"}),r("common.save")]})})]})]})}const dO={material:"",subtype:"",brand:"",color_name:"",rgba:"808080FF",label_weight:1e3,core_weight:250,core_weight_catalog_id:null,weight_used:0,slicer_filament:"",note:"",cost_per_kg:null};function Vle(t,e=!1){const n={};return e?(t.material||(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 Gle=["PLA","PETG","ABS","TPU","ASA","PC","PA","PVA","HIPS","PA-CF","PETG-CF","PLA-CF"],Crt=["Bambu","PolyLite","PolyTerra","eSUN","Overture","Fiberon","SUNLU","Inland","Hatchbox","Generic"],J0=["Basic","Matte","Silk","Silk+","Tough","Tough+","HF","High Flow","Engineering","Galaxy","Glow","Marble","Metal","Rainbow","Sparkle","Wood","Translucent","Transparent","Clear","Lite","Pro","Plus","Max","Super","Ultra","Flex","Soft","Hard","Strong","Impact","Heat Resistant","UV Resistant","ESD","Conductive","Magnetic","Gradient","Dual Color","Tri Color","Multicolor"],Wle=[{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"}],Prt=[{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"}],CY=[...Wle,...Prt],Kle="bambuddy-recent-colors",Trt=8,Art=[{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 Cp(t){let e=t.replace(/@.*$/,"").trim();e=e.replace(/\(Custom\)/i,"").trim(),e=e.replace(/^[#*]+\s*/,"").trim();const n=["PLA-CF","PETG-CF","ABS-GF","ASA-CF","PA-CF","PAHT-CF","PA6-CF","PA6-GF","PPA-CF","PPA-GF","PET-CF","PPS-CF","PC-CF","PC-ABS","ABS-GF","PCTG","PETG","PLA","ABS","ASA","PC","PA","TPU","PVA","HIPS","BVOH","PPS","PEEK","PEI"];let r="",i=-1;for(const c of n){const d=e.toUpperCase().indexOf(c.toUpperCase());if(d!==-1){r=c,i=d;break}}let s="";i>0&&(s=e.substring(0,i).trim(),s=s.replace(/[-_\s]+$/,""));let o="";i!==-1&&r&&(o=e.substring(i+r.length).trim(),o=o.replace(/^[-_\s]+/,""));let l="";for(const c of J0)if(o.toLowerCase().includes(c.toLowerCase())){l=c;break}if(!l&&s)for(const c of J0){const d=new RegExp(`\\s+${c}$`,"i");if(d.test(s)){l=c,s=s.replace(d,"").trim();break}}return{brand:s,material:r,variant:l}}function Xle(t,e){const n=new Set(Crt);for(const r of t){const{brand:i}=Cp(r.name);i&&i.length>1&&n.add(i)}if(e)for(const r of e)if(r.filament_vendor&&r.filament_vendor.length>1)n.add(r.filament_vendor);else{const{brand:i}=Cp(r.name);i&&i.length>1&&n.add(i)}return Array.from(n).sort((r,i)=>r.localeCompare(i))}function jrt(t){const e=t.filter(r=>r.preset_type==="filament");if(e.length===0)return[];const n=new Map;for(const r of e){const i=r.name.replace(/@.*$/,"").trim(),s=n.get(i);if(s)s.allCodes.push(String(r.id));else{const o=r.filament_type||String(r.id);n.set(i,{code:o,name:i,displayName:i,isCustom:!1,allCodes:[o]})}}return Array.from(n.values()).sort((r,i)=>r.displayName.localeCompare(i.displayName))}function Yle(t,e,n){if(t.length>0){const r=[],i=new Map;for(const s of t)if(s.is_custom){const o=s.name.toUpperCase();(e.size===0||Array.from(e).some(c=>o.includes(c))||!o.includes("@"))&&r.push({code:s.setting_id,name:s.name,displayName:`${s.name} (Custom)`,isCustom:!0,allCodes:[s.setting_id]})}else{const o=s.name.replace(/@.*$/,"").trim(),l=i.get(o);l?l.allCodes.push(s.setting_id):i.set(o,{code:s.setting_id,name:o,displayName:o,isCustom:!1,allCodes:[s.setting_id]})}return[...r,...Array.from(i.values())].sort((s,o)=>s.displayName.localeCompare(o.displayName))}if(n&&n.length>0){const r=jrt(n);if(r.length>0)return r}return Art}function Qle(t,e){if(!t)return;let n=e.find(r=>r.code===t);if(n||(n=e.find(r=>r.allCodes.includes(t))),!n){const r=t.toLowerCase();n=e.find(i=>i.code.toLowerCase()===r||i.allCodes.some(s=>s.toLowerCase()===r))}return n}function Zle(){try{const t=localStorage.getItem(Kle);if(t)return JSON.parse(t)}catch{}return[]}function Jle(t,e){const n=e.filter(i=>i.hex.toUpperCase()!==t.hex.toUpperCase()),r=[t,...n].slice(0,Trt);try{localStorage.setItem(Kle,JSON.stringify(r))}catch{}return r}function D3(t,e){if(!e.material)return!1;const r=(t.name||"").replace(/^High Flow[_\s]+/i,"").replace(/^Standard[_\s]+/i,"").replace(/^HF[_\s]+/i,"").replace(/^S[_\s]+/i,"").trim(),i=Cp(r);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())||r.toLowerCase().includes(e.subtype.toLowerCase())))}function ece({formData:t,updateField:e,cloudAuthenticated:n,loadingCloudPresets:r,presetInputValue:i,setPresetInputValue:s,selectedPresetOption:o,filamentOptions:l,availableBrands:c,availableMaterials:d,quickAdd:u,quantity:m,onQuantityChange:p,errors:f}){const{t:y}=Ft(),[v,b]=w.useState(!1),[g,_]=w.useState(!1),[C,P]=w.useState(!1),[N,A]=w.useState(!1),[T,F]=w.useState(""),[k,D]=w.useState(""),[H,z]=w.useState(""),[Q,L]=w.useState(String(t.label_weight)),[te,ie]=w.useState(!1),J=w.useRef(null),oe=w.useRef(null),fe=w.useRef(null),re=w.useRef(null);w.useEffect(()=>{const q=Y=>{J.current&&!J.current.contains(Y.target)&&b(!1),re.current&&!re.current.contains(Y.target)&&A(!1),oe.current&&!oe.current.contains(Y.target)&&_(!1),fe.current&&!fe.current.contains(Y.target)&&P(!1)};return document.addEventListener("mousedown",q),()=>document.removeEventListener("mousedown",q)},[]);const W=w.useMemo(()=>{if(!i)return l;const q=i.toLowerCase();return l.filter(Y=>Y.displayName.toLowerCase().includes(q)||Y.code.toLowerCase().includes(q))},[l,i]),ne=w.useMemo(()=>{if(!T)return c;const q=T.toLowerCase();return c.filter(E=>E.toLowerCase().includes(q)).sort((E,j)=>{const O=E.toLowerCase()===q,K=j.toLowerCase()===q;return O&&!K?-1:!O&&K?1:E.localeCompare(j)})},[c,T]),me=w.useMemo(()=>{if(!k)return J0;const q=k.toLowerCase();return J0.filter(Y=>Y.toLowerCase().includes(q))},[k]),be=w.useMemo(()=>{if(!H)return d;const q=H.toLowerCase();return d.filter(E=>E.toLowerCase().includes(q)).sort((E,j)=>{const O=E.toLowerCase()===q,K=j.toLowerCase()===q;return O&&!K?-1:!O&&K?1:E.localeCompare(j)})},[H,d]);w.useEffect(()=>{te||L(String(t.label_weight))},[t.label_weight,te]);const Ce=q=>{e("slicer_filament",q.code),s(q.displayName),b(!1);const Y=Cp(q.name);Y.material&&e("material",Y.material),Y.brand&&e("brand",Y.brand),Y.variant&&e("subtype",Y.variant)};return a.jsxs("div",{className:"space-y-4",children:[!u&&a.jsx("div",{className:"flex items-center gap-2 text-xs text-bambu-gray",children:r?a.jsxs(a.Fragment,{children:[a.jsx(pt,{className:"w-3 h-3 animate-spin"})," ",y("inventory.loadingPresets")]}):n?a.jsxs(a.Fragment,{children:[a.jsx(vy,{className:"w-3 h-3 text-bambu-green"})," ",y("inventory.cloudConnected")]}):a.jsxs(a.Fragment,{children:[a.jsx(xfe,{className:"w-3 h-3"})," ",y("inventory.cloudNotConnected")]})}),!u&&a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:[y("inventory.slicerPreset")," *"]}),a.jsxs("div",{className:"relative",ref:J,children:[a.jsx(Pr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50 pointer-events-none"}),a.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:y("inventory.searchPresets"),value:i,onChange:q=>{s(q.target.value),b(!0)},onFocus:()=>{b(!0),s("")}}),v&&a.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:W.length===0?a.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:y("inventory.noPresetsFound")}):W.map(q=>a.jsx("button",{type:"button",className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary truncate ${o?.code===q.code?"bg-bambu-green/10 text-bambu-green":"text-white"}`,onClick:()=>Ce(q),children:q.displayName},q.code))})]}),o&&a.jsxs("div",{className:"mt-1 text-xs text-bambu-gray",children:[y("inventory.selectedPreset"),": ",a.jsx("span",{className:"font-mono text-bambu-green",children:o.code})]}),f?.slicer_filament&&a.jsx("p",{className:"mt-1 text-xs text-red-400",children:f.slicer_filament})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:[y("inventory.material")," *"]}),a.jsxs("div",{className:"relative",ref:re,children:[a.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:y("inventory.selectMaterial"),value:N?H:t.material,onChange:q=>{z(q.target.value),A(!0)},onFocus:()=>{A(!0),z("")}}),a.jsx(On,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50 pointer-events-none"}),N&&a.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:[be.length===0?a.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:y("inventory.noResults")}):be.map(q=>a.jsx("button",{type:"button",className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary ${t.material===q?"bg-bambu-green/10 text-bambu-green":"text-white"}`,onClick:()=>{e("material",q),A(!1),z("")},children:q},q)),H&&!be.includes(H)&&a.jsx("button",{type:"button",className:"w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary text-bambu-green border-t border-bambu-dark-tertiary",onClick:()=>{e("material",H),A(!1),z("")},children:y("inventory.useCustomMaterial",{material:H})})]})]}),f?.material&&a.jsx("p",{className:"mt-1 text-xs text-red-400",children:f.material})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:[y("inventory.brand"),!u&&" *"]}),a.jsxs("div",{className:"relative",ref:oe,children:[a.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:y("inventory.searchBrand"),value:g?T:t.brand,onChange:q=>{F(q.target.value),_(!0)},onFocus:()=>{_(!0),F("")}}),a.jsx(On,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50 pointer-events-none"}),g&&a.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:[ne.length===0?a.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:y("inventory.noResults")}):ne.map(q=>a.jsx("button",{type:"button",className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary ${t.brand===q?"bg-bambu-green/10 text-bambu-green":"text-white"}`,onClick:()=>{e("brand",q),_(!1),F("")},children:q},q)),T&&!ne.includes(T)&&a.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",T),_(!1),F("")},children:y("inventory.useCustomBrand",{brand:T})})]})]}),f?.brand&&a.jsx("p",{className:"mt-1 text-xs text-red-400",children:f.brand})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:[y("inventory.subtype"),!u&&" *"]}),a.jsxs("div",{className:"relative",ref:fe,children:[a.jsx("input",{type:"text",value:C?k:t.subtype,onChange:q=>{D(q.target.value),P(!0)},onFocus:()=>{P(!0),D("")},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"}),a.jsx(On,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50 pointer-events-none"}),C&&a.jsxs("div",{className:"absolute z-50 w-full mt-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-lg max-h-48 overflow-y-auto",children:[me.length===0?a.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:y("inventory.noResults")}):me.map(q=>a.jsx("button",{type:"button",className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary ${t.subtype===q?"bg-bambu-green/10 text-bambu-green":"text-white"}`,onClick:()=>{e("subtype",q),P(!1),D("")},children:q},q)),k&&!J0.some(q=>q.toLowerCase()===k.toLowerCase().trim())&&a.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),P(!1),D("")},children:y("inventory.useCustomBrand",{brand:k})})]})]}),f?.subtype&&a.jsx("p",{className:"mt-1 text-xs text-red-400",children:f.subtype})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:y("inventory.labelWeight")}),a.jsxs("div",{className:"relative",children:[a.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:Q,min:0,onFocus:()=>ie(!0),onChange:q=>L(q.target.value),onBlur:()=>{ie(!1);const q=Q.trim(),Y=Number(q);if(!q||!Number.isFinite(Y)||Y<0){L(String(t.label_weight));return}const E=Math.round(Y);e("label_weight",E),L(String(E))}}),a.jsx("span",{className:"absolute right-2 top-1/2 -translate-y-1/2 text-xs text-bambu-gray",children:"g"})]})]}),u&&a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:y("inventory.quantity")}),a.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:q=>{const Y=Math.max(1,Math.min(100,parseInt(q.target.value)||1));p(Y)}})]})]})}function tce({formData:t,updateField:e,recentColors:n,onColorUsed:r,catalogColors:i}){const{t:s}=Ft(),[o,l]=w.useState(!1),[c,d]=w.useState(""),u=t.rgba.replace("#","").substring(0,6),m=g=>u.toUpperCase()===g.toUpperCase(),p=(g,_)=>{e("rgba",g.toUpperCase()+"FF"),e("color_name",_),r({name:_,hex:g})},f=w.useMemo(()=>{if(i.length===0)return[];const g=t.brand?.trim(),_=t.material?.toLowerCase().trim(),C=t.subtype?.toLowerCase().trim();if(!g&&!_)return[];const P=g?g.toLowerCase().split(/[\s\-_]+/).filter(T=>T.length>=2):[],N=T=>{if(P.length===0)return!0;const F=T.toLowerCase();return P.some(k=>F.includes(k))};if(g&&!_){const T=i.filter(F=>N(F.manufacturer));if(T.length>0)return T.map(F=>({name:F.color_name,hex:F.hex_color.replace("#","").substring(0,6),manufacturer:F.manufacturer,material:typeof F.material=="string"?F.material:void 0}))}const A=_&&C?`${_} ${C}`:"";if(A){const T=i.filter(k=>N(k.manufacturer)&&k.material?.toLowerCase()===A);if(T.length>0)return T.map(k=>({name:k.color_name,hex:k.hex_color.replace("#","").substring(0,6),manufacturer:k.manufacturer,material:typeof k.material=="string"?k.material:void 0}));const F=A.replace(/\+$/,"");if(F!==A){const k=i.filter(D=>N(D.manufacturer)&&D.material?.toLowerCase()===F);if(k.length>0)return k.map(D=>({name:D.color_name,hex:D.hex_color.replace("#","").substring(0,6),manufacturer:D.manufacturer,material:typeof D.material=="string"?D.material:void 0}))}}if(_){const T=i.filter(F=>N(F.manufacturer)&&(!F.material||F.material.toLowerCase().startsWith(_)));if(T.length>0)return T.map(F=>({name:F.color_name,hex:F.hex_color.replace("#","").substring(0,6),manufacturer:F.manufacturer,material:typeof F.material=="string"?F.material:void 0}))}return[]},[i,t.brand,t.material,t.subtype]),y=w.useMemo(()=>{if(!c)return f;if(f.length===0)return[];const g=c.toLowerCase();return f.filter(C=>C.name.toLowerCase().includes(g)||(C.manufacturer?.toLowerCase().includes(g)??!1)||(C.material?.toLowerCase().includes(g)??!1))},[c,f]),v=f.length>0,b=w.useMemo(()=>c?CY.filter(g=>g.name.toLowerCase().includes(c.toLowerCase())):o?CY:Wle,[c,o]);return a.jsxs("div",{className:"space-y-3",children:[a.jsx("div",{className:"h-10 rounded-lg border border-bambu-dark-tertiary",style:{backgroundColor:`#${u}`}}),n.length>0&&a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-bambu-gray shrink-0",children:[a.jsx(Yn,{className:"w-3 h-3"}),a.jsx("span",{children:s("inventory.recentColors")})]}),a.jsx("div",{className:"flex flex-wrap gap-1.5",children:n.map(g=>a.jsx("button",{type:"button",onClick:()=>p(g.hex,g.name),className:`w-6 h-6 rounded border-2 transition-all hover:scale-110 ${m(g.hex)?"border-bambu-green ring-1 ring-bambu-green/30 scale-110":"border-bambu-dark-tertiary"}`,style:{backgroundColor:`#${g.hex}`},title:g.name},g.hex))})]}),a.jsxs("div",{className:"relative",children:[a.jsx(Pr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50 pointer-events-none"}),a.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:g=>d(g.target.value)})]}),v?a.jsxs("div",{className:"space-y-1.5",children:[a.jsx("span",{className:"text-xs text-bambu-gray",children:c?s("inventory.searchResults"):`${t.brand}${t.material?` ${t.material}`:""}`}),a.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[y.map(g=>a.jsx("button",{type:"button",onClick:()=>p(g.hex,g.name),className:`w-6 h-6 rounded border-2 transition-all hover:scale-110 hover:z-20 relative group ${m(g.hex)?"border-bambu-green ring-1 ring-bambu-green/30 scale-110":"border-bambu-dark-tertiary"}`,style:{backgroundColor:`#${g.hex}`},title:g.manufacturer&&g.material?`${g.name} (${g.manufacturer} — ${g.material})`:g.manufacturer?`${g.name} (${g.manufacturer})`:g.name,children:a.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:g.manufacturer&&g.material?`${g.name} (${g.manufacturer} — ${g.material})`:g.manufacturer?`${g.name} (${g.manufacturer})`:g.name})},`${g.hex}-${g.name}-${g.manufacturer??""}`)),y.length===0&&a.jsx("p",{className:"text-sm text-bambu-gray py-1",children:s("inventory.noColorsFound")})]})]}):a.jsxs("div",{className:"space-y-1.5",children:[a.jsxs("div",{className:"flex items-center justify-between text-xs text-bambu-gray",children:[a.jsx("span",{children:s(c?"inventory.searchResults":o?"inventory.allColors":"inventory.commonColors")}),!c&&a.jsx("button",{type:"button",onClick:()=>l(!o),className:"flex items-center gap-1 hover:text-white transition-colors",children:o?a.jsxs(a.Fragment,{children:[s("inventory.showLess")," ",a.jsx(dc,{className:"w-3 h-3"})]}):a.jsxs(a.Fragment,{children:[s("inventory.showAll")," ",a.jsx(On,{className:"w-3 h-3"})]})})]}),a.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[b.map(g=>a.jsx("button",{type:"button",onClick:()=>p(g.hex,g.name),className:`w-6 h-6 rounded border-2 transition-all hover:scale-110 hover:z-20 relative group ${m(g.hex)?"border-bambu-green ring-1 ring-bambu-green/30 scale-110":"border-bambu-dark-tertiary"}`,style:{backgroundColor:`#${g.hex}`},title:g.name,children:a.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:g.name})},g.hex)),b.length===0&&a.jsx("p",{className:"text-sm text-bambu-gray py-1",children:s("inventory.noColorsFound")})]})]}),a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:s("inventory.colorName")}),a.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:g=>e("color_name",g.target.value)})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:s("inventory.hexColor")}),a.jsxs("div",{className:"flex gap-2",children:[a.jsxs("div",{className:"relative flex-1",children:[a.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-bambu-gray",children:"#"}),a.jsx("input",{type:"text",className:"w-full pl-7 pr-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm font-mono uppercase focus:outline-none focus:border-bambu-green",placeholder:"RRGGBB",value:u.toUpperCase(),onChange:g=>{const _=g.target.value.replace("#","").replace(/[^0-9A-Fa-f]/g,"");_.length<=8&&e("rgba",_.toUpperCase()+(_.length<=6?"FF":""))}})]}),a.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:g=>{const _=g.target.value.replace("#","").toUpperCase();e("rgba",_+"FF")},title:s("inventory.pickColor")})]})]})]})]})}function Mrt({catalog:t,value:e,onChange:n,catalogId:r,onCatalogIdChange:i}){const{t:s}=Ft(),[o,l]=w.useState(!1),[c,d]=w.useState(""),u=w.useRef(null),m=w.useRef(null);w.useEffect(()=>{const v=b=>{u.current&&!u.current.contains(b.target)&&l(!1)};return document.addEventListener("mousedown",v),()=>document.removeEventListener("mousedown",v)},[]),w.useEffect(()=>{if(t.length===0)return;const v=t.filter(b=>b.weight===e);if(r){const b=t.find(g=>g.id===r);if(b&&b.weight===e)return}v.length===1?i(v[0].id):v.length===0&&r!==null&&i(null)},[e,t,r,i]);const p=w.useMemo(()=>{if(!c)return t;const v=c.toLowerCase();return t.filter(b=>b.name.toLowerCase().includes(v)||b.weight.toString().includes(v))},[t,c]),f=w.useMemo(()=>t.filter(v=>v.weight===e),[t,e]),y=w.useMemo(()=>{if(o)return c;if(r){const v=t.find(b=>b.id===r);if(v)return v.name}return f.length>0?f[0].name:""},[o,c,r,t,f]);return a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:a.jsxs("span",{className:"flex items-center gap-2",children:[a.jsx(BQ,{className:"w-3.5 h-3.5 text-bambu-gray"}),s("inventory.coreWeight")]})}),a.jsxs("div",{className:"flex gap-2 items-center",children:[a.jsxs("div",{className:"flex-1 min-w-0 relative",ref:u,children:[a.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:y,onFocus:()=>{l(!0),d("")},onChange:v=>{d(v.target.value),l(!0)}}),o&&a.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?a.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:s("inventory.noResults")}):p.map(v=>a.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 ${(r?v.id===r:v.weight===e)?"bg-bambu-green/10 text-bambu-green":"text-white"}`,onClick:()=>{i(v.id),n(v.weight),l(!1),d("")},children:[a.jsx("span",{className:"truncate",children:v.name}),a.jsxs("span",{className:"font-mono text-xs text-bambu-gray ml-2 shrink-0",children:[v.weight,"g"]})]},v.id))})]}),a.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[a.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:v=>{const b=parseInt(v.target.value);!isNaN(b)&&b>=0&&n(b)}}),a.jsx("span",{className:"text-bambu-gray text-sm",children:"g"})]})]})]})}function nce({formData:t,updateField:e,spoolCatalog:n,currencySymbol:r}){const{t:i}=Ft(),{showToast:s}=hn(),[o,l]=w.useState(""),[c,d]=w.useState(!1),[u,m]=w.useState(""),[p,f]=w.useState(!1),y=Math.max(0,t.label_weight-t.weight_used),v=t.core_weight+y;return w.useEffect(()=>{c||l(String(v))},[c,v]),w.useEffect(()=>{p||m(String(y))},[p,y]),a.jsxs("div",{className:"space-y-4",children:[a.jsx(Mrt,{catalog:n,value:t.core_weight,onChange:b=>e("core_weight",b),catalogId:t.core_weight_catalog_id,onCatalogIdChange:b=>e("core_weight_catalog_id",b)}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:i("inventory.currentWeight")}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs("div",{className:"relative flex-1",children:[a.jsx("input",{type:"number",value:u,min:0,max:t.label_weight,onFocus:()=>f(!0),onChange:b=>{m(b.target.value)},onBlur:()=>{f(!1);const b=u.trim(),g=Number(b);if(!b||!Number.isFinite(g)||g<0||g>t.label_weight){m(String(y));return}const _=Math.round(g);e("weight_used",Math.max(0,t.label_weight-_)),m(String(_))},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"}),a.jsx("span",{className:"absolute right-2 top-1/2 -translate-y-1/2 text-xs text-bambu-gray",children:"g"})]}),a.jsxs("span",{className:"text-xs text-bambu-gray shrink-0",children:["/ ",t.label_weight,"g"]})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:i("inventory.measuredWeight")}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs("div",{className:"relative flex-1",children:[a.jsx("input",{type:"number",value:o,min:0,onFocus:()=>d(!0),onChange:b=>{l(b.target.value)},onBlur:()=>{d(!1);const b=o.trim(),g=Number(b),_=t.core_weight,C=t.core_weight+t.label_weight;if(!b||!Number.isFinite(g)||g<_||g>C){s(i("inventory.measuredWeightError",{min:_,max:C}),"error"),l(String(v));return}const P=Math.round(g),N=Math.max(0,Math.min(t.label_weight,P-t.core_weight));e("weight_used",Math.max(0,t.label_weight-N)),l(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"}),a.jsx("span",{className:"absolute right-2 top-1/2 -translate-y-1/2 text-xs text-bambu-gray",children:"g"})]}),a.jsxs("span",{className:"text-xs text-bambu-gray shrink-0",children:["/ ",t.core_weight+t.label_weight,"g"]})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:i("inventory.costPerKg","Cost per kg")}),a.jsx("div",{className:"flex items-center gap-2",children:a.jsxs("div",{className:"relative flex-1",children:[a.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-bambu-gray text-sm pointer-events-none",children:r}),a.jsx("input",{type:"number",value:t.cost_per_kg??"",min:0,step:.01,placeholder:"0.00",onChange:b=>{const g=b.target.value===""?null:parseFloat(b.target.value);e("cost_per_kg",g)},style:{paddingLeft:`${Math.max(2,r.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"})]})})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:i("inventory.note")}),a.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:i("inventory.notePlaceholder"),value:t.note,onChange:b=>e("note",b.target.value)})]})]})}function rce({formData:t,printersWithCalibrations:e,selectedProfiles:n,setSelectedProfiles:r,expandedPrinters:i,setExpandedPrinters:s}){const{t:o}=Ft(),l=p=>{s(f=>{const y=new Set(f);return y.has(p)?y.delete(p):y.add(p),y})},c=(p,f,y)=>{const v=`${p}:${f}:${y??"null"}`,b=`${p}:${y??"null"}`;r(g=>{const _=new Set(g);if(_.has(v))_.delete(v);else{for(const C of Array.from(_)){const P=C.split(":");`${P[0]}:${P[2]}`===b&&_.delete(C)}_.add(v)}return _})},d=()=>{const p=new Set;for(const{printer:f,calibrations:y}of e){if(!f.connected)continue;const v=y.filter(g=>D3(g,t)),b=new Map;for(const g of v){const _=`${g.extruder_id??"null"}`;b.has(_)||b.set(_,[]),b.get(_).push(g)}for(const[g,_]of b)if(_.length>0){const P=[..._].sort((N,A)=>A.k_value-N.k_value)[0];p.add(`${f.id}:${P.cali_idx}:${g}`)}}r(p)};if(!t.material)return a.jsx("div",{className:"p-6 bg-bambu-dark rounded-lg text-center",children:a.jsx("p",{className:"text-bambu-gray",children:o("inventory.selectMaterialFirst")})});if(e.length===0)return a.jsx("div",{className:"p-6 bg-bambu-dark rounded-lg text-center",children:a.jsx("p",{className:"text-bambu-gray",children:o("inventory.noPrintersConfigured")})});const u=e.reduce((p,{printer:f,calibrations:y})=>f.connected?p+y.filter(v=>D3(v,t)).length:p,0),m=(p,f)=>{const y=`${p.id}:${f.cali_idx}:${f.extruder_id??"null"}`,v=n.has(y);return a.jsxs("label",{className:`flex items-center gap-3 p-3 rounded-lg cursor-pointer transition-all border ${v?"bg-bambu-green/10 border-bambu-green/30":"bg-bambu-dark border-transparent hover:bg-bambu-dark/80"}`,children:[a.jsx("input",{type:"checkbox",checked:v,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"}),a.jsx("div",{className:"flex-1 min-w-0",children:a.jsx("span",{className:`text-sm font-medium ${v?"text-bambu-green":"text-white"}`,children:f.name||f.filament_id})}),a.jsx("div",{className:"flex items-center gap-2 shrink-0",children:a.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 a.jsxs("div",{className:"space-y-4",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.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&&a.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:[a.jsx($x,{className:"w-3.5 h-3.5"}),o("inventory.autoSelect")," (",u,")"]})]}),a.jsx("div",{className:"space-y-3",children:e.map(({printer:p,calibrations:f})=>{const y=i.has(String(p.id)),v=f.filter(P=>D3(P,t)),b=v.length,g=v.some(P=>P.extruder_id!==void 0&&P.extruder_id!==null&&P.extruder_id>0),_=v.filter(P=>P.extruder_id===1),C=v.filter(P=>P.extruder_id===0||P.extruder_id===void 0||P.extruder_id===null);return a.jsxs("div",{className:"border border-bambu-dark-tertiary rounded-lg overflow-hidden",children:[a.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:[a.jsxs("div",{className:"flex items-center gap-3",children:[y?a.jsx(On,{className:"w-4 h-4 text-bambu-gray"}):a.jsx(ti,{className:"w-4 h-4 text-bambu-gray"}),a.jsx("span",{className:"font-medium text-white",children:p.name}),b>0?a.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")]}):a.jsx("span",{className:"text-xs px-2 py-0.5 rounded-full bg-bambu-dark-tertiary text-bambu-gray",children:o("inventory.noMatches")})]}),a.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")})]}),y&&a.jsx("div",{className:"px-4 py-3 space-y-3 bg-bambu-dark border-t border-bambu-dark-tertiary",children:p.connected?b===0?a.jsx("p",{className:"text-sm text-bambu-gray italic py-2",children:o("inventory.noKProfilesMatch")}):g?a.jsxs(a.Fragment,{children:[_.length>0&&a.jsxs("div",{className:"space-y-2",children:[a.jsx("p",{className:"text-xs font-medium text-bambu-gray uppercase tracking-wide",children:o("inventory.leftNozzle")}),a.jsx("div",{className:"space-y-2",children:_.map(P=>m(p,P))})]}),C.length>0&&a.jsxs("div",{className:"space-y-2",children:[a.jsx("p",{className:"text-xs font-medium text-bambu-gray uppercase tracking-wide",children:o("inventory.rightNozzle")}),a.jsx("div",{className:"space-y-2",children:C.map(P=>m(p,P))})]})]}):a.jsx("div",{className:"space-y-2",children:v.map(P=>m(p,P))}):a.jsx("p",{className:"text-sm text-bambu-gray italic py-2",children:o("inventory.printerOffline")})})]},p.id)})}),n.size>0&&a.jsx("div",{className:"p-3 bg-bambu-green/10 border border-bambu-green/30 rounded-lg",children:a.jsxs("p",{className:"text-sm text-white",children:[a.jsx("span",{className:"font-semibold",children:n.size})," ",o("inventory.profilesSelected")]})})]})}function Ert(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 Drt={completed:"text-bambu-green",failed:"text-red-400",aborted:"text-yellow-400"};function Frt({spoolId:t}){const{t:e}=Ft(),n=nn(),{showToast:r}=hn(),{data:i,isLoading:s}=Xe({queryKey:["spool-usage",t],queryFn:()=>de.getSpoolUsageHistory(t)}),o=it({mutationFn:()=>de.clearSpoolUsageHistory(t),onSuccess:()=>{n.invalidateQueries({queryKey:["spool-usage",t]}),r(e("inventory.historyCleared"),"success")}});return s?a.jsx("div",{className:"flex justify-center py-4",children:a.jsx(pt,{className:"w-5 h-5 animate-spin text-bambu-green"})}):!i||i.length===0?a.jsxs("div",{className:"text-center py-4 text-bambu-gray text-sm",children:[a.jsx(Yn,{className:"w-5 h-5 mx-auto mb-2 opacity-50"}),e("inventory.noUsageHistory")]}):a.jsxs("div",{className:"space-y-2",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("h4",{className:"text-sm font-medium text-white",children:e("inventory.usageHistory")}),a.jsxs(De,{variant:"ghost",size:"sm",onClick:()=>o.mutate(),disabled:o.isPending,className:"text-xs text-bambu-gray hover:text-red-400",children:[a.jsx(en,{className:"w-3 h-3 mr-1"}),e("inventory.clearHistory")]})]}),a.jsx("div",{className:"max-h-48 overflow-y-auto space-y-1",children:i.map(l=>a.jsxs("div",{className:"flex items-center justify-between p-2 rounded bg-bambu-dark/50 text-xs",children:[a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("span",{className:"text-bambu-gray",children:Ert(l.created_at)}),l.print_name&&a.jsx("span",{className:"text-white ml-2 truncate",title:l.print_name,children:l.print_name})]}),a.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0 ml-2",children:[a.jsxs("span",{className:"text-white font-medium",children:[l.weight_used.toFixed(1),"g"]}),a.jsxs("span",{className:"text-bambu-gray",children:["(",l.percent_used,"%)"]}),a.jsx("span",{className:Drt[l.status]||"text-bambu-gray",children:l.status})]})]},l.id))})]})}function Rrt({isOpen:t,onClose:e,spool:n,printersWithCalibrations:r=[],currencySymbol:i,onSpoolsCreated:s}){const{t:o}=Ft(),l=nn(),{showToast:c}=hn(),d=!!n,[u,m]=w.useState(dO),[p,f]=w.useState({}),[y,v]=w.useState("filament"),[b,g]=w.useState(!1),[_,C]=w.useState(!1),[P,N]=w.useState(1),[A,T]=w.useState(!1),[F,k]=w.useState(!1),[D,H]=w.useState([]),[z,Q]=w.useState(""),[L,te]=w.useState([]),[ie,J]=w.useState([]),[oe,fe]=w.useState([]),[re,W]=w.useState([]),[ne,me]=w.useState([]),[be,Ce]=w.useState(new Set),[q,Y]=w.useState(new Set),E=r.length>0?r:ne,j=w.useMemo(()=>be.size,[be]);w.useEffect(()=>{W(Zle())},[]),w.useEffect(()=>{t&&((async()=>{k(!0);try{const Le=await de.getCloudStatus();if(T(Le.is_authenticated),Le.is_authenticated){const Me=await de.getFilamentPresets();H(Me)}}catch(Le){console.error("Failed to fetch cloud presets:",Le),T(!1)}finally{k(!1)}})(),de.getSpoolCatalog().then(te).catch(console.error),de.getColorCatalog().then(fe).catch(console.error),de.getLocalPresets().then(Le=>J(Le.filament)).catch(console.error),r.length===0&&(async()=>{try{const Le=await de.getPrinters(),Me=await Promise.all(Le.map(Re=>de.getPrinterStatus(Re.id).catch(()=>null))),Oe=[];for(let Re=0;Re({cali_idx:we.slot_id,filament_id:we.filament_id,setting_id:we.setting_id||"",name:we.name,k_value:parseFloat(we.k_value)||0,n_coef:parseFloat(we.n_coef)||0,extruder_id:we.extruder_id,nozzle_diameter:we.nozzle_diameter}))}catch{}Oe.push({printer:{...$e,connected:tt},calibrations:pe})}me(Oe)}catch(Le){console.error("Failed to fetch printer calibrations:",Le)}})())},[t,r.length]);const O=w.useMemo(()=>Yle(D,new Set,ie),[D,ie]),K=w.useMemo(()=>{const Ae=Xle(D,ie),Le=oe.map(Oe=>Oe.manufacturer?.trim()).filter(Oe=>!!Oe),Me=new Set([...Ae,...Le]);return Array.from(Me).sort((Oe,Re)=>Oe.localeCompare(Re))},[D,ie,oe]),U=w.useMemo(()=>{const Ae=oe.map(Me=>Me.material?.trim()).filter(Me=>!!Me),Le=new Set([...Gle,...Ae]);return Array.from(Le).sort((Me,Oe)=>Me.localeCompare(Oe))},[oe]),ue=w.useMemo(()=>{const Ae=[];for(const Le of oe){const Me=Le.manufacturer?.trim(),Oe=Le.material?.trim();Me&&Oe&&Ae.push({brand:Me,material:Oe})}for(const Le of D){const Me=Cp(Le.name);Me.brand&&Me.material&&Ae.push({brand:Me.brand,material:Me.material})}for(const Le of ie){const Me=Cp(Le.name),Oe=Le.filament_vendor?.trim()||Me.brand,Re=Me.material;Oe&&Re&&Ae.push({brand:Oe,material:Re})}return Ae},[D,oe,ie]),I=w.useMemo(()=>{const Ae=new Map;for(const Le of ue){const Me=Le.brand.toLowerCase(),Oe=Le.material.toLowerCase();Ae.has(Me)||Ae.set(Me,new Set),Ae.get(Me).add(Oe)}return Ae},[ue]),G=w.useMemo(()=>{const Ae=new Map;for(const Le of ue){const Me=Le.brand.toLowerCase(),Oe=Le.material.toLowerCase();Ae.has(Oe)||Ae.set(Oe,new Set),Ae.get(Oe).add(Me)}return Ae},[ue]),X=w.useMemo(()=>{if(!u.material)return K;const Ae=u.material.toLowerCase(),Le=G.get(Ae);return!Le||Le.size===0?K:K.filter(Me=>Le.has(Me.toLowerCase()))},[K,u.material,G]),V=w.useMemo(()=>{if(!u.brand)return U;const Ae=u.brand.toLowerCase(),Le=I.get(Ae);return!Le||Le.size===0?U:U.filter(Me=>Le.has(Me.toLowerCase()))},[U,u.brand,I]),ee=w.useMemo(()=>Qle(u.slicer_filament,O),[u.slicer_filament,O]);w.useEffect(()=>{if(t){if(n)if(m({material:n.material||"",subtype:n.subtype||"",brand:n.brand||"",color_name:n.color_name||"",rgba:n.rgba||"808080FF",label_weight:n.label_weight||1e3,core_weight:n.core_weight||250,core_weight_catalog_id:n.core_weight_catalog_id??null,weight_used:n.weight_used||0,slicer_filament:n.slicer_filament||"",note:n.note||"",cost_per_kg:n.cost_per_kg??null}),Q(n.slicer_filament_name||n.slicer_filament||""),n.k_profiles&&n.k_profiles.length>0){const Ae=new Set;for(const Le of n.k_profiles)Le.cali_idx!==null&&Le.cali_idx!==void 0&&Ae.add(`${Le.printer_id}:${Le.cali_idx}:${Le.extruder??"null"}`);Ce(Ae)}else Ce(new Set);else m(dO),Q(""),Ce(new Set),C(!1),N(1);f({}),v("filament"),g(!1)}},[t,n]),w.useEffect(()=>{t&&E.length>0&&Y(new Set(E.map(Ae=>String(Ae.printer.id))))},[t,E]);const se=(Ae,Le)=>{m(Me=>({...Me,[Ae]:Le})),Ae==="weight_used"&&g(!0),p[Ae]&&f(Me=>({...Me,[Ae]:void 0}))},ge=Ae=>{W(Le=>Jle(Ae,Le))},he=it({mutationFn:Ae=>de.createSpool(Ae),onSuccess:async Ae=>{be.size>0&&Ae?.id&&await ve(Ae.id),await l.invalidateQueries({queryKey:["inventory-spools"]}),s&&s([Ae]),c(o("inventory.spoolCreated"),"success"),e()},onError:Ae=>{c(Ae.message,"error")}}),le=it({mutationFn:({data:Ae,qty:Le})=>de.bulkCreateSpools(Ae,Le),onSuccess:async Ae=>{if(be.size>0)for(const Le of Ae)await ve(Le.id);await l.invalidateQueries({queryKey:["inventory-spools"]}),s&&s(Ae),c(o("inventory.spoolsCreated",{count:Ae.length}),"success"),e()},onError:Ae=>{c(Ae.message,"error")}}),B=it({mutationFn:Ae=>de.updateSpool(n.id,Ae),onSuccess:async()=>{n?.id&&await ve(n.id),await l.invalidateQueries({queryKey:["inventory-spools"]}),c(o("inventory.spoolUpdated"),"success"),e()},onError:Ae=>{c(Ae.message,"error")}}),R=it({mutationFn:()=>de.updateSpool(n.id,{tag_uid:null,tray_uuid:null,tag_type:null,data_origin:null}),onSuccess:async()=>{await l.invalidateQueries({queryKey:["inventory-spools"]}),c(o("inventory.tagDeleted","Tag removed"),"success"),e()},onError:Ae=>{c(Ae.message,"error")}}),{data:ae}=Xe({queryKey:["spool-assignments"],queryFn:()=>de.getAssignments(),enabled:t&&d}),_e=n?ae?.find(Ae=>Ae.spool_id===n.id):void 0,Se=it({mutationFn:()=>{if(!_e)throw new Error("No assignment");return de.unassignSpool(_e.printer_id,_e.ams_id,_e.tray_id)},onSuccess:async()=>{await l.invalidateQueries({queryKey:["spool-assignments"]}),c(o("inventory.unassignSuccess","Spool unassigned"),"success"),e()},onError:Ae=>{c(Ae.message,"error")}}),ve=async Ae=>{if(be.size===0){try{await de.saveSpoolKProfiles(Ae,[])}catch{}return}const Le=[];for(const Me of be){const[Oe,Re,$e]=Me.split(":"),Ye=parseInt(Oe),tt=parseInt(Re),pe=$e==="null"?0:parseInt($e),Fe=E.find(we=>we.printer.id===Ye);if(Fe){const we=Fe.calibrations.find(Ve=>Ve.cali_idx===tt);we&&Le.push({printer_id:Ye,extruder:pe,nozzle_diameter:we.nozzle_diameter||"0.4",k_value:we.k_value,name:we.name||null,cali_idx:we.cali_idx,setting_id:we.setting_id||null})}}if(Le.length>0)try{await de.saveSpoolKProfiles(Ae,Le)}catch(Me){console.error("Failed to save K-profiles:",Me)}};if(w.useEffect(()=>{if(!t)return;const Ae=Le=>{Le.key==="Escape"&&e()};return document.addEventListener("keydown",Ae),()=>document.removeEventListener("keydown",Ae)},[t,e]),!t)return null;const Te=()=>{const Ae=Vle(u,_);if(!Ae.isValid){f(Ae.errors),(Ae.errors.slicer_filament||Ae.errors.material||Ae.errors.brand||Ae.errors.subtype)&&v("filament");return}const Le=ee?.displayName||z||null,Me={material:u.material,subtype:u.subtype||null,brand:u.brand||null,color_name:u.color_name||null,rgba:u.rgba||null,label_weight:u.label_weight,core_weight:u.core_weight,core_weight_catalog_id:u.core_weight_catalog_id,slicer_filament:u.slicer_filament||null,slicer_filament_name:Le,nozzle_temp_min:null,nozzle_temp_max:null,note:u.note||null,cost_per_kg:u.cost_per_kg};(!d||b)&&(Me.weight_used=u.weight_used),d?B.mutate(Me):P>1?le.mutate({data:Me,qty:P}):he.mutate(Me)},ye=he.isPending||le.isPending||B.isPending||R.isPending||Se.isPending;return a.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[a.jsx("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-sm",onClick:e}),a.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:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary flex-shrink-0",children:[a.jsx("h2",{className:"text-lg font-semibold text-white",children:o(d?"inventory.editSpool":"inventory.addSpool")}),a.jsx("button",{onClick:e,className:"p-1 text-bambu-gray hover:text-white rounded transition-colors",children:a.jsx(Ht,{className:"w-5 h-5"})})]}),!d&&a.jsxs("div",{className:"flex items-center justify-between px-4 py-2 border-b border-bambu-dark-tertiary flex-shrink-0",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(uc,{className:"w-4 h-4 text-amber-400"}),a.jsx("span",{className:"text-sm text-white",children:o("inventory.quickAdd")})]}),a.jsx("button",{type:"button",onClick:()=>{C(!_),_||v("filament")},className:`relative inline-flex h-5 w-9 items-center rounded-full transition-colors ${_?"bg-bambu-green":"bg-bambu-dark-tertiary"}`,children:a.jsx("span",{className:`inline-block h-3.5 w-3.5 rounded-full bg-white transition-transform ${_?"translate-x-4":"translate-x-0.5"}`})})]}),a.jsxs("div",{className:"flex border-b border-bambu-dark-tertiary flex-shrink-0",children:[a.jsxs("button",{onClick:()=>v("filament"),className:`flex-1 px-4 py-2.5 text-sm font-medium flex items-center justify-center gap-2 transition-colors ${y==="filament"?"text-bambu-green border-b-2 border-bambu-green":"text-bambu-gray hover:text-white"}`,children:[a.jsx(nS,{className:"w-4 h-4"}),o("inventory.filamentInfoTab")]}),!_&&a.jsxs("button",{onClick:()=>v("pa-profile"),className:`flex-1 px-4 py-2.5 text-sm font-medium flex items-center justify-center gap-2 transition-colors ${y==="pa-profile"?"text-bambu-green border-b-2 border-bambu-green":"text-bambu-gray hover:text-white"}`,children:[a.jsx(Npe,{className:"w-4 h-4"}),o("inventory.paProfileTab"),j>0&&a.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded-full bg-bambu-green/20 text-bambu-green",children:j})]})]}),a.jsx("div",{className:"p-4 overflow-y-auto flex-1",style:{scrollbarGutter:"stable"},children:y==="filament"?a.jsxs("div",{className:"space-y-6",children:[a.jsxs("div",{children:[a.jsx("h3",{className:"text-sm font-semibold text-bambu-gray uppercase tracking-wide mb-3",children:o("inventory.filamentInfo")}),a.jsx(ece,{formData:u,updateField:se,cloudAuthenticated:A,loadingCloudPresets:F,presetInputValue:z,setPresetInputValue:Q,selectedPresetOption:ee,filamentOptions:O,availableBrands:X,availableMaterials:V,quickAdd:_,quantity:P,onQuantityChange:N,errors:p})]}),a.jsxs("div",{children:[a.jsx("h3",{className:"text-sm font-semibold text-bambu-gray uppercase tracking-wide mb-3",children:o("inventory.color")}),a.jsx(tce,{formData:u,updateField:se,recentColors:re,onColorUsed:ge,catalogColors:oe})]}),a.jsxs("div",{children:[a.jsx("h3",{className:"text-sm font-semibold text-bambu-gray uppercase tracking-wide mb-3",children:o("inventory.additional")}),a.jsx(nce,{formData:u,updateField:se,spoolCatalog:L,currencySymbol:i})]}),d&&n&&a.jsx("div",{children:a.jsx(Frt,{spoolId:n.id})})]}):a.jsx(rce,{formData:u,updateField:se,printersWithCalibrations:E,selectedProfiles:be,setSelectedProfiles:Ce,expandedPrinters:q,setExpandedPrinters:Y})}),a.jsxs("div",{className:"flex gap-2 p-4 border-t border-bambu-dark-tertiary flex-shrink-0",children:[d&&a.jsxs("div",{className:"flex gap-2 mr-auto",children:[a.jsxs(De,{variant:"secondary",onClick:()=>R.mutate(),disabled:ye||!n?.tag_uid,children:[a.jsx(xm,{className:"w-4 h-4"}),o("inventory.deleteTag","Delete Tag")]}),a.jsxs(De,{variant:"secondary",onClick:()=>Se.mutate(),disabled:ye||!_e,children:[a.jsx(gp,{className:"w-4 h-4"}),o("inventory.unassignSpool","Unassign")]})]}),a.jsxs("div",{className:"flex gap-2 ml-auto",children:[a.jsx(De,{variant:"secondary",onClick:e,children:o("common.cancel")}),a.jsx(De,{onClick:Te,disabled:ye,children:ye?a.jsxs(a.Fragment,{children:[a.jsx(pt,{className:"w-4 h-4 animate-spin"}),o("common.saving")]}):a.jsxs(a.Fragment,{children:[a.jsx(_s,{className:"w-4 h-4"}),o(d?"common.save":"inventory.addSpool")]})})]})]})]})]})}function Lrt({isOpen:t,onClose:e,columns:n,defaultColumns:r,onSave:i}){const{t:s}=Ft(),[o,l]=w.useState(n),[c,d]=w.useState(null),u=w.useRef(null);if(w.useEffect(()=>{t&&l(n.map(P=>({...P})))},[t,n]),w.useEffect(()=>{if(!t)return;const P=N=>{N.key==="Escape"&&e()};return window.addEventListener("keydown",P),()=>window.removeEventListener("keydown",P)},[t,e]),!t)return null;const m=P=>{l(N=>N.map((A,T)=>T===P?{...A,visible:!A.visible}:A))},p=(P,N)=>{N<0||N>=o.length||l(A=>{const T=[...A],[F]=T.splice(P,1);return T.splice(N,0,F),T})},f=(P,N)=>{u.current=N,d(N),P.dataTransfer.effectAllowed="move"},y=(P,N)=>{P.preventDefault(),P.dataTransfer.dropEffect="move";const A=u.current;A!==null&&A!==N&&(p(A,N),u.current=N,d(N))},v=P=>{P.preventDefault()},b=()=>{u.current=null,d(null)},g=()=>{l(r.map(P=>({...P})))},_=()=>{i(o),e()},C=o.filter(P=>P.visible).length;return a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",onClick:e,children:a.jsx(Tt,{className:"w-full max-w-md max-h-[80vh] flex flex-col",onClick:P=>P.stopPropagation(),children:a.jsxs(Mt,{className:"p-6 flex flex-col min-h-0",children:[a.jsx("h3",{className:"text-lg font-semibold text-white mb-2",children:s("inventory.configureColumns")}),a.jsxs("p",{className:"text-sm text-bambu-gray mb-4",children:[s("inventory.configureColumnsDesc"),a.jsxs("span",{className:"ml-2 text-bambu-gray/60",children:["(",C," ",s("inventory.of")," ",o.length," ",s("inventory.visible"),")"]})]}),a.jsx("div",{className:"space-y-1 overflow-y-auto flex-1 min-h-0 pr-1",children:o.map((P,N)=>a.jsxs("div",{className:`flex items-center gap-2 p-2 rounded-lg border transition-colors ${c===N?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary bg-bambu-dark-tertiary/50"} ${P.visible?"":"opacity-50"}`,draggable:!0,onDragStart:A=>f(A,N),onDragOver:A=>y(A,N),onDrop:v,onDragEnd:b,children:[a.jsx("div",{className:"cursor-grab text-bambu-gray/50 hover:text-bambu-gray",children:a.jsx(np,{className:"w-4 h-4"})}),a.jsx("span",{className:"flex-1 font-medium text-sm text-white",children:P.label}),a.jsxs("div",{className:"flex items-center gap-0.5",children:[a.jsx("button",{onClick:()=>p(N,N-1),disabled:N===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:a.jsx(dc,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>p(N,N+1),disabled:N===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:a.jsx(On,{className:"w-4 h-4"})})]}),a.jsx("button",{onClick:()=>m(N),className:`p-1.5 rounded transition-colors ${P.visible?"text-bambu-green hover:bg-bambu-green/10":"text-bambu-gray/50 hover:bg-bambu-dark-secondary"}`,title:P.visible?s("inventory.hideColumn"):s("inventory.showColumn"),children:P.visible?a.jsx(vl,{className:"w-4 h-4"}):a.jsx(Og,{className:"w-4 h-4"})})]},P.id))}),a.jsxs("div",{className:"flex items-center gap-3 mt-4 pt-4 border-t border-bambu-dark-tertiary",children:[a.jsxs(De,{variant:"secondary",onClick:g,className:"mr-auto",children:[a.jsx(co,{className:"w-4 h-4"}),s("inventory.reset")]}),a.jsx(De,{variant:"secondary",onClick:e,children:s("inventory.cancel")}),a.jsx(De,{onClick:_,children:s("inventory.applyChanges")})]})]})})})}function PY(t){return`${t.material}|${t.subtype||""}|${t.brand||""}|${t.color_name||""}|${t.rgba||""}|${t.label_weight}`}const ace="bambuddy-inventory-columns",uN=[{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:"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 Ort(){try{const t=localStorage.getItem(ace);if(t){const e=JSON.parse(t),n=new Set(uN.map(o=>o.id)),r=new Set(e.map(o=>o.id)),i=e.filter(o=>n.has(o.id)),s=uN.filter(o=>!r.has(o.id));return[...i,...s]}}catch{}return uN.map(t=>({...t}))}function Irt(t){try{localStorage.setItem(ace,JSON.stringify(t))}catch{}}function Rd(t,e=!1){return e&&t>=1e3?`${(t/1e3).toFixed(1)}kg`:`${Math.round(t)}g`}const zrt={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 F3(t,e="system"){if(!t)return"-";const n=Zn(t);return n?mF(n,e):"-"}const Urt={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",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")},uO={id:({spool:t})=>a.jsx("span",{className:"text-sm font-medium text-white",children:t.id}),added_time:({spool:t,dateFormat:e})=>a.jsx("span",{className:"text-sm text-bambu-gray",children:F3(t.created_at,e)}),encode_time:({spool:t,dateFormat:e})=>a.jsx("span",{className:"text-sm text-bambu-gray",children:F3(t.encode_time,e)}),last_used_time:({spool:t,dateFormat:e})=>a.jsx("span",{className:"text-sm text-bambu-gray",children:t.last_used?F3(t.last_used,e):"Never"}),rgba:({spool:t})=>a.jsx("div",{className:"flex items-center justify-center",children:a.jsx("span",{className:"w-5 h-5 rounded-full border border-black/20 flex-shrink-0",style:{backgroundColor:t.rgba?`#${t.rgba.substring(0,6)}`:"#808080"},title:t.rgba?`#${t.rgba.substring(0,6)}`:void 0})}),material:({spool:t})=>a.jsx("span",{className:"text-sm text-white",children:t.material}),subtype:({spool:t})=>a.jsx("span",{className:"text-sm text-bambu-gray",children:t.subtype||"-"}),color_name:({spool:t})=>a.jsx("span",{className:"text-sm text-bambu-gray",children:XP(t.color_name,t.rgba)||"-"}),brand:({spool:t})=>a.jsx("span",{className:"text-sm text-bambu-gray",children:t.brand||"-"}),slicer_filament:({spool:t})=>a.jsx("span",{className:"text-sm text-bambu-gray",title:t.slicer_filament||void 0,children:t.slicer_filament_name||t.slicer_filament||"-"}),location:({spool:t,assignmentMap:e})=>{const n=e[t.id];if(!n)return a.jsx("span",{className:"text-sm text-bambu-gray",children:"-"});const r=n.printer_name||`Printer ${n.printer_id}`,i=n.ams_id===254||n.ams_id===255,s=!i&&n.ams_id>=128,o=RS(n.ams_id,n.tray_id,s,i);return a.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:[r," ",o,n.ams_label?` (${n.ams_label})`:""]})},label_weight:({spool:t})=>a.jsx("span",{className:"text-sm text-white",children:Rd(t.label_weight)}),net:({remaining:t})=>a.jsx("span",{className:"text-sm text-white",children:Rd(t)}),gross:({spool:t,remaining:e})=>a.jsx("span",{className:"text-sm text-bambu-gray",children:Rd(e+t.core_weight)}),added_full:({spool:t})=>a.jsx("span",{className:"text-sm text-bambu-gray",children:t.added_full==null?"-":t.added_full?"Yes":"No"}),used:({spool:t})=>a.jsx("span",{className:"text-sm text-bambu-gray",children:t.weight_used>0?Rd(t.weight_used):"-"}),printed_total:()=>a.jsx("span",{className:"text-sm text-bambu-gray/50",children:"-"}),printed_since_weight:()=>a.jsx("span",{className:"text-sm text-bambu-gray/50",children:"-"}),note:({spool:t})=>a.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?a.jsx("span",{className:"text-sm text-bambu-gray",children:"-"}):a.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?a.jsx("span",{className:"text-sm text-bambu-gray font-mono",title:e,children:e.length>12?`${e.slice(0,6)}...${e.slice(-4)}`:e}):a.jsx("span",{className:"text-sm text-bambu-gray/50",children:"-"})},data_origin:({spool:t})=>a.jsx("span",{className:"text-sm text-bambu-gray",children:t.data_origin||"-"}),tag_type:({spool:t})=>a.jsx("span",{className:"text-sm text-bambu-gray",children:t.tag_type||"-"}),stock:({spool:t,t:e})=>t.slicer_filament?a.jsx("span",{className:"text-sm text-bambu-gray",children:"-"}):a.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})=>a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("div",{className:"flex-1 h-2 bg-bambu-dark-tertiary rounded-full overflow-hidden",children:a.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)}%`}})}),a.jsxs("span",{className:"text-xs text-bambu-gray min-w-[40px] text-right",children:[Math.round(t),"g"]})]}),spool_name:({spool:t,catalogMap:e})=>{const n=t.core_weight_catalog_id!=null?e[t.core_weight_catalog_id]:void 0;return a.jsx("span",{className:"text-sm text-bambu-gray",children:n?.name||"-"})},cost_per_kg:({spool:t,currencySymbol:e})=>a.jsx("span",{className:"text-sm text-bambu-gray",children:t.cost_per_kg!=null?`${e}${t.cost_per_kg.toFixed(2)}`:"-"}),weight_check:({spool:t,onSyncWeight:e})=>{const n=t.last_scale_weight;if(n==null)return a.jsx("span",{className:"text-sm text-bambu-gray/50",title:"No scale measurement",children:"-"});const r=t.core_weight||0,i=Math.max(0,t.label_weight-t.weight_used)+r;let s,o;n0?`+${Math.round(s)}`:`${Math.round(s)}`,c=o?`Scale: ${Math.round(n)}g +`+n+"}"}return String(t)}function $nt({setting:t,onClose:e,onDeleted:n,onDuplicate:r,onEdit:i,hasPermission:s,t:o}){const{showToast:l}=hn(),c=nn(),[d,u]=w.useState(!1),{data:m,isLoading:p}=Xe({queryKey:["cloudSettingDetail",t.setting_id],queryFn:()=>de.getCloudSettingDetail(t.setting_id)}),f=it({mutationFn:()=>de.deleteCloudSetting(t.setting_id),onSuccess:()=>{l(o("profiles.presets.toast.deleted")),c.invalidateQueries({queryKey:["cloudSettings"]}),n()},onError:b=>l(b.message,"error")}),y=Kw(t.setting_id),v=b5(t.name,m?.setting?.inherits);return a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:a.jsx(Tt,{className:"w-full max-w-3xl max-h-[90vh] flex flex-col overflow-hidden",children:a.jsxs(Mt,{className:"p-0 flex flex-col min-h-0 flex-1",children:[a.jsxs("div",{className:"flex-shrink-0 flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("h2",{className:"text-xl font-semibold text-white truncate",children:t.name}),y&&a.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")})]}),a.jsxs("div",{className:"flex items-center gap-2 mt-1 text-sm text-bambu-gray",children:[a.jsx("span",{className:"capitalize",children:o(`profiles.presets.types.${t.type}`)}),v.printer&&a.jsxs(a.Fragment,{children:[a.jsx("span",{children:"•"}),a.jsx("span",{children:v.printer})]})]})]}),a.jsx("button",{onClick:e,className:"p-2 text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary rounded-lg transition-colors",children:a.jsx(Ht,{className:"w-5 h-5"})})]}),a.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto p-4",children:p?a.jsx("div",{className:"flex items-center justify-center py-16",children:a.jsx(pt,{className:"w-8 h-8 text-bambu-green animate-spin"})}):m?a.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:lO(m)}):a.jsx("div",{className:"text-center py-16 text-bambu-gray",children:o("profiles.presets.failedToLoadDetails")})}),d?a.jsxs("div",{className:"flex-shrink-0 p-4 border-t border-bambu-dark-tertiary bg-red-500/5",children:[a.jsxs("div",{className:"flex items-center gap-2 mb-3 text-red-400",children:[a.jsx(Dn,{className:"w-5 h-5"}),a.jsx("span",{className:"font-medium",children:o("profiles.presets.deleteConfirm")})]}),a.jsx("p",{className:"text-sm text-bambu-gray mb-4",children:o("profiles.presets.deleteWarning",{name:t.name})}),a.jsxs("div",{className:"flex gap-2",children:[a.jsx(De,{variant:"secondary",onClick:()=>u(!1),disabled:f.isPending,className:"flex-1",children:o("common.cancel")}),a.jsxs(De,{variant:"danger",onClick:()=>f.mutate(),disabled:f.isPending,className:"flex-1",children:[f.isPending?a.jsx(pt,{className:"w-4 h-4 animate-spin"}):a.jsx(en,{className:"w-4 h-4"}),o("common.delete")]})]})]}):a.jsx("div",{className:"flex-shrink-0 p-4 border-t border-bambu-dark-tertiary",children:a.jsxs("div",{className:"flex gap-2",children:[a.jsx(De,{variant:"secondary",onClick:e,className:"flex-1",children:o("common.close")}),a.jsxs(De,{variant:"secondary",onClick:r,disabled:!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.presets.noDuplicatePermission"),children:[a.jsx(qs,{className:"w-4 h-4"}),o("profiles.presets.duplicate")]}),y&&a.jsxs(a.Fragment,{children:[a.jsxs(De,{variant:"secondary",onClick:i,disabled:p||!m||!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.presets.noEditPermission"),children:[a.jsx(ci,{className:"w-4 h-4"}),o("common.edit")]}),a.jsx(De,{variant:"danger",onClick:()=>u(!0),disabled:!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.presets.noDeletePermission"),children:a.jsx(en,{className:"w-4 h-4"})})]})]})})]})})})}function zle(){try{const t=localStorage.getItem("bambusy_preset_templates");return t?JSON.parse(t):[]}catch{return[]}}function Ule(t){localStorage.setItem("bambusy_preset_templates",JSON.stringify(t))}function Vnt({onClose:t,onApply:e,t:n}){const{showToast:r}=hn(),[i,s]=w.useState(zle),[o,l]=w.useState("all"),[c,d]=w.useState(null),[u,m]=w.useState(""),[p,f]=w.useState(""),[y,v]=w.useState("{}"),[b,g]=w.useState(null),[_,C]=w.useState(null),P=o==="all"?i:i.filter(Q=>Q.type===o),N=Q=>{s(Q),Ule(Q)},A=Q=>{const L=i.filter(te=>te.id!==Q);N(L),C(null),r(n("profiles.templates.toast.deleted"))},T=Q=>{d(Q.id),m(Q.name),f(Q.description),v(JSON.stringify(Q.settings,null,2)),g(null)},F=()=>{if(!(!c||!u.trim()))try{const Q=JSON.parse(y),L=i.map(te=>te.id===c?{...te,name:u.trim(),description:p.trim(),settings:Q}:te);N(L),d(null),r(n("profiles.templates.toast.updated"))}catch(Q){g(Q.message)}},k=()=>{d(null),m(""),f(""),v("{}"),g(null)},D=Q=>{const L=i.map(te=>te.id===Q?{...te,showInModal:!te.showInModal}:te);N(L)},H={filament:{label:n("profiles.presets.types.filament"),icon:qP,color:"text-amber-400"},print:{label:n("profiles.presets.types.process"),icon:Ud,color:"text-blue-400"},printer:{label:n("profiles.presets.types.printer"),icon:Er,color:"text-purple-400"}},z=_?i.find(Q=>Q.id===_):null;return w.useEffect(()=>{const Q=L=>{L.key==="Escape"&&(_?C(null):c?k():t())};return window.addEventListener("keydown",Q),()=>window.removeEventListener("keydown",Q)},[_,c,t]),a.jsxs("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:[z&&a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-60",children:a.jsx(Tt,{className:"w-full max-w-md",children:a.jsxs(Mt,{className:"p-6",children:[a.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[a.jsx("div",{className:"p-2 bg-red-500/20 rounded-lg",children:a.jsx(Dn,{className:"w-6 h-6 text-red-400"})}),a.jsxs("div",{children:[a.jsx("h3",{className:"text-lg font-semibold text-white",children:n("profiles.templates.deleteTitle")}),a.jsx("p",{className:"text-sm text-bambu-gray",children:n("profiles.templates.deleteWarning")})]})]}),a.jsx("p",{className:"text-white mb-6",children:n("profiles.templates.deleteConfirm",{name:z.name})}),a.jsxs("div",{className:"flex gap-2",children:[a.jsx(De,{variant:"secondary",onClick:()=>C(null),className:"flex-1",children:n("common.cancel")}),a.jsxs(De,{onClick:()=>A(_),className:"flex-1 bg-red-500 hover:bg-red-600",children:[a.jsx(en,{className:"w-4 h-4"}),n("common.delete")]})]})]})})}),a.jsx(Tt,{className:"w-full max-w-2xl max-h-[80vh] flex flex-col",children:a.jsxs(Mt,{className:"p-0 flex flex-col h-full",children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx($x,{className:"w-5 h-5 text-amber-400"}),n("profiles.templates.title")]}),a.jsx("button",{onClick:t,className:"text-bambu-gray hover:text-white",children:a.jsx(Ht,{className:"w-5 h-5"})})]}),a.jsxs("div",{className:"flex items-center gap-2 p-4 border-b border-bambu-dark-tertiary",children:[a.jsx("span",{className:"text-sm text-bambu-gray",children:n("profiles.templates.typeFilter")}),["all","filament","print","printer"].map(Q=>a.jsx("button",{onClick:()=>l(Q),className:`px-3 py-1 text-sm rounded-lg transition-colors ${o===Q?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:Q==="all"?n("common.all"):H[Q].label},Q))]}),a.jsx("div",{className:"flex-1 overflow-y-auto p-4",children:P.length===0?a.jsxs("div",{className:"text-center py-12 text-bambu-gray",children:[a.jsx($x,{className:"w-12 h-12 mx-auto mb-4 opacity-30"}),a.jsx("p",{children:n("profiles.templates.noTemplates")}),a.jsx("p",{className:"text-sm mt-1",children:n("profiles.templates.createFirst")})]}):a.jsx("div",{className:"space-y-2",children:P.map(Q=>{const L=H[Q.type],te=L.icon;return c===Q.id?a.jsxs("div",{className:"p-4 bg-bambu-dark rounded-lg border border-bambu-green",children:[a.jsxs("div",{className:"grid grid-cols-2 gap-3 mb-3",children:[a.jsx("input",{type:"text",value:u,onChange:ie=>m(ie.target.value),placeholder:n("profiles.templates.namePlaceholder"),className:"px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none",autoFocus:!0}),a.jsx("input",{type:"text",value:p,onChange:ie=>f(ie.target.value),placeholder:n("profiles.templates.descriptionPlaceholder"),className:"px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none"})]}),a.jsxs("div",{className:"mb-3",children:[a.jsx("label",{className:"text-xs text-bambu-gray mb-1 block",children:n("profiles.templates.settingsJson")}),a.jsx("textarea",{value:y,onChange:ie=>{v(ie.target.value),g(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&&a.jsx("p",{className:"text-xs text-red-400 mt-1",children:b})]}),a.jsxs("div",{className:"flex gap-2",children:[a.jsxs(De,{size:"sm",onClick:F,disabled:!u.trim(),children:[a.jsx(_s,{className:"w-4 h-4"}),"Save"]}),a.jsx(De,{size:"sm",variant:"secondary",onClick:k,children:"Cancel"})]})]},Q.id):a.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:[a.jsx(te,{className:`w-5 h-5 ${L.color} flex-shrink-0`}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("p",{className:"text-sm font-medium text-white",children:Q.name}),a.jsx("p",{className:"text-xs text-bambu-gray truncate",children:Q.description})]}),a.jsx("span",{className:"text-xs text-bambu-gray-dark px-2 py-1 bg-bambu-dark-secondary rounded",children:n("profiles.templates.fieldsCount",{count:Object.keys(Q.settings).length})}),a.jsx("button",{onClick:()=>D(Q.id),className:`p-1 transition-colors ${Q.showInModal?"text-bambu-green hover:text-bambu-green/70":"text-bambu-gray hover:text-white"}`,title:Q.showInModal?n("profiles.templates.shownInModals"):n("profiles.templates.hiddenInModals"),children:Q.showInModal?a.jsx(vl,{className:"w-4 h-4"}):a.jsx(Og,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>e(Q),className:"px-3 py-1 text-xs bg-bambu-green/20 text-bambu-green rounded hover:bg-bambu-green/30 transition-colors",children:n("profiles.templates.apply")}),a.jsx("button",{onClick:()=>T(Q),className:"p-1 text-bambu-gray hover:text-white",title:n("common.edit"),children:a.jsx(ci,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>C(Q.id),className:"p-1 text-bambu-gray hover:text-red-400",title:n("common.delete"),children:a.jsx(en,{className:"w-4 h-4"})})]},Q.id)})})})]})})]})}function Ble({onClose:t,leftPreset:e,rightPreset:n,leftLabel:r,rightLabel:i,t:s}){const[o,l]=w.useState("changes"),[c,d]=w.useState(""),u=w.useMemo(()=>{const y=new Set([...Object.keys(e),...Object.keys(n)]),v=[];for(const b of y){if(b==="inherits"||b==="version")continue;const g=e[b],_=n[b],C=b in e,P=b in n;let N;!C&&P?N="added":C&&!P?N="removed":JSON.stringify(g)!==JSON.stringify(_)?N="changed":N="same",v.push({key:b,left:g,right:_,status:N})}return v.sort((b,g)=>{const _={changed:0,added:1,removed:2,same:3};return _[b.status]!==_[g.status]?_[b.status]-_[g.status]:b.key.localeCompare(g.key)})},[e,n]),m=w.useMemo(()=>{let y=[...u];if(o==="changes"&&(y=y.filter(v=>v.status!=="same")),c){const v=c.toLowerCase();y=y.filter(b=>b.key.toLowerCase().includes(v)||String(b.left).toLowerCase().includes(v)||String(b.right).toLowerCase().includes(v))}return y},[u,o,c]),p=w.useMemo(()=>({added:u.filter(y=>y.status==="added").length,removed:u.filter(y=>y.status==="removed").length,changed:u.filter(y=>y.status==="changed").length,same:u.filter(y=>y.status==="same").length}),[u]),f=y=>{if(y===void 0)return"—";if(y===null)return"null";if(Array.isArray(y))return y.length===0?"[]":y.length===1?String(y[0]):y.join(", ");if(typeof y=="object")return JSON.stringify(y);const v=String(y);if(v.includes("\\n")||v.length>100){const b=v.split("\\n").length;if(b>1)return`[${b} lines of G-code/script]`;if(v.length>100)return v.substring(0,100)+"…"}return v};return w.useEffect(()=>{const y=v=>{v.key==="Escape"&&t()};return window.addEventListener("keydown",y),()=>window.removeEventListener("keydown",y)},[t]),a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:a.jsx(Tt,{className:"w-full max-w-4xl max-h-[85vh] flex flex-col overflow-hidden",children:a.jsxs(Mt,{className:"p-0 flex flex-col min-h-0 flex-1",children:[a.jsxs("div",{className:"flex-shrink-0 flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(Cx,{className:"w-5 h-5 text-blue-400"}),s("profiles.diff.title")]}),a.jsx("button",{onClick:t,className:"text-bambu-gray hover:text-white",children:a.jsx(Ht,{className:"w-5 h-5"})})]}),a.jsxs("div",{className:"flex-shrink-0 grid grid-cols-2 gap-4 p-4 border-b border-bambu-dark-tertiary bg-bambu-dark",children:[a.jsxs("div",{className:"text-center",children:[a.jsx("span",{className:"text-sm text-bambu-gray",children:s("profiles.diff.left")}),a.jsx("p",{className:"text-white font-medium truncate",children:r})]}),a.jsxs("div",{className:"text-center",children:[a.jsx("span",{className:"text-sm text-bambu-gray",children:s("profiles.diff.right")}),a.jsx("p",{className:"text-white font-medium truncate",children:i})]})]}),a.jsxs("div",{className:"flex-shrink-0 flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-4 text-sm",children:[a.jsxs("span",{className:"flex items-center gap-1 text-green-400",children:[a.jsx(sr,{className:"w-3.5 h-3.5"}),p.added," ",s("profiles.diff.added")]}),a.jsxs("span",{className:"flex items-center gap-1 text-red-400",children:[a.jsx(kN,{className:"w-3.5 h-3.5"}),p.removed," ",s("profiles.diff.removed")]}),a.jsxs("span",{className:"flex items-center gap-1 text-amber-400",children:[a.jsx(rF,{className:"w-3.5 h-3.5"}),p.changed," ",s("profiles.diff.changed")]}),a.jsxs("span",{className:"flex items-center gap-1 text-bambu-gray",children:[a.jsx(jM,{className:"w-3.5 h-3.5"}),p.same," ",s("profiles.diff.same")]})]}),a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsxs("div",{className:"relative",children:[a.jsx(Pr,{className:"absolute left-2 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),a.jsx("input",{type:"text",value:c,onChange:y=>d(y.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&&a.jsxs("div",{className:"flex rounded overflow-hidden border border-bambu-dark-tertiary",children:[a.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")}),a.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")})]})]})]}),a.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto",children:m.length===0?a.jsxs("div",{className:"text-center py-12 text-bambu-gray",children:[a.jsx(jM,{className:"w-12 h-12 mx-auto mb-4 opacity-30"}),a.jsx("p",{children:s(o==="changes"?"profiles.diff.noDifferences":"profiles.diff.noFieldsMatch")})]}):a.jsxs("table",{className:"w-full",children:[a.jsx("thead",{className:"sticky top-0 bg-bambu-dark-secondary",children:a.jsxs("tr",{className:"text-sm text-bambu-gray border-b border-bambu-dark-tertiary",children:[a.jsx("th",{className:"text-left p-3 w-1/3",children:s("profiles.diff.field")}),a.jsx("th",{className:"text-left p-3 w-1/3",children:r}),a.jsx("th",{className:"text-left p-3 w-1/3",children:i})]})}),a.jsx("tbody",{children:m.map(y=>{const v={added:"bg-green-500/10",removed:"bg-red-500/10",changed:"bg-amber-500/10",same:""}[y.status],b={added:a.jsx(sr,{className:"w-3.5 h-3.5 text-green-400"}),removed:a.jsx(kN,{className:"w-3.5 h-3.5 text-red-400"}),changed:a.jsx(rF,{className:"w-3.5 h-3.5 text-amber-400"}),same:a.jsx(jM,{className:"w-3.5 h-3.5 text-bambu-gray-dark"})}[y.status];return a.jsxs("tr",{className:`border-b border-bambu-dark-tertiary ${v}`,children:[a.jsx("td",{className:"p-3",children:a.jsxs("div",{className:"flex items-center gap-2",children:[b,a.jsx("span",{className:"text-sm text-white font-mono",children:y.key})]})}),a.jsx("td",{className:"p-3",children:a.jsx("span",{className:`text-sm font-mono break-all ${y.status==="removed"?"text-red-300":y.status==="changed"?"text-white":"text-bambu-gray"}`,children:f(y.left)})}),a.jsx("td",{className:"p-3",children:a.jsx("span",{className:`text-sm font-mono break-all ${y.status==="added"?"text-green-300":y.status==="changed"?"text-white":"text-bambu-gray"}`,children:f(y.right)})})]},y.key)})})]})})]})})})}function Gnt({onClose:t,initialData:e,allPresets:n,t:r}){const{showToast:i}=hn(),s=nn(),o=!!e?.setting_id,[l,c]=w.useState("common"),[d,u]=w.useState(e?.type||"filament"),[m,p]=w.useState(e?.name?o?e.name:`${e.name} (Copy)`:""),[f,y]=w.useState(e?.base_id||""),[v,b]=w.useState(""),[g,_]=w.useState(e?.setting||{inherits:""}),[C,P]=w.useState(JSON.stringify(e?.setting||{inherits:""},null,2)),[N,A]=w.useState(null),[T,F]=w.useState(""),[k,D]=w.useState(!1),[H,z]=w.useState(""),[Q,L]=w.useState(!1),[te,ie]=w.useState(zle),[J,oe]=w.useState(!1),[fe,re]=w.useState(""),[W,ne]=w.useState(""),[me,be]=w.useState(!0),[Ce,q]=w.useState(null),[Y,E]=w.useState(!1),j=w.useMemo(()=>({filament:n.filament,print:n.process,printer:n.printer})[d]||[],[n,d]),O=w.useMemo(()=>j.filter(Re=>Kw(Re.setting_id)),[j]),{data:K}=Xe({queryKey:["cloudFields",d],queryFn:()=>de.getCloudFields(d==="print"?"process":d),staleTime:1e3*60*60}),{data:U}=Xe({queryKey:["allPresetDetails",d,O.map(Re=>Re.setting_id).join(",")],queryFn:async()=>{const Re={};for(let Ye=0;Ye{try{const we=await de.getCloudSettingDetail(Fe.setting_id);return{id:Fe.setting_id,detail:we}}catch{return null}}))).forEach(Fe=>{Fe&&(Re[Fe.id]=Fe.detail)})}return Re},enabled:O.length>0,staleTime:1e3*60*10}),{data:ue,isLoading:I}=Xe({queryKey:["cloudSettingDetail",f],queryFn:()=>de.getCloudSettingDetail(f),enabled:!!f});w.useEffect(()=>{l!=="json"&&P(JSON.stringify(g,null,2))},[g,l]);const G=w.useMemo(()=>({filament:n.filament,print:n.process,printer:n.printer}[d]||[]).filter($e=>!Kw($e.setting_id)).sort(($e,Ye)=>$e.name.localeCompare(Ye.name)),[n,d]);w.useEffect(()=>{if(!f)return;const Re=G.find($e=>$e.setting_id===f);Re&&(b(Re.name),o||(_({inherits:Re.name}),P(JSON.stringify({inherits:Re.name},null,2))))},[f,G,o]);const X=w.useMemo(()=>{const Re=K?.fields||[],$e=new Set(Re.map(Fe=>Fe.key)),Ye=new Set,tt=new Set(["inherits","updated_time","compatible_printers","compatible_prints"]);U&&Object.values(U).forEach(Fe=>{Fe?.setting&&Object.keys(Fe.setting).forEach(we=>{!$e.has(we)&&!tt.has(we)&&Ye.add(we)})}),Object.keys(g).forEach(Fe=>{!$e.has(Fe)&&!tt.has(Fe)&&Ye.add(Fe)});const pe=Array.from(Ye).sort().map(Fe=>({key:Fe,label:Fe.replace(/_/g," ").replace(/\b\w/g,we=>we.toUpperCase()),type:"text",category:"discovered",description:r("profiles.presets.discoveredFromPresets")}));return[...Re,...pe]},[K,U,g,r]),V=X.filter(Re=>Re.label.toLowerCase().includes(T.toLowerCase())||Re.key.toLowerCase().includes(T.toLowerCase())),ee=()=>{if(H.trim()){const Re=H.trim().toLowerCase().replace(/\s+/g,"_");se(Re,""),z(""),L(!1),i(r("profiles.presets.toast.fieldAdded",{key:Re}))}},se=(Re,$e)=>{_(Ye=>{const tt={...Ye};return $e===""||$e===void 0?delete tt[Re]:tt[Re]=$e,tt})},ge=Re=>{_($e=>({...$e,...Re.settings})),q(Re.name),i(r("profiles.templates.toast.applied"))},he=()=>{if(!fe.trim())return;const Re={...g};if(delete Re.inherits,Object.keys(Re).length===0){i(r("profiles.presets.noOverridesToSave"),"error");return}const $e={id:Date.now().toString(),name:fe.trim(),description:W.trim()||r("profiles.presets.customTemplate"),type:d,settings:Re,showInModal:me},Ye=[...te,$e];ie(Ye),Ule(Ye),oe(!1),re(""),ne(""),be(!0),i(r("profiles.templates.toast.created"))},le=w.useMemo(()=>te.filter(Re=>Re.type===d&&Re.showInModal),[d,te]),B=Re=>{P(Re);try{const $e=JSON.parse(Re);_($e),A(null)}catch($e){A($e.message)}},R=Re=>{Re.preventDefault(),D(!1);const $e=Re.dataTransfer.files[0];if($e&&$e.name.endsWith(".json")){const Ye=new FileReader;Ye.onload=tt=>{try{const pe=tt.target?.result,Fe=JSON.parse(pe),we=Fe.setting||Fe;_(Ve=>({...Ve,...we})),P(JSON.stringify({...g,...we},null,2)),i(r("profiles.presets.fileImported"))}catch{i(r("profiles.presets.invalidJsonFile"),"error")}},Ye.readAsText($e)}},ae=it({mutationFn:()=>{const Re={...g},$e=d==="filament"?"filament_settings_id":d==="print"?"print_settings_id":"printer_settings_id";Re[$e]=`"${m}"`;const Ye={type:d,name:m,base_id:f,setting:Re};return de.createCloudSetting(Ye)},onSuccess:async()=>{i(r("profiles.presets.toast.created")),await s.refetchQueries({queryKey:["cloudSettings"]}),t()},onError:Re=>i(Re.message,"error")}),_e=it({mutationFn:()=>{if(!e?.setting_id)throw new Error(r("profiles.presets.noSettingId"));return de.updateCloudSetting(e.setting_id,{name:m,setting:g})},onSuccess:async()=>{i(r("profiles.presets.toast.updated")),s.removeQueries({queryKey:["cloudSettingDetail"]}),await s.refetchQueries({queryKey:["cloudSettings"]}),t()},onError:Re=>i(Re.message,"error")}),Se=o?_e:ae,ve=ue?.setting?.inherits,Te=ve?G.find(Re=>Re.name===ve):void 0,{data:ye}=Xe({queryKey:["cloudSettingDetail",Te?.setting_id],queryFn:()=>de.getCloudSettingDetail(Te.setting_id),enabled:!!Te?.setting_id}),Ae=w.useMemo(()=>{const Re=ye?.setting||{},$e=ue?.setting||{},Ye=f&&U?.[f]?.setting?U[f].setting:{};return{...Re,...$e,...Ye}},[f,ue,ye,U]),Le=Re=>{if(Re==null)return"";if(Array.isArray(Re)){const $e=[...new Set(Re.map(Ye=>String(Ye)))];return $e.length===1?$e[0]:Re.join(", ")}return String(Re)},Me=Re=>{const $e=g[Re.key],Ye=Ae[Re.key],tt=Le(Ye),pe=I?r("common.loading"):tt||"",Fe="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 we=$e==="1"||$e===void 0&&Ye==="1";return a.jsx("button",{type:"button",onClick:()=>se(Re.key,$e==="1"?"0":"1"),className:`w-8 h-5 rounded-full transition-colors ${we?"bg-bambu-green":"bg-bambu-dark-tertiary"}`,children:a.jsx("div",{className:`w-4 h-4 rounded-full bg-white shadow transition-transform ${we?"translate-x-3.5":"translate-x-0.5"}`})})}return Re.type==="select"?a.jsxs("select",{value:$e||"",onChange:we=>se(Re.key,we.target.value),className:Fe,children:[a.jsx("option",{value:"",children:pe}),Re.options?.map(we=>a.jsx("option",{value:we.value,children:we.label},we.value))]}):a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("input",{type:Re.type==="number"?"number":"text",value:$e!==void 0?String($e):"",onChange:we=>se(Re.key,we.target.value),step:Re.step,min:Re.min,max:Re.max,placeholder:pe,className:Fe}),Re.unit&&a.jsx("span",{className:"text-xs text-bambu-gray whitespace-nowrap",children:Re.unit})]})},Oe=w.useMemo(()=>ue?.setting?ue.setting:{},[ue]);return a.jsxs("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",onDragOver:Re=>{Re.preventDefault(),D(!0)},onDragLeave:()=>D(!1),onDrop:R,children:[Y&&f&&a.jsx(Ble,{onClose:()=>E(!1),leftPreset:Oe,rightPreset:g,leftLabel:r("profiles.presets.baseLabel",{name:v||f}),rightLabel:r("profiles.presets.currentLabel",{name:m||r("profiles.presets.newPreset")}),t:r}),a.jsx(Tt,{className:"w-full max-w-6xl max-h-[90vh] flex flex-col overflow-y-auto",children:a.jsxs(Mt,{className:"p-0 flex flex-col h-full",children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[a.jsxs("div",{children:[a.jsx("h2",{className:"text-xl font-semibold text-white",children:r(o?"profiles.presets.editPreset":e?"profiles.presets.duplicatePreset":"profiles.presets.createNewPreset")}),a.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:r("profiles.presets.customizeSettings")})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[f&&a.jsxs("button",{onClick:()=>E(!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:r("profiles.presets.compareWithBase"),children:[a.jsx(Cx,{className:"w-4 h-4"}),r("profiles.presets.compare")]}),a.jsx("button",{onClick:t,className:"p-2 text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary rounded-lg transition-colors",children:a.jsx(Ht,{className:"w-5 h-5"})})]})]}),k&&a.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:a.jsxs("div",{className:"text-center",children:[a.jsx(La,{className:"w-12 h-12 text-bambu-green mx-auto mb-2"}),a.jsx("p",{className:"text-bambu-green font-medium",children:r("profiles.presets.dropJsonToImport")})]})}),a.jsxs("div",{className:"p-4 border-b border-bambu-dark-tertiary space-y-3",children:[a.jsxs("div",{className:"grid grid-cols-3 gap-4 max-[640px]:grid-cols-1",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("common.type")}),a.jsxs("select",{value:d,onChange:Re=>{u(Re.target.value),y("")},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:[a.jsx("option",{value:"filament",children:r("profiles.presets.types.filament")}),a.jsx("option",{value:"print",children:r("profiles.presets.types.process")}),a.jsx("option",{value:"printer",children:r("profiles.presets.types.printer")})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("profiles.presets.basePreset")}),a.jsxs("select",{value:f,onChange:Re=>y(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:[a.jsx("option",{value:"",children:r("profiles.presets.selectBasePreset")}),G.map(Re=>a.jsx("option",{value:Re.setting_id,children:Re.name},Re.setting_id))]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("profiles.presets.presetName")}),a.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:r("profiles.presets.myCustomPreset")})]})]}),v&&a.jsx("div",{className:"text-xs text-bambu-gray",children:a.jsxs("p",{className:"flex items-center gap-1",children:[a.jsx(Ur,{className:"w-3 h-3 text-bambu-green"}),r("profiles.presets.inheritsFrom")," ",a.jsx("span",{className:"text-white",children:v}),I&&a.jsx(pt,{className:"w-3 h-3 animate-spin ml-1"})]})})]}),a.jsxs("div",{className:"flex border-b border-bambu-dark-tertiary max-[640px]:flex-wrap max-[640px]:items-center",children:[a.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:[a.jsx(PH,{className:"w-4 h-4"}),r("profiles.presets.tabs.common")]}),a.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:[a.jsx(tS,{className:"w-4 h-4"}),r("profiles.presets.tabs.allFields")]}),a.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:[a.jsx(wy,{className:"w-4 h-4"}),"JSON",N&&a.jsx(ei,{className:"w-3 h-3 text-red-400"})]}),a.jsx("div",{className:"flex-1 max-[640px]:hidden"}),a.jsxs("button",{onClick:()=>{const Re={name:m,type:d,base_id:f,setting:g},$e=new Blob([JSON.stringify(Re,null,2)],{type:"application/json"}),Ye=URL.createObjectURL($e),tt=document.createElement("a");tt.href=Ye,tt.download=`${m||"preset"}.json`,document.body.appendChild(tt),tt.click(),document.body.removeChild(tt),URL.revokeObjectURL(Ye),i(r("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:r("profiles.presets.exportToJson"),children:[a.jsx(ga,{className:"w-4 h-4"}),r("common.download")]}),a.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:r("profiles.presets.importFromJson"),children:[a.jsx(La,{className:"w-4 h-4"}),r("common.upload")]}),a.jsx("input",{id:"file-import",type:"file",accept:".json",className:"hidden",onChange:Re=>{const $e=Re.target.files?.[0];if($e){const Ye=new FileReader;Ye.onload=tt=>{try{const pe=JSON.parse(tt.target?.result),Fe=pe.setting||pe;_(we=>({...we,...Fe})),i(r("profiles.presets.fileImported"))}catch{i(r("profiles.presets.invalidJson"),"error")}},Ye.readAsText($e)}}})]}),a.jsxs("div",{className:"flex-1 p-4",children:[l==="common"&&a.jsxs("div",{className:"space-y-6",children:[a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center justify-between mb-3",children:[a.jsxs("h3",{className:"text-sm font-medium text-white flex items-center gap-2",children:[a.jsx($x,{className:"w-4 h-4 text-amber-400"}),r("profiles.templates.title")]}),Object.keys(g).filter(Re=>Re!=="inherits").length>0&&a.jsxs("button",{onClick:()=>oe(!J),className:"text-xs text-bambu-gray hover:text-white flex items-center gap-1 transition-colors",children:[a.jsx(_s,{className:"w-3 h-3"}),r("profiles.presets.saveAsTemplate")]})]}),J&&a.jsxs("div",{className:"mb-3 p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"grid grid-cols-2 gap-2 mb-2",children:[a.jsx("input",{type:"text",value:fe,onChange:Re=>re(Re.target.value),placeholder:r("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}),a.jsx("input",{type:"text",value:W,onChange:Re=>ne(Re.target.value),placeholder:r("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"})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex gap-2",children:[a.jsxs(De,{size:"sm",onClick:he,disabled:!fe.trim(),children:[a.jsx(_s,{className:"w-3 h-3"}),r("common.save")]}),a.jsx(De,{size:"sm",variant:"secondary",onClick:()=>oe(!1),children:r("common.cancel")})]}),a.jsxs("button",{onClick:()=>be(!me),className:`flex items-center gap-1.5 text-xs transition-colors ${me?"text-bambu-green":"text-bambu-gray hover:text-white"}`,children:[me?a.jsx(vl,{className:"w-3.5 h-3.5"}):a.jsx(Og,{className:"w-3.5 h-3.5"}),r(me?"profiles.templates.shownInModals":"profiles.templates.hiddenInModals")]})]})]}),Ce&&a.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:[a.jsx(Ur,{className:"w-4 h-4 text-bambu-green"}),a.jsxs("span",{className:"text-sm text-bambu-green",children:[r("profiles.presets.templateApplied")," ",a.jsx("span",{className:"font-medium",children:Ce})]}),a.jsx("button",{onClick:()=>q(null),className:"ml-auto text-bambu-green/70 hover:text-bambu-green",children:a.jsx(Ht,{className:"w-4 h-4"})})]}),a.jsxs("div",{className:"grid grid-cols-3 gap-2",children:[le.map(Re=>a.jsxs("button",{onClick:()=>ge(Re),className:"p-3 text-left bg-bambu-dark border border-bambu-dark-tertiary rounded-lg hover:border-bambu-gray-dark transition-colors",children:[a.jsx("p",{className:"text-sm font-medium text-white",children:Re.name}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:Re.description})]},Re.id)),le.length===0&&a.jsx("p",{className:"col-span-3 text-center text-bambu-gray text-sm py-4",children:r("profiles.presets.noTemplatesSelected")})]}),a.jsx("p",{className:"text-xs text-bambu-gray-dark mt-2 text-center",children:r("profiles.presets.manageTemplatesHint")})]}),a.jsxs("div",{children:[a.jsx("h3",{className:"text-sm font-medium text-white mb-3",children:r("profiles.presets.commonSettings")}),a.jsx("div",{className:"grid grid-cols-2 gap-x-6 gap-y-3",children:X.slice(0,10).map(Re=>a.jsxs("div",{className:"flex items-center justify-between gap-4 max-[640px]:flex-col max-[640px]:items-start",children:[a.jsx("label",{className:"text-sm text-bambu-gray flex-shrink-0",children:Re.label}),a.jsx("div",{className:"w-48 max-[640px]:w-full",children:Me(Re)})]},Re.key))})]}),Object.keys(g).length>1&&a.jsxs("div",{children:[a.jsx("h3",{className:"text-sm font-medium text-white mb-3",children:r("profiles.presets.currentOverrides")}),a.jsx("div",{className:"flex flex-wrap gap-2",children:Object.entries(g).filter(([Re])=>Re!=="inherits").map(([Re,$e])=>a.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($e).slice(0,20),a.jsx("button",{onClick:()=>se(Re,void 0),className:"hover:text-white",children:a.jsx(Ht,{className:"w-3 h-3"})})]},Re))})]})]}),l==="fields"&&a.jsxs("div",{className:"grid grid-cols-2 gap-6",style:{height:"400px"},children:[a.jsxs("div",{className:"flex flex-col h-full overflow-hidden",children:[a.jsxs("div",{className:"flex items-center justify-between mb-3 flex-shrink-0",children:[a.jsx("h3",{className:"text-sm font-medium text-white",children:r("profiles.presets.availableFields")}),a.jsx("span",{className:"text-xs text-bambu-gray",children:U?r("profiles.templates.fieldsCount",{count:X.length}):r("common.loading")})]}),a.jsxs("div",{className:"relative mb-3 flex-shrink-0",children:[a.jsx(Pr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),a.jsx("input",{type:"text",value:T,onChange:Re=>F(Re.target.value),placeholder:r("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"})]}),a.jsxs("div",{className:"flex-1 overflow-y-auto space-y-1 pr-2 min-h-0",children:[V.filter(Re=>!(Re.key in g)).map(Re=>{const $e=Ae[Re.key],Ye=Le($e);return a.jsxs("div",{onClick:()=>{_(tt=>({...tt,[Re.key]:Ye||""}))},className:"flex items-center justify-between gap-2 p-2 rounded-lg hover:bg-bambu-dark-tertiary transition-colors cursor-pointer group",children:[a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsx("p",{className:"text-sm text-white truncate",children:Re.label}),a.jsx("p",{className:"text-xs text-bambu-gray-dark truncate",children:Re.key})]}),a.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[Ye&&a.jsxs("span",{className:"text-xs text-bambu-gray bg-bambu-dark px-2 py-0.5 rounded max-w-32 truncate",title:Ye,children:[Ye.slice(0,20),Ye.length>20?"...":""]}),a.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:a.jsx(sr,{className:"w-4 h-4 text-bambu-gray group-hover:text-bambu-green transition-colors"})})]})]},Re.key)}),V.filter(Re=>!(Re.key in g)).length===0&&a.jsx("p",{className:"text-center text-bambu-gray py-4 text-sm",children:r(T?"profiles.presets.noMatchingFields":"profiles.presets.allFieldsAdded")})]}),a.jsx("div",{className:"pt-3 mt-3 border-t border-bambu-dark-tertiary flex-shrink-0",children:Q?a.jsxs("div",{className:"flex gap-2",children:[a.jsx("input",{type:"text",value:H,onChange:Re=>z(Re.target.value),onKeyDown:Re=>Re.key==="Enter"&&ee(),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}),a.jsx(De,{size:"sm",onClick:ee,disabled:!H.trim(),children:a.jsx(sr,{className:"w-4 h-4"})}),a.jsx(De,{size:"sm",variant:"secondary",onClick:()=>{L(!1),z("")},children:a.jsx(Ht,{className:"w-4 h-4"})})]}):a.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:[a.jsx(sr,{className:"w-4 h-4"}),r("profiles.presets.addCustomField")]})})]}),a.jsxs("div",{className:"flex flex-col h-full overflow-hidden",children:[a.jsxs("div",{className:"flex items-center justify-between mb-3 flex-shrink-0",children:[a.jsx("h3",{className:"text-sm font-medium text-white",children:r("profiles.presets.yourOverrides")}),a.jsx("span",{className:"text-xs text-bambu-gray",children:r("profiles.templates.fieldsCount",{count:Object.keys(g).filter(Re=>Re!=="inherits").length})})]}),a.jsxs("div",{className:"flex-1 overflow-y-auto space-y-2 pr-2 min-h-0",children:[Object.entries(g).filter(([Re])=>Re!=="inherits").map(([Re,$e])=>{const Ye=X.find(tt=>tt.key===Re);return a.jsxs("div",{className:"p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center justify-between mb-2",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm font-medium text-white",children:Ye?.label||Re}),a.jsx("p",{className:"text-xs text-bambu-gray-dark",children:Re})]}),a.jsx("button",{onClick:()=>se(Re,void 0),className:"p-1 text-bambu-gray hover:text-red-400 transition-colors",children:a.jsx(Ht,{className:"w-4 h-4"})})]}),Ye?Me(Ye):a.jsx("input",{type:"text",value:String($e),onChange:tt=>se(Re,tt.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(g).filter(Re=>Re!=="inherits").length===0&&a.jsxs("div",{className:"text-center py-8 text-bambu-gray",children:[a.jsx(PH,{className:"w-8 h-8 mx-auto mb-2 opacity-50"}),a.jsx("p",{className:"text-sm",children:r("profiles.presets.noOverridesYet")}),a.jsx("p",{className:"text-xs mt-1",children:r("profiles.presets.clickFieldsToAdd")})]})]}),Object.keys(g).filter(Re=>Re!=="inherits").length>0&&a.jsx("div",{className:"pt-3 mt-3 border-t border-bambu-dark-tertiary flex-shrink-0",children:a.jsxs("button",{onClick:()=>{oe(!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:[a.jsx(_s,{className:"w-4 h-4"}),r("profiles.presets.saveAsTemplate")]})})]})]}),l==="json"&&a.jsxs("div",{className:"space-y-2",children:[N&&a.jsxs("div",{className:"flex items-center gap-2 text-red-400 text-sm",children:[a.jsx(ei,{className:"w-4 h-4"}),N]}),a.jsx("textarea",{value:C,onChange:Re=>B(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 ${N?"border-red-500 focus:border-red-500":"border-bambu-dark-tertiary focus:border-bambu-green"}`,spellCheck:!1}),a.jsx("p",{className:"text-xs text-bambu-gray",children:r("profiles.presets.jsonTip")})]})]}),a.jsxs("div",{className:"p-4 border-t border-bambu-dark-tertiary flex gap-2",children:[a.jsx(De,{variant:"secondary",onClick:t,className:"flex-1",children:r("common.cancel")}),a.jsxs(De,{onClick:()=>Se.mutate(),disabled:Se.isPending||!m.trim()||!o&&!f||!!N,className:"flex-1",children:[Se.isPending?a.jsx(pt,{className:"w-4 h-4 animate-spin"}):o?a.jsx(_s,{className:"w-4 h-4"}):a.jsx(sr,{className:"w-4 h-4"}),r(o?"common.save":e?"common.duplicate":"common.create")]})]})]})})]})}function Wnt({settings:t,lastSyncTime:e,onRefresh:n,isRefreshing:r,printers:i,hasPermission:s,t:o}){const[l,c]=w.useState(""),[d,u]=w.useState("all"),[m,p]=w.useState("all"),[f,y]=w.useState("all"),[v,b]=w.useState("all"),[g,_]=w.useState("all"),[C,P]=w.useState("all"),[N,A]=w.useState(null),[T,F]=w.useState(!1),[k,D]=w.useState(!1),[H,z]=w.useState(null),[Q,L]=w.useState(null),[te,ie]=w.useState(null),[J,oe]=w.useState(!1),[fe,re]=w.useState([null,null]),[W,ne]=w.useState(!1),[me,be]=w.useState(null),Ce=nn(),q=w.useMemo(()=>[...t.filament.map(ee=>({...ee,type:"filament"})),...t.printer.map(ee=>({...ee,type:"printer"})),...t.process.map(ee=>({...ee,type:"process"}))].map(ee=>({...ee,meta:b5(ee.name)})),[t]),Y=w.useMemo(()=>{const V=new Set,ee=new Set,se=new Set;return q.forEach(ge=>{ge.meta.nozzle&&V.add(ge.meta.nozzle),ge.meta.filamentType&&ee.add(ge.meta.filamentType),ge.meta.layerHeight&&se.add(ge.meta.layerHeight)}),{printers:i.map(ge=>({id:ge.id.toString(),name:ge.name})),nozzles:Array.from(V).sort((ge,he)=>parseFloat(ge)-parseFloat(he)),filaments:Array.from(ee).sort(),layerHeights:Array.from(se).sort((ge,he)=>parseFloat(ge)-parseFloat(he))}},[q,i]),E=w.useMemo(()=>f==="all"?null:i.find(ee=>ee.id.toString()===f)?.model||null,[f,i]),j=w.useMemo(()=>q.filter(V=>d==="all"||V.type===d).filter(V=>{if(m==="all")return!0;const ee=Kw(V.setting_id);return m==="custom"?ee:!ee}).filter(V=>{if(f==="all"||!E)return!0;const ee=V.meta.printer?.toLowerCase()||"",se=E.toLowerCase();return ee.includes(se)||se.includes(ee)}).filter(V=>v==="all"||V.meta.nozzle===v).filter(V=>g==="all"||V.meta.filamentType===g).filter(V=>C==="all"||V.meta.layerHeight===C).filter(V=>l===""||V.name.toLowerCase().includes(l.toLowerCase())).sort((V,ee)=>V.name.localeCompare(ee.name)),[q,d,m,f,E,v,g,C,l]),O=V=>{if(J){const ee=fe[0]?.setting_id===V.setting_id,se=fe[1]?.setting_id===V.setting_id;if(ee)re([fe[1],null]);else if(se)re([fe[0],null]);else if(!fe[0])re([V,null]);else if(fe[1]){if(fe[0].type!==V.type)return;re([fe[0],V])}else{if(fe[0].type!==V.type)return;re([fe[0],V])}}else A(V)},K=V=>{if(fe[0]?.setting_id===V.setting_id)return 0;if(fe[1]?.setting_id===V.setting_id)return 1},U=async V=>{try{const ee=await de.getCloudSettingDetail(V.setting_id),se=V.type==="process"?"print":V.type;z({type:se,name:V.name,base_id:ee.base_id||"GFSA00",setting:ee.setting||{}}),A(null)}catch(ee){console.error("Failed to fetch preset details for duplication:",ee)}},ue=async V=>{try{Ce.removeQueries({queryKey:["cloudSettingDetail",V.setting_id]});const ee=await de.getCloudSettingDetail(V.setting_id),se=V.type==="process"?"print":V.type;L({type:se,name:V.name,base_id:ee.base_id||"GFSA00",setting:ee.setting||{},setting_id:V.setting_id}),A(null)}catch(ee){console.error("Failed to fetch preset details for editing:",ee)}},I=()=>{u("all"),p("all"),y("all"),b("all"),_("all"),P("all"),c("")},G=d!=="all"||m!=="all"||f!=="all"||v!=="all"||g!=="all"||C!=="all"||l!=="",X=t.filament.length+t.printer.length+t.process.length;return a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"space-y-4 mb-6",children:[a.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[a.jsxs("div",{className:"relative flex-1",children:[a.jsx(Pr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),a.jsx("input",{type:"text",value:l,onChange:V=>c(V.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"})]}),a.jsxs("div",{className:"flex gap-2 max-[550px]:flex-wrap max-[550px]:items-center",children:[a.jsxs(De,{variant:J?"primary":"secondary",onClick:()=>{J?(oe(!1),re([null,null])):oe(!0)},children:[a.jsx(Cx,{className:"w-4 h-4"}),o(J?"common.cancel":"profiles.presets.compare")]}),a.jsxs(De,{variant:"secondary",onClick:()=>D(!0),disabled:!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.cloudView.noTemplatesPermission"),children:[a.jsx($x,{className:"w-4 h-4"}),o("profiles.cloudView.templates")]}),a.jsxs(De,{variant:"secondary",onClick:n,disabled:r||!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.cloudView.noRefreshPermission"),children:[a.jsx(lr,{className:`w-4 h-4 ${r?"animate-spin":""}`}),o("profiles.cloudView.refresh")]}),a.jsxs(De,{onClick:()=>F(!0),disabled:!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.cloudView.noCreatePermission"),children:[a.jsx(sr,{className:"w-4 h-4"}),o("profiles.cloudView.newPreset")]})]})]}),a.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[a.jsx(VP,{className:"w-4 h-4 text-bambu-gray"}),a.jsx(cx,{label:o("profiles.cloudView.filters.type"),value:d,options:[{value:"all",label:o("profiles.cloudView.filters.all"),count:X},{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:V=>u(V)}),a.jsx(cx,{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:V=>p(V)}),Y.printers.length>0&&a.jsx(cx,{label:o("profiles.cloudView.filters.printer"),value:f,options:[{value:"all",label:o("profiles.cloudView.filters.all")},...Y.printers.map(V=>({value:V.id,label:V.name}))],onChange:y}),Y.nozzles.length>0&&a.jsx(cx,{label:o("profiles.cloudView.filters.nozzle"),value:v,options:[{value:"all",label:o("profiles.cloudView.filters.all")},...Y.nozzles.map(V=>({value:V,label:V}))],onChange:b}),Y.filaments.length>0&&(d==="all"||d==="filament")&&a.jsx(cx,{label:o("profiles.cloudView.filters.filament"),value:g,options:[{value:"all",label:o("profiles.cloudView.filters.all")},...Y.filaments.map(V=>({value:V,label:V}))],onChange:_}),Y.layerHeights.length>0&&(d==="all"||d==="process")&&a.jsx(cx,{label:o("profiles.cloudView.filters.layer"),value:C,options:[{value:"all",label:o("profiles.cloudView.filters.all")},...Y.layerHeights.map(V=>({value:V,label:V}))],onChange:P}),G&&a.jsx("button",{onClick:I,className:"px-3 py-2 text-sm text-bambu-gray hover:text-white transition-colors",children:o("profiles.cloudView.clearFilters")})]})]}),J&&a.jsx("div",{className:"mb-4 p-3 bg-blue-500/10 border border-blue-500/30 rounded-lg",children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-4",children:[a.jsx(Cx,{className:"w-5 h-5 text-blue-400"}),a.jsx("span",{className:"text-white font-medium",children:o("profiles.cloudView.compareMode")}),a.jsx("span",{className:"text-bambu-gray",children:fe[0]?o("profiles.cloudView.selectAnotherPreset",{type:fe[0].type}):o("profiles.cloudView.clickTwoPresets")})]}),a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:`px-2 py-1 text-sm rounded truncate max-w-[200px] ${fe[0]?"bg-blue-500/30 text-blue-700 dark:text-blue-300":"bg-bambu-dark text-bambu-gray"}`,children:fe[0]?fe[0].name:o("profiles.cloudView.selectFirst")}),a.jsx(rF,{className:"w-4 h-4 text-bambu-gray"}),a.jsx("span",{className:`px-2 py-1 text-sm rounded truncate max-w-[200px] ${fe[1]?"bg-blue-500/30 text-blue-700 dark:text-blue-300":"bg-bambu-dark text-bambu-gray"}`,children:fe[1]?fe[1].name:o("profiles.cloudView.selectSecond")})]}),fe[0]&&fe[1]&&a.jsxs(De,{size:"sm",onClick:async()=>{try{const[V,ee]=await Promise.all([de.getCloudSettingDetail(fe[0].setting_id),de.getCloudSettingDetail(fe[1].setting_id)]);be([V.setting||{},ee.setting||{}]),ne(!0)}catch{}},children:[a.jsx(Cx,{className:"w-4 h-4"}),o("profiles.cloudView.compareNow")]})]})]})}),a.jsxs("div",{className:"flex flex-wrap items-center gap-4 mb-4 text-sm text-bambu-gray",children:[e&&a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsx(Yn,{className:"w-3 h-3"}),o("profiles.cloudView.lastSynced")," ",ap(e.toISOString(),"system",o)]}),a.jsx("span",{children:o("profiles.cloudView.showingCount",{showing:j.length,total:X})}),a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-bambu-green"}),a.jsxs("span",{children:["= ",o("profiles.presets.myPreset")]})]})]}),j.length===0?a.jsxs("div",{className:"text-center py-16",children:[a.jsx(da,{className:"w-12 h-12 text-bambu-gray-dark mx-auto mb-4"}),a.jsx("p",{className:"text-bambu-gray",children:o("profiles.cloudView.noPresetsFound")}),G&&a.jsx("button",{onClick:I,className:"mt-2 text-sm text-bambu-green hover:text-bambu-green-light",children:o("profiles.cloudView.clearFilters")})]}):a.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-6",children:[a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center gap-2 mb-3 px-1",children:[a.jsx(qP,{className:"w-4 h-4 text-amber-400"}),a.jsx("h3",{className:"text-sm font-medium text-bambu-gray",children:o("profiles.cloudView.columns.filament")}),a.jsxs("span",{className:"text-xs text-bambu-gray-dark",children:["(",j.filter(V=>V.type==="filament").length,")"]})]}),a.jsxs("div",{className:"space-y-1 max-h-[calc(100vh-320px)] overflow-y-auto pr-1",children:[j.filter(V=>V.type==="filament").map(V=>a.jsx(j3,{setting:V,onClick:()=>O(V),onDuplicate:()=>U(V),compareMode:J,isCompareSelected:K(V)!==void 0,compareIndex:K(V),compareDisabled:J&&!!fe[0]&&fe[0].type!==V.type,t:o},V.setting_id)),j.filter(V=>V.type==="filament").length===0&&a.jsx("p",{className:"text-xs text-bambu-gray-dark px-3 py-2",children:o("profiles.cloudView.noFilamentPresets")})]})]}),a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center gap-2 mb-3 px-1",children:[a.jsx(Ud,{className:"w-4 h-4 text-blue-400"}),a.jsx("h3",{className:"text-sm font-medium text-bambu-gray",children:o("profiles.cloudView.columns.process")}),a.jsxs("span",{className:"text-xs text-bambu-gray-dark",children:["(",j.filter(V=>V.type==="process").length,")"]})]}),a.jsxs("div",{className:"space-y-1 max-h-[calc(100vh-320px)] overflow-y-auto pr-1",children:[j.filter(V=>V.type==="process").map(V=>a.jsx(j3,{setting:V,onClick:()=>O(V),onDuplicate:()=>U(V),compareMode:J,isCompareSelected:K(V)!==void 0,compareIndex:K(V),compareDisabled:J&&!!fe[0]&&fe[0].type!==V.type,t:o},V.setting_id)),j.filter(V=>V.type==="process").length===0&&a.jsx("p",{className:"text-xs text-bambu-gray-dark px-3 py-2",children:o("profiles.cloudView.noProcessPresets")})]})]}),a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center gap-2 mb-3 px-1",children:[a.jsx(Er,{className:"w-4 h-4 text-purple-400"}),a.jsx("h3",{className:"text-sm font-medium text-bambu-gray",children:o("profiles.cloudView.columns.printer")}),a.jsxs("span",{className:"text-xs text-bambu-gray-dark",children:["(",j.filter(V=>V.type==="printer").length,")"]})]}),a.jsxs("div",{className:"space-y-1 max-h-[calc(100vh-320px)] overflow-y-auto pr-1",children:[j.filter(V=>V.type==="printer").map(V=>a.jsx(j3,{setting:V,onClick:()=>O(V),onDuplicate:()=>U(V),compareMode:J,isCompareSelected:K(V)!==void 0,compareIndex:K(V),compareDisabled:J&&!!fe[0]&&fe[0].type!==V.type,t:o},V.setting_id)),j.filter(V=>V.type==="printer").length===0&&a.jsx("p",{className:"text-xs text-bambu-gray-dark px-3 py-2",children:o("profiles.cloudView.noPrinterPresets")})]})]})]}),N&&a.jsx($nt,{setting:N,onClose:()=>A(null),onDeleted:()=>A(null),onDuplicate:()=>U(N),onEdit:()=>ue(N),hasPermission:s,t:o}),(T||H||Q||te)&&a.jsx(Gnt,{onClose:()=>{F(!1),z(null),L(null),ie(null)},initialData:Q||H||(te?{type:te.type,name:"",base_id:"",setting:te.setting}:void 0),allPresets:t,t:o}),k&&a.jsx(Vnt,{onClose:()=>D(!1),onApply:V=>{ie({type:V.type,setting:V.settings}),D(!1)},t:o}),W&&me&&fe[0]&&fe[1]&&a.jsx(Ble,{onClose:()=>{ne(!1),be(null)},leftPreset:me[0],rightPreset:me[1],leftLabel:fe[0].name,rightLabel:fe[1].name,t:o})]})}function Knt(){const{t}=Ft(),e=nn(),{showToast:n}=hn(),{hasPermission:r}=Sr(),[i,s]=w.useState("cloud"),[o,l]=w.useState(),{data:c,isLoading:d}=Xe({queryKey:["cloudStatus"],queryFn:de.getCloudStatus}),{data:u=[]}=Xe({queryKey:["printers"],queryFn:de.getPrinters}),{data:m,isLoading:p,refetch:f,dataUpdatedAt:y}=Xe({queryKey:["cloudSettings"],queryFn:()=>de.getCloudSettings(),enabled:!!c?.is_authenticated,retry:!1,staleTime:1e3*60*5});w.useEffect(()=>{y&&l(new Date(y))},[y]);const v=it({mutationFn:de.cloudLogout,onSuccess:()=>{e.invalidateQueries({queryKey:["cloudStatus"]}),e.removeQueries({queryKey:["cloudSettings"]}),n(t("profiles.toast.loggedOut"))}}),b=()=>{e.invalidateQueries({queryKey:["cloudStatus"]})};return d?a.jsx("div",{className:"p-4 md:p-8 flex items-center justify-center min-h-[400px]",children:a.jsx(pt,{className:"w-8 h-8 text-bambu-green animate-spin"})}):a.jsxs("div",{className:"p-6 lg:p-8",children:[a.jsxs("div",{className:"mb-6",children:[a.jsx("h1",{className:"text-2xl font-bold text-white",children:t("profiles.title")}),a.jsx("p",{className:"text-bambu-gray",children:t("profiles.subtitle")})]}),a.jsxs("div",{className:"flex border-b border-bambu-dark-tertiary mb-6",children:[a.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:[a.jsx(vy,{className:"w-4 h-4"}),t("profiles.tabs.cloud")]}),a.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:[a.jsx(Ig,{className:"w-4 h-4"}),t("profiles.tabs.local")]}),a.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:[a.jsx(Zw,{className:"w-4 h-4"}),t("profiles.tabs.kprofiles")]})]}),i==="cloud"&&a.jsxs(a.Fragment,{children:[c?.is_authenticated&&a.jsxs("div",{className:"flex items-center justify-between p-3 mb-6 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:"w-2 h-2 rounded-full bg-bambu-green animate-pulse"}),a.jsxs("span",{className:"text-sm text-bambu-gray",children:[t("profiles.connectedAs")," ",a.jsx("span",{className:"text-white",children:c.email}),c.region&&a.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")})]})]}),a.jsxs(De,{variant:"secondary",size:"sm",onClick:()=>v.mutate(),disabled:v.isPending||!r("cloud:auth"),title:r("cloud:auth")?void 0:t("profiles.noLogoutPermission"),children:[a.jsx(oF,{className:"w-4 h-4"}),t("profiles.logout")]})]}),c?.is_authenticated?p?a.jsx("div",{className:"flex items-center justify-center py-16",children:a.jsx(pt,{className:"w-8 h-8 text-bambu-green animate-spin"})}):m?a.jsx(Wnt,{settings:m,lastSyncTime:o,onRefresh:()=>f(),isRefreshing:p,printers:u,hasPermission:r,t}):a.jsxs("div",{className:"text-center py-16",children:[a.jsx("p",{className:"text-bambu-gray mb-4",children:t("profiles.failedToLoad")}),a.jsx(De,{onClick:()=>f(),children:t("profiles.retry")})]}):a.jsx(Hnt,{onSuccess:b,t})]}),i==="local"&&a.jsx(Bnt,{}),i==="kprofiles"&&a.jsx(Ont,{}),a.jsx(qnt,{})]})}function Xnt(t,e){const n=(e||"").toUpperCase().replace(/[- ]/g,""),r=n.includes("X1"),i=n.includes("P1"),s=n.includes("A1MINI"),o=n.includes("A1")&&!s,l=n.includes("H2D"),c=n.includes("H2C"),d=n.includes("H2S"),u=l||c||d,m=n.includes("P2S"),p=n.includes("X2D"),f=m||p;switch(t){case"Lubricate Steel Rods":return f?"https://wiki.bambulab.com/en/p2s/maintenance/lubricate-x-y-z-axis":null;case"Clean Steel Rods":return f?"https://wiki.bambulab.com/en/p2s/maintenance/lubricate-x-y-z-axis":null;case"Lubricate Linear Rails":return s?"https://wiki.bambulab.com/en/a1-mini/maintenance/lubricate-y-axis":o?"https://wiki.bambulab.com/en/a1/maintenance/lubricate-y-axis":u?"https://wiki.bambulab.com/en/h2/maintenance/x-axis-lubrication":null;case"Clean Nozzle/Hotend":return r||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 r?"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 r||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 r||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 C0={Droplet:qP,Flame:Hu,Ruler:Ybe,Sparkles:$x,Square:uo,Cable:AO,Wrench:mg,Calendar:na,Timer:jd,Cog:Tfe,Fan:RQ,Zap:uc,Wind:YQ,Thermometer:oS,Layers:da,Box:vi,Target:GQ,RefreshCw:lr,Settings:sS,Filter:VP,CircleDot:cfe};function Z0(t){return t&&C0[t]||mg}function dx(t,e,n){if(e==="days"){if(t<1)return n?n("common.today"):"Today";if(t===1)return n?n("maintenance.day"):"1 day";if(t<7){const i=Math.round(t);return n?n("maintenance.days",{count:i}):`${i} days`}if(t<180){const i=Math.round(t/7);return i===1?n?n("maintenance.week"):"1 week":n?n("maintenance.weeks",{count:i}):`${i} weeks`}const r=Math.round(t/30);return r===1?n?n("maintenance.month"):"1 month":n?n("maintenance.months",{count:r}):`${r} 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 r=t/24;if(r<7)return`${r<2?r.toFixed(1):Math.round(r)}d`;const i=r/7;return i<12?`${i<2?i.toFixed(1):Math.round(i)}w`:`${Math.round(i/4)}mo`}}function M3(t,e,n){return e==="days"?t===1?n?n("maintenance.day"):"1 day":t===7?n?n("maintenance.week"):"1 week":t===14?n?n("maintenance.weeks",{count:2}):"2 weeks":t===30?n?n("maintenance.month"):"1 month":t===60?n?n("maintenance.months",{count:2}):"2 months":t===90?n?n("maintenance.months",{count:3}):"3 months":t===180?n?n("maintenance.months",{count:6}):"6 months":t===365?n?n("maintenance.year"):"1 year":n?n("maintenance.days",{count:t}):`${t} days`:`${t}h`}function Ynt({item:t,onPerform:e,onToggle:n,hasPermission:r,t:i}){const s=Z0(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:dx(Math.abs(f),"days",i)}):t.is_warning?i("maintenance.dueIn",{duration:dx(f,"days",i)}):i("maintenance.timeLeft",{duration:dx(f,"days",i)})}else return t.is_due?i("maintenance.overdueBy",{duration:dx(Math.abs(t.hours_until_due),"hours",i)}):t.is_warning?i("maintenance.dueIn",{duration:dx(t.hours_until_due,"hours",i)}):i("maintenance.timeLeft",{duration:dx(t.hours_until_due,"hours",i)})};return a.jsx("div",{className:`rounded-xl border p-4 transition-all ${m()}`,children:a.jsxs("div",{className:"flex items-start gap-3 max-[550px]:flex-wrap",children:[a.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:[a.jsx(s,{className:`w-5 h-5 ${d()}`}),t.enabled&&(t.is_due||t.is_warning)&&a.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`})]}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("h3",{className:`font-medium truncate ${t.enabled?"text-white":"text-bambu-gray"}`,children:t.maintenance_type_name}),o==="days"&&a.jsx("span",{title:i("maintenance.timeBasedInterval"),children:a.jsx(na,{className:"w-3.5 h-3.5 text-bambu-gray shrink-0"})}),(()=>{const f=t.maintenance_type_wiki_url||Xnt(t.maintenance_type_name,t.printer_model);return f?a.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:y=>y.stopPropagation(),children:a.jsx(la,{className:"w-3.5 h-3.5"})}):null})()]}),a.jsx("div",{className:"mt-2 mb-1.5",children:a.jsx("div",{className:"w-full h-1.5 bg-bambu-dark rounded-full overflow-hidden",children:a.jsx("div",{className:`h-full rounded-full transition-all duration-500 ${u()}`,style:{width:`${c}%`}})})}),a.jsxs("div",{className:`text-xs flex items-center gap-1 ${d()}`,children:[t.is_due&&a.jsx(Dn,{className:"w-3 h-3"}),t.is_warning&&!t.is_due&&a.jsx(Yn,{className:"w-3 h-3"}),!t.is_due&&!t.is_warning&&t.enabled&&a.jsx(Ur,{className:"w-3 h-3"}),p()]})]}),a.jsxs("div",{className:"flex items-center gap-2 shrink-0 max-[550px]:w-full max-[550px]:justify-end max-[550px]:mt-1",children:[a.jsx("span",{title:r("maintenance:update")?void 0:i("maintenance.noPermissionUpdate"),children:a.jsx(Ln,{checked:t.enabled,onChange:f=>n(t.id,f),disabled:!r("maintenance:update")})}),a.jsxs(De,{size:"sm",variant:t.is_due?"primary":"secondary",onClick:()=>e(t.id),disabled:!t.enabled||!r("maintenance:update"),title:r("maintenance:update")?void 0:i("maintenance.noPermissionPerform"),className:"!px-3",children:[a.jsx(co,{className:"w-3.5 h-3.5"}),i("common.reset")]})]})]})})}function Qnt({overview:t,onPerform:e,onToggle:n,onSetHours:r,hasPermission:i,t:s}){const[o,l]=w.useState(!1),[c,d]=w.useState(!1),[u,m]=w.useState(t.total_print_hours.toFixed(1)),p=[...t.maintenance_items].sort((v,b)=>v.is_due&&!b.is_due?-1:!v.is_due&&b.is_due?1:v.is_warning&&!b.is_warning?-1:!v.is_warning&&b.is_warning?1:v.maintenance_type_id-b.maintenance_type_id),f=p.find(v=>v.enabled&&(v.is_due||v.is_warning)),y=()=>{const v=parseFloat(u);!isNaN(v)&&v>=0&&(r(t.printer_id,v),d(!1))};return a.jsxs(Tt,{className:"overflow-hidden",children:[a.jsxs("div",{className:"p-5",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-4",children:[a.jsx("h2",{className:"text-xl font-semibold text-white",children:t.printer_name}),a.jsxs("div",{className:"flex items-center gap-2",children:[t.due_count>0&&a.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:[a.jsx(Dn,{className:"w-3 h-3"}),s("maintenance.overdueCount",{count:t.due_count})]}),t.warning_count>0&&a.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:[a.jsx(Yn,{className:"w-3 h-3"}),s("maintenance.dueSoonCount",{count:t.warning_count})]}),t.due_count===0&&t.warning_count===0&&a.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:[a.jsx(Ur,{className:"w-3 h-3"}),s("maintenance.allGood")]})]})]}),a.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?a.jsx(dc,{className:"w-4 h-4"}):a.jsx(On,{className:"w-4 h-4"}),s(o?"common.collapse":"common.expand")]})]}),a.jsxs("div",{className:"flex items-center gap-6 mt-4",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:"p-2 bg-bambu-dark/50 rounded-lg",children:a.jsx(jd,{className:"w-4 h-4 text-bambu-gray"})}),c?a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("input",{type:"number",value:u,onChange:v=>m(v.target.value),onKeyDown:v=>{v.key==="Enter"&&y(),v.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}),a.jsx("span",{className:"text-xs text-bambu-gray",children:s("common.hours")}),a.jsx(De,{size:"sm",onClick:y,children:s("common.save")}),a.jsx(De,{size:"sm",variant:"secondary",onClick:()=>d(!1),children:s("common.cancel")})]}):a.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:[a.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"),a.jsx(dg,{className:`w-3 h-3 text-bambu-gray ${i("maintenance:update")?"group-hover:text-bambu-green":""}`})]}),a.jsx("div",{className:"text-xs text-bambu-gray",children:s("maintenance.totalPrintTime")})]})]}),a.jsx("div",{className:"w-px h-10 bg-bambu-dark-tertiary"}),f&&a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:`p-2 rounded-lg ${f.is_due?"bg-red-500/20":"bg-amber-500/20"}`,children:(()=>{const v=Z0(f.maintenance_type_icon);return a.jsx(v,{className:`w-4 h-4 ${f.is_due?"text-red-400":"text-amber-400"}`})})()}),a.jsxs("div",{children:[a.jsx("div",{className:`text-sm font-medium ${f.is_due?"text-red-400":"text-amber-400"}`,children:f.maintenance_type_name}),a.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&&a.jsx(Mt,{className:"pt-0 border-t border-bambu-dark-tertiary",children:a.jsx("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-3 pt-4",children:p.map(v=>a.jsx(Ynt,{item:v,onPerform:e,onToggle:n,hasPermission:i,t:s},v.id))})})]})}function Znt({overview:t,types:e,onUpdateInterval:n,onAddType:r,onUpdateType:i,onDeleteType:s,onRestoreDefaults:o,isRestoringDefaults:l,onAssignType:c,onRemoveItem:d,hasPermission:u,t:m}){const[p,f]=w.useState(null),[y,v]=w.useState(""),[b,g]=w.useState("hours"),[_,C]=w.useState(!1),[P,N]=w.useState(""),[A,T]=w.useState("100"),[F,k]=w.useState("hours"),[D,H]=w.useState("Wrench"),[z,Q]=w.useState(""),[L,te]=w.useState(new Set),[ie,J]=w.useState(null),[oe,fe]=w.useState(null),re=w.useMemo(()=>t?t.map(B=>({id:B.printer_id,name:B.printer_name})):[],[t]),W=B=>t?t.filter(R=>R.maintenance_items.some(ae=>ae.maintenance_type_id===B)).map(R=>({printerId:R.printer_id,printerName:R.printer_name,itemId:R.maintenance_items.find(ae=>ae.maintenance_type_id===B)?.id})):[],ne=B=>{if(!t)return[];const R=new Set(W(B).map(ae=>ae.printerId));return re.filter(ae=>!R.has(ae.id))},[me,be]=w.useState(null),[Ce,q]=w.useState(""),[Y,E]=w.useState(""),[j,O]=w.useState("hours"),[K,U]=w.useState("Wrench"),[ue,I]=w.useState(""),G=B=>{be(B),q(B.name),E(B.default_interval_hours.toString()),O(B.interval_type||"hours"),U(B.icon||"Wrench"),I(B.wiki_url||"")},X=()=>{me&&Ce.trim()&&parseFloat(Y)>0&&(i(me.id,{name:Ce.trim(),default_interval_hours:parseFloat(Y),interval_type:j,icon:K,wiki_url:ue.trim()||null}),be(null))},V=(B,R,ae)=>{const _e=parseFloat(y);if(!isNaN(_e)&&_e>0){const Se=Math.abs(_e-R)<.01?null:_e;n(B,{custom_interval_hours:Se,custom_interval_type:b!==ae?b:null})}f(null)},ee=B=>{B.preventDefault(),P.trim()&&parseFloat(A)>0&&L.size>0&&(r({name:P.trim(),default_interval_hours:parseFloat(A),interval_type:F,icon:D,wiki_url:z.trim()||null},Array.from(L)),N(""),T("100"),k("hours"),Q(""),te(new Set),C(!1))},se=B=>{te(R=>{const ae=new Set(R);return ae.has(B)?ae.delete(B):ae.add(B),ae})},ge=t?.map(B=>({printerId:B.printer_id,printerName:B.printer_name,items:B.maintenance_items.sort((R,ae)=>R.maintenance_type_id-ae.maintenance_type_id)})).sort((B,R)=>B.printerName.localeCompare(R.printerName))||[],he=e.filter(B=>B.is_system),le=e.filter(B=>!B.is_system);return a.jsxs("div",{className:"space-y-8",children:[a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center justify-between mb-4",children:[a.jsxs("div",{children:[a.jsx("h2",{className:"text-lg font-semibold text-white",children:m("maintenance.maintenanceTypes")}),a.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:m("maintenance.maintenanceTypesDescription")})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(De,{variant:"secondary",onClick:o,disabled:!u("maintenance:delete")||l,title:u("maintenance:delete")?void 0:m("maintenance.noPermissionDeleteTypes"),children:m("maintenance.restoreDefaults")}),a.jsxs(De,{onClick:()=>C(!_),disabled:!u("maintenance:create"),title:u("maintenance:create")?void 0:m("maintenance.noPermissionEditTypes"),children:[a.jsx(sr,{className:"w-4 h-4"}),m("maintenance.addCustomType")]})]})]}),_&&a.jsx(Tt,{className:"mb-6",children:a.jsx(Mt,{className:"py-4",children:a.jsxs("form",{onSubmit:ee,children:[a.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4",children:[a.jsxs("div",{className:"lg:col-span-2",children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:m("common.name")}),a.jsx("input",{type:"text",value:P,onChange:B=>N(B.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})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:m("maintenance.intervalType")}),a.jsxs("select",{value:F,onChange:B=>{k(B.target.value),B.target.value==="days"?T("30"):T("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:[a.jsx("option",{value:"hours",children:m("maintenance.printHours")}),a.jsx("option",{value:"days",children:m("maintenance.calendarDays")})]})]}),a.jsxs("div",{children:[a.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")})}),a.jsx("input",{type:"number",value:A,onChange:B=>T(B.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"})]})]}),a.jsx("div",{className:"mt-4 flex items-end justify-between",children:a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:m("maintenance.icon")}),a.jsx("div",{className:"flex gap-1",children:Object.keys(C0).map(B=>{const R=C0[B];return a.jsx("button",{type:"button",onClick:()=>H(B),className:`p-2 rounded-lg transition-colors ${D===B?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary"}`,children:a.jsx(R,{className:"w-4 h-4"})},B)})})]})}),a.jsxs("div",{className:"mt-4",children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:m("maintenance.documentationLink")}),a.jsx("input",{type:"url",value:z,onChange:B=>Q(B.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/..."})]}),a.jsxs("div",{className:"mt-4",children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:m("maintenance.assignToPrinters")}),a.jsx("div",{className:"flex flex-wrap gap-2",children:re.map(B=>a.jsx("button",{type:"button",onClick:()=>se(B.id),className:`px-3 py-1.5 rounded-lg text-sm transition-colors ${L.has(B.id)?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary"}`,children:B.name},B.id))}),L.size===0&&a.jsx("p",{className:"text-xs text-orange-400 mt-1",children:m("maintenance.selectAtLeastOnePrinter")})]}),a.jsxs("div",{className:"mt-4 flex justify-end gap-2",children:[a.jsx(De,{type:"button",variant:"secondary",onClick:()=>{C(!1),te(new Set)},children:m("common.cancel")}),a.jsx(De,{type:"submit",disabled:!P.trim()||L.size===0,children:m("maintenance.addType")})]})]})})}),a.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3",children:[he.map(B=>{const R=Z0(B.icon),ae=B.interval_type||"hours";return a.jsx("div",{className:"bg-bambu-dark-secondary rounded-xl p-4 border border-bambu-dark-tertiary",children:a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:"p-2.5 bg-bambu-dark rounded-lg",children:a.jsx(R,{className:"w-5 h-5 text-bambu-gray"})}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("div",{className:"text-sm font-medium text-white truncate",children:B.name}),a.jsxs("div",{className:"text-xs text-bambu-gray mt-0.5 flex items-center gap-1",children:[ae==="days"?a.jsx(na,{className:"w-3 h-3"}):a.jsx(jd,{className:"w-3 h-3"}),M3(B.default_interval_hours,ae,m)]})]}),a.jsx("button",{onClick:()=>{u("maintenance:delete")&&fe(B)},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:a.jsx(en,{className:"w-4 h-4"})})]})},B.id)}),le.map(B=>{const R=Z0(B.icon),ae=B.interval_type||"hours";if(me?.id===B.id)return a.jsx("div",{className:"bg-bambu-dark-secondary rounded-xl p-4 border border-bambu-green",children:a.jsxs("div",{className:"space-y-3",children:[a.jsx("input",{type:"text",value:Ce,onChange:ye=>q(ye.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}),a.jsxs("div",{className:"flex gap-2",children:[a.jsxs("select",{value:j,onChange:ye=>O(ye.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:[a.jsx("option",{value:"hours",children:m("maintenance.printHours")}),a.jsx("option",{value:"days",children:m("maintenance.calendarDays")})]}),a.jsx("input",{type:"number",value:Y,onChange:ye=>E(ye.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"})]}),a.jsx("div",{className:"flex flex-wrap gap-1",children:Object.keys(C0).map(ye=>{const Ae=C0[ye];return a.jsx("button",{type:"button",onClick:()=>U(ye),className:`p-1.5 rounded transition-colors ${K===ye?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:a.jsx(Ae,{className:"w-3.5 h-3.5"})},ye)})}),a.jsx("input",{type:"url",value:ue,onChange:ye=>I(ye.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")}),a.jsxs("div",{className:"flex gap-2",children:[a.jsx(De,{size:"sm",onClick:X,disabled:!Ce.trim(),children:m("common.save")}),a.jsx(De,{size:"sm",variant:"secondary",onClick:()=>be(null),children:m("common.cancel")})]})]})},B.id);const Se=W(B.id),ve=ne(B.id),Te=ie===B.id;return a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-xl p-4 border border-bambu-green/30",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:"p-2.5 bg-bambu-green/20 rounded-lg",children:a.jsx(R,{className:"w-5 h-5 text-bambu-green"})}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:"text-sm font-medium text-white truncate",children:B.name}),a.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")})]}),a.jsxs("div",{className:"text-xs text-bambu-gray mt-0.5 flex items-center gap-1",children:[ae==="days"?a.jsx(na,{className:"w-3 h-3"}):a.jsx(jd,{className:"w-3 h-3"}),M3(B.default_interval_hours,ae,m)]})]}),a.jsxs("button",{onClick:()=>J(Te?null:B.id),className:`px-2 py-1 rounded-lg border transition-colors flex items-center gap-1 ${Se.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:Se.length}),children:[a.jsx(Er,{className:"w-3 h-3"}),a.jsx("span",{className:"text-xs font-medium",children:Se.length}),a.jsx(On,{className:`w-3 h-3 transition-transform ${Te?"rotate-180":""}`})]}),a.jsx("button",{onClick:()=>G(B),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:a.jsx(dg,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>{confirm(m("maintenance.deleteTypeConfirm",{name:B.name}))&&s(B.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:a.jsx(en,{className:"w-4 h-4"})})]}),Te&&a.jsxs("div",{className:"mt-3 pt-3 border-t border-bambu-dark-tertiary",children:[a.jsx("p",{className:"text-xs text-bambu-gray mb-2",children:m("maintenance.assignedToPrinters")}),Se.length===0?a.jsx("p",{className:"text-xs text-orange-400",children:m("maintenance.noPrintersAssigned")}):a.jsx("div",{className:"flex flex-wrap gap-1 mb-2",children:Se.map(ye=>a.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-1 bg-bambu-dark rounded text-xs text-white",children:[ye.printerName,a.jsx("button",{onClick:()=>ye.itemId&&d(ye.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:"×"})]},ye.printerId))}),ve.length>0&&a.jsxs("div",{className:"flex flex-wrap gap-1",children:[a.jsx("span",{className:"text-xs text-bambu-gray mr-1",children:m("maintenance.addPrinterShort")}),ve.map(ye=>a.jsxs("button",{onClick:()=>c(ye.id,B.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:["+ ",ye.name]},ye.id))]})]})]},B.id)})]})]}),ge.length>0&&a.jsxs("div",{children:[a.jsxs("div",{className:"mb-4",children:[a.jsx("h2",{className:"text-lg font-semibold text-white",children:m("maintenance.intervalOverrides")}),a.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:m("maintenance.intervalOverridesDescription")})]}),a.jsx("div",{className:"space-y-4",children:ge.map(B=>a.jsx(Tt,{children:a.jsxs(Mt,{className:"py-4",children:[a.jsx("h3",{className:"text-sm font-medium text-white mb-3",children:B.printerName}),a.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-2",children:B.items.map(R=>{const ae=Z0(R.maintenance_type_icon),_e=e.find(Ae=>Ae.id===R.maintenance_type_id),Se=_e?.default_interval_hours||R.interval_hours,ve=_e?.interval_type||"hours",Te=R.interval_type||"hours",ye=p===R.id;return a.jsxs("div",{className:"flex items-center gap-2 p-2.5 bg-bambu-dark rounded-lg",children:[a.jsx(ae,{className:"w-4 h-4 text-bambu-gray shrink-0"}),a.jsx("span",{className:"text-xs text-bambu-gray flex-1 truncate",children:R.maintenance_type_name}),ye?a.jsxs("div",{className:"flex items-center gap-1",children:[b==="days"?a.jsx(na,{className:"w-3.5 h-3.5 text-bambu-gray shrink-0"}):a.jsx(jd,{className:"w-3.5 h-3.5 text-bambu-gray shrink-0"}),a.jsxs("select",{value:b,onChange:Ae=>g(Ae.target.value),className:"px-1.5 py-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-xs",children:[a.jsx("option",{value:"hours",children:m("maintenance.printHours")}),a.jsx("option",{value:"days",children:m("maintenance.calendarDays")})]}),a.jsx("input",{type:"number",value:y,onChange:Ae=>v(Ae.target.value),onKeyDown:Ae=>{Ae.key==="Enter"&&V(R.id,Se,ve),Ae.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"}),a.jsx(De,{size:"sm",onClick:()=>V(R.id,Se,ve),children:"OK"})]}):a.jsxs("button",{onClick:()=>{u("maintenance:update")&&(f(R.id),v(R.interval_hours.toString()),g(Te))},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:[Te==="days"?a.jsx(na,{className:"w-3 h-3"}):a.jsx(jd,{className:"w-3 h-3"}),M3(R.interval_hours,Te,m),a.jsx(dg,{className:"w-3 h-3 text-bambu-gray"})]})]},R.id)})})]})},B.printerId))})]}),ge.length===0&&a.jsx(Tt,{children:a.jsxs(Mt,{className:"text-center py-12",children:[a.jsx(Yn,{className:"w-12 h-12 mx-auto mb-4 text-bambu-gray/30"}),a.jsx("p",{className:"text-bambu-gray",children:m("common.noPrinters")}),a.jsx("p",{className:"text-sm text-bambu-gray/70 mt-1",children:m("maintenance.intervalOverridesDescription")})]})}),oe&&a.jsx(yn,{title:m("maintenance.deleteSystemTypeTitle"),message:m("maintenance.deleteSystemTypeMessage",{name:oe.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(oe.id),fe(null)},onCancel:()=>fe(null)})]})}function Jnt(){const{t}=Ft(),e=nn(),{showToast:n}=hn(),{hasPermission:r}=Sr(),[i,s]=w.useState("status"),{data:o,isLoading:l}=Xe({queryKey:["maintenanceOverview"],queryFn:de.getMaintenanceOverview}),{data:c}=Xe({queryKey:["maintenanceTypes"],queryFn:de.getMaintenanceTypes}),d=it({mutationFn:({id:A,notes:T})=>de.performMaintenance(A,T),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]}),e.invalidateQueries({queryKey:["maintenanceSummary"]}),n(t("maintenance.maintenanceComplete"))},onError:A=>{n(A.message,"error")}}),u=it({mutationFn:({id:A,data:T})=>de.updateMaintenanceItem(A,T),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]})},onError:A=>{n(A.message,"error")}}),m=it({mutationFn:({id:A,data:T})=>de.updateMaintenanceType(A,T),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceTypes"]}),e.invalidateQueries({queryKey:["maintenanceOverview"]}),n(t("maintenance.typeUpdated"))},onError:A=>{n(A.message,"error")}}),p=it({mutationFn:de.deleteMaintenanceType,onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceTypes"]}),e.invalidateQueries({queryKey:["maintenanceOverview"]}),n(t("maintenance.typeDeleted"))},onError:A=>{n(A.message,"error")}}),f=it({mutationFn:de.restoreDefaultMaintenanceTypes,onSuccess:A=>{e.invalidateQueries({queryKey:["maintenanceTypes"]}),e.invalidateQueries({queryKey:["maintenanceOverview"]}),n(t("maintenance.defaultsRestored",{count:A.restored}))},onError:A=>{n(A.message,"error")}}),y=it({mutationFn:({printerId:A,hours:T})=>de.setPrinterHours(A,T),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]}),e.invalidateQueries({queryKey:["maintenanceSummary"]}),n(t("maintenance.printHoursUpdated"))},onError:A=>{n(A.message,"error")}}),v=it({mutationFn:({printerId:A,typeId:T})=>de.assignMaintenanceType(A,T),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]}),n(t("maintenance.printerAssigned"))},onError:A=>{n(A.message,"error")}}),b=it({mutationFn:de.removeMaintenanceItem,onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]}),n(t("maintenance.printerRemoved"))},onError:A=>{n(A.message,"error")}}),g=A=>{d.mutate({id:A})},_=(A,T)=>{u.mutate({id:A,data:{enabled:T}})},C=(A,T)=>{y.mutate({printerId:A,hours:T})};if(l)return a.jsx("div",{className:"p-4 md:p-8 flex justify-center",children:a.jsx(pt,{className:"w-8 h-8 text-bambu-green animate-spin"})});const P=o?.reduce((A,T)=>A+T.due_count,0)||0,N=o?.reduce((A,T)=>A+T.warning_count,0)||0;return a.jsxs("div",{className:"p-4 md:p-8",children:[a.jsxs("div",{className:"mb-6",children:[a.jsx("h1",{className:"text-2xl font-bold text-white",children:t("maintenance.title")}),a.jsx("p",{className:"text-bambu-gray text-sm mt-1",children:i==="status"?a.jsxs(a.Fragment,{children:[P>0&&a.jsx("span",{className:"text-red-400",children:t("maintenance.dueCount",{count:P})}),P>0&&N>0&&" · ",N>0&&a.jsx("span",{className:"text-amber-400",children:t("maintenance.warningCount",{count:N})}),P===0&&N===0&&a.jsx("span",{className:"text-bambu-green",children:t("maintenance.allOk")})]}):t("maintenance.configureSettings")})]}),a.jsxs("div",{className:"flex gap-1 mb-6 border-b border-bambu-dark-tertiary",children:[a.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")}),a.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"?a.jsx("div",{className:"space-y-6",children:o&&o.length>0?[...o].sort((A,T)=>{const F=A.due_count*10+A.warning_count,k=T.due_count*10+T.warning_count;return F!==k?k-F:A.printer_name.localeCompare(T.printer_name)}).map(A=>a.jsx(Qnt,{overview:A,onPerform:g,onToggle:_,onSetHours:C,hasPermission:r,t},A.printer_id)):a.jsx(Tt,{children:a.jsxs(Mt,{className:"text-center py-16",children:[a.jsx(mg,{className:"w-16 h-16 mx-auto mb-4 text-bambu-gray/30"}),a.jsx("p",{className:"text-lg font-medium text-white mb-2",children:t("common.noPrinters")}),a.jsx("p",{className:"text-bambu-gray",children:t("maintenance.configureSettings")})]})})}):a.jsx(Znt,{overview:o,types:c||[],onUpdateInterval:(A,T)=>u.mutate({id:A,data:T}),onAddType:async(A,T)=>{const F=await de.createMaintenanceType(A);for(const k of T)await de.assignMaintenanceType(k,F.id);e.invalidateQueries({queryKey:["maintenanceTypes"]}),e.invalidateQueries({queryKey:["maintenanceOverview"]}),n(t("maintenance.typeUpdated"))},onUpdateType:(A,T)=>m.mutate({id:A,data:T}),onDeleteType:A=>p.mutate(A),onRestoreDefaults:()=>f.mutate(),isRestoringDefaults:f.isPending,onAssignType:(A,T)=>v.mutate({printerId:A,typeId:T}),onRemoveItem:A=>b.mutate(A),hasPermission:r,t})]})}const _Y=["#ef4444","#f97316","#eab308","#22c55e","#06b6d4","#3b82f6","#8b5cf6","#ec4899","#6b7280"];function Hle({project:t,onClose:e,onSave:n,isLoading:r,currencySymbol:i,t:s}){const[o,l]=w.useState(t?.name||""),[c,d]=w.useState(t?.description||""),[u,m]=w.useState(t?.color||_Y[0]),[p,f]=w.useState(t?.target_count?.toString()||""),[y,v]=w.useState(t?.target_parts_count?.toString()||""),[b,g]=w.useState(t?.status||"active"),[_,C]=w.useState(t?.tags||""),[P,N]=w.useState(t?.due_date?.split("T")[0]||""),[A,T]=w.useState(t?.priority||"normal"),[F,k]=w.useState(t?.budget?.toString()||""),D=H=>{H.preventDefault(),n({name:o.trim(),description:c.trim()||void 0,color:u,target_count:p?parseInt(p,10):void 0,target_parts_count:y?parseInt(y,10):void 0,tags:_.trim()||void 0,due_date:P||void 0,priority:A,budget:F.trim()?parseFloat(F):null,...t&&{status:b}})};return a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-md border border-bambu-dark-tertiary",children:[a.jsx("div",{className:"p-4 border-b border-bambu-dark-tertiary",children:a.jsx("h2",{className:"text-lg font-semibold text-white",children:s(t?"projects.editProject":"projects.newProject")})}),a.jsxs("form",{onSubmit:D,className:"p-4 space-y-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("common.name")}),a.jsx("input",{type:"text",value:o,onChange:H=>l(H.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})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("common.description")}),a.jsx("textarea",{value:c,onChange:H=>d(H.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})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("projects.color")}),a.jsx("div",{className:"flex gap-2 flex-wrap",children:_Y.map(H=>a.jsx("button",{type:"button",onClick:()=>m(H),className:`w-8 h-8 rounded-full transition-transform ${u===H?"ring-2 ring-white ring-offset-2 ring-offset-bambu-dark-secondary scale-110":""}`,style:{backgroundColor:H}},H))})]}),a.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("projects.targetPlates")}),a.jsx("input",{type:"number",value:p,onChange:H=>f(H.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"}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:s("projects.targetPlatesHelp")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("projects.targetParts")}),a.jsx("input",{type:"number",value:y,onChange:H=>v(H.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"}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:s("projects.targetPartsHelp")})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("projects.tagsLabel")}),a.jsx("input",{type:"text",value:_,onChange:H=>C(H.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")})]}),a.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("projects.dueDate")}),a.jsx("input",{type:"date",value:P,onChange:H=>N(H.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"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("projects.priority")}),a.jsxs("select",{value:A,onChange:H=>T(H.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:[a.jsx("option",{value:"low",children:s("projects.priorityLow")}),a.jsx("option",{value:"normal",children:s("projects.priorityNormal")}),a.jsx("option",{value:"high",children:s("projects.priorityHigh")}),a.jsx("option",{value:"urgent",children:s("projects.priorityUrgent")})]})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("projectDetail.cost.budget")}),a.jsxs("div",{className:"relative",children:[a.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-bambu-gray pointer-events-none",children:i}),a.jsx("input",{type:"number",step:"0.01",min:"0",value:F,onChange:H=>k(H.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&&a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("common.status")}),a.jsxs("select",{value:b,onChange:H=>g(H.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:[a.jsx("option",{value:"active",children:s("projects.statusActive")}),a.jsx("option",{value:"completed",children:s("projects.statusCompleted")}),a.jsx("option",{value:"archived",children:s("projects.statusArchived")})]})]}),a.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[a.jsx(De,{type:"button",variant:"secondary",onClick:e,children:s("common.cancel")}),a.jsx(De,{type:"submit",disabled:!o.trim()||r,children:r?a.jsx(pt,{className:"w-4 h-4 animate-spin"}):s(t?"common.save":"projects.create")})]})]})]})})}function ert({project:t,onClick:e,onEdit:n,onDelete:r,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]=w.useState(!1),f=c?{icon:ul,color:"text-bambu-green",bg:"bg-bambu-green/10"}:d?{icon:so,color:"text-bambu-gray",bg:"bg-bambu-gray/10"}:t.queue_count>0?{icon:Yn,color:"text-blue-400",bg:"bg-blue-400/10"}:{icon:Bs,color:"text-bambu-gray",bg:"bg-bambu-gray/10"};return a.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:[a.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`}}),a.jsxs("div",{className:"p-5 pl-6",children:[a.jsxs("div",{className:"flex items-start justify-between mb-4",children:[a.jsxs("div",{className:"flex items-center gap-3 min-w-0 flex-1",children:[a.jsx("div",{className:`p-2 rounded-lg ${f.bg} flex-shrink-0`,children:a.jsx(f.icon,{className:`w-5 h-5 ${f.color}`})}),a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[a.jsx("h3",{className:"font-semibold text-white truncate",children:t.name}),t.target_parts_count?a.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?a.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?a.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&&a.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&&a.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&&a.jsx("p",{className:"text-sm text-bambu-gray/70 mt-1 line-clamp-1",children:t.description}),t.archives&&t.archives.length>0&&(()=>{const y=t.archives.map(_=>_.filament_type).filter(Boolean).flatMap(_=>_.split(",").map(C=>C.trim())).filter(Boolean),v=[...new Set(y)],b=t.archives.map(_=>_.filament_color).filter(Boolean).flatMap(_=>_.split(",").map(C=>C.trim())).filter(_=>_.startsWith("#")||/^[0-9A-Fa-f]{6}$/.test(_)),g=[...new Set(b)];return v.length===0&&g.length===0?null:a.jsxs("div",{className:"flex items-center gap-2 mt-1.5",children:[v.slice(0,3).map(_=>a.jsx("span",{className:"text-[10px] px-1.5 py-0.5 bg-bambu-dark text-bambu-gray rounded",children:_},_)),g.length>0&&a.jsxs("div",{className:"flex items-center gap-0.5",children:[g.slice(0,5).map(_=>a.jsx("div",{className:"w-3 h-3 rounded-full border border-black/20",style:{backgroundColor:_.startsWith("#")?_:`#${_}`},title:_},_)),g.length>5&&a.jsxs("span",{className:"text-[10px] text-bambu-gray ml-0.5",children:["+",g.length-5]})]})]})})()]})]}),a.jsxs("div",{className:"relative",onClick:y=>y.stopPropagation(),children:[a.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:a.jsx(Jh,{className:"w-4 h-4"})}),u&&a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>m(!1)}),a.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:[a.jsxs("button",{className:`w-full px-3 py-2 text-left text-sm flex items-center gap-2 ${i("projects:update")?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{i("projects:update")&&(n(),m(!1))},disabled:!i("projects:update"),title:i("projects:update")?void 0:s("projects.noEditPermission"),children:[a.jsx(dg,{className:"w-4 h-4"}),s("common.edit")]}),a.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")&&(r(),m(!1))},disabled:!i("projects:delete"),title:i("projects:delete")?void 0:s("projects.noDeletePermission"),children:[a.jsx(en,{className:"w-4 h-4"}),s("common.delete")]})]})]})]})]}),a.jsx("div",{className:"mb-4",children:t.target_count||t.target_parts_count?a.jsxs("div",{className:"space-y-3",children:[t.target_count&&a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center justify-between text-xs mb-1",children:[a.jsx("span",{className:"text-bambu-gray",children:s("projects.plates")}),a.jsxs("span",{className:o>=100?"text-bambu-green font-medium":"text-white",children:[t.archive_count," / ",t.target_count]})]}),a.jsx("div",{className:"h-2 bg-bambu-dark/80 rounded-full overflow-hidden backdrop-blur-sm",children:a.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&&a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center justify-between text-xs mb-1",children:[a.jsx("span",{className:"text-bambu-gray",children:s("projects.parts")}),a.jsxs("span",{className:l>=100?"text-bambu-green font-medium":"text-white",children:[t.completed_count," / ",t.target_parts_count]})]}),a.jsx("div",{className:"h-2 bg-bambu-dark/80 rounded-full overflow-hidden backdrop-blur-sm",children:a.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&&a.jsxs("div",{className:"text-xs text-red-400",children:[t.failed_count," ",s("projects.failed")]})]}):t.completed_count>0||t.failed_count>0?a.jsxs("div",{className:"flex items-center gap-4 text-xs",children:[t.completed_count>0&&a.jsxs("div",{className:"flex items-center gap-1.5 text-bambu-gray",children:[a.jsx(so,{className:"w-3.5 h-3.5"}),a.jsxs("span",{children:[t.completed_count," ",s("projects.completed")]})]}),t.failed_count>0&&a.jsxs("div",{className:"flex items-center gap-1.5 text-red-400",children:[a.jsx(Dn,{className:"w-3.5 h-3.5"}),a.jsxs("span",{children:[t.failed_count," ",s("projects.failed")]})]}),t.queue_count>0&&a.jsxs("div",{className:"flex items-center gap-1.5 text-blue-400",children:[a.jsx(Yn,{className:"w-3.5 h-3.5"}),a.jsxs("span",{children:[t.queue_count," ",s("projects.inQueue")]})]})]}):a.jsx("div",{className:"text-xs text-bambu-gray/60 italic",children:s("projects.noPrintsYet")})}),t.archives&&t.archives.length>0&&a.jsxs("div",{className:"mb-4",children:[a.jsx("div",{className:"grid grid-cols-4 gap-1.5",children:t.archives.slice(0,4).map(y=>a.jsxs("div",{className:"relative aspect-square rounded-lg bg-bambu-dark overflow-hidden border border-bambu-dark-tertiary",title:y.print_name||"Unknown",children:[y.thumbnail_path?a.jsx("img",{src:de.getArchiveThumbnail(y.id),alt:y.print_name||"",className:"w-full h-full object-cover"}):a.jsx("div",{className:"w-full h-full flex items-center justify-center text-bambu-gray/50",children:a.jsx(Ra,{className:"w-6 h-6"})}),y.status==="failed"&&a.jsx("div",{className:"absolute inset-0 bg-red-500/40 flex items-center justify-center",children:a.jsx(Dn,{className:"w-4 h-4 text-white"})})]},y.id))}),t.archive_count>4&&a.jsx("p",{className:"text-xs text-bambu-gray mt-1.5 text-center",children:s("common.more",{count:t.archive_count-4})})]}),a.jsxs("div",{className:"flex items-center justify-between pt-3 border-t border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-4 text-xs text-bambu-gray",children:[a.jsxs("div",{className:"flex items-center gap-1.5",title:s("projects.printJobs"),children:[a.jsx(da,{className:"w-3.5 h-3.5 text-blue-400"}),a.jsxs("span",{children:[t.archive_count," ",s("projects.plates")]})]}),a.jsxs("div",{className:"flex items-center gap-1.5",title:s("projects.partsPrinted"),children:[a.jsx(Ra,{className:"w-3.5 h-3.5 text-bambu-green"}),a.jsxs("span",{children:[t.completed_count," ",s("projects.parts")]})]}),t.failed_count>0&&a.jsxs("div",{className:"flex items-center gap-1.5 text-red-400",title:s("projects.failedParts"),children:[a.jsx(Dn,{className:"w-3.5 h-3.5"}),a.jsx("span",{children:t.failed_count})]}),t.queue_count>0&&a.jsxs("div",{className:"flex items-center gap-1.5 text-yellow-400",title:s("projects.inQueue"),children:[a.jsx(sF,{className:"w-3.5 h-3.5"}),a.jsx("span",{children:t.queue_count})]})]}),a.jsx(ti,{className:"w-4 h-4 text-bambu-gray/50 group-hover:text-bambu-gray transition-colors"})]})]})]})}function trt(){const{t}=Ft(),e=qo(),n=nn(),{showToast:r}=hn(),{hasPermission:i}=Sr(),[s,o]=w.useState(!1),[l,c]=w.useState(),[d,u]=w.useState("active"),[m,p]=w.useState(null),{data:f}=Xe({queryKey:["settings"],queryFn:de.getSettings}),y=Eo(f?.currency||"USD"),{data:v,isLoading:b}=Xe({queryKey:["projects",d==="all"?void 0:d],queryFn:()=>de.getProjects(d==="all"?void 0:d)}),g=it({mutationFn:te=>de.createProject(te),onSuccess:()=>{n.invalidateQueries({queryKey:["projects"]}),o(!1),r(t("projects.toast.created"),"success")},onError:te=>{r(te.message,"error")}}),_=it({mutationFn:({id:te,data:ie})=>de.updateProject(te,ie),onSuccess:()=>{n.invalidateQueries({queryKey:["projects"]}),o(!1),c(void 0),r(t("projects.toast.updated"),"success")},onError:te=>{r(te.message,"error")}}),C=it({mutationFn:te=>de.deleteProject(te),onSuccess:()=>{p(null),r(t("projects.toast.deleted"),"success"),setTimeout(()=>window.location.reload(),100)},onError:te=>{p(null),r(te.message,"error")}}),P=it({mutationFn:te=>de.importProject(te),onSuccess:()=>{n.invalidateQueries({queryKey:["projects"]}),r(t("projects.toast.imported"),"success")},onError:te=>{r(te.message,"error")}}),N=w.useRef(null),A=async()=>{try{const te=await de.getProjects(),ie=await Promise.all(te.map(async re=>await de.exportProjectJson(re.id))),J=new Blob([JSON.stringify(ie,null,2)],{type:"application/json"}),oe=URL.createObjectURL(J),fe=document.createElement("a");fe.href=oe,fe.download=`bambuddy_projects_${new Date().toISOString().split("T")[0]}.json`,fe.click(),URL.revokeObjectURL(oe),r(t("projects.toast.exported"),"success")}catch(te){r(te.message,"error")}},T=()=>{N.current?.click()},F=async te=>{const ie=te.target.files?.[0];if(ie){try{if(ie.name.toLowerCase().endsWith(".zip"))await de.importProjectFile(ie),n.invalidateQueries({queryKey:["projects"]}),r(t("projects.toast.imported"),"success");else{const oe=await ie.text(),fe=JSON.parse(oe),re=Array.isArray(fe)?fe:[fe];for(const W of re)await P.mutateAsync(W);re.length>1&&r(t("projects.toast.multipleImported",{count:re.length}),"success")}}catch(J){r(`${t("projects.toast.importFailed")}: ${J.message}`,"error")}te.target.value=""}},k=te=>{l?_.mutate({id:l.id,data:te}):g.mutate(te)},D=te=>{c(te),o(!0)},H=te=>{e(`/projects/${te.id}`)},z=te=>{p(te)},Q=()=>{m!==null&&C.mutate(m)},L=v?.reduce((te,ie)=>(te[ie.status]=(te[ie.status]||0)+1,te.all=(te.all||0)+1,te),{})||{};return a.jsxs("div",{className:"p-4 md:p-8 space-y-8",children:[a.jsx("input",{ref:N,type:"file",accept:".json,.zip",onChange:F,className:"hidden"}),a.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4",children:[a.jsxs("div",{children:[a.jsxs("h1",{className:"text-2xl font-bold text-white flex items-center gap-3",children:[a.jsx("div",{className:"p-2.5 bg-bambu-green/10 rounded-xl",children:a.jsx(Bs,{className:"w-6 h-6 text-bambu-green"})}),t("projects.title")]}),a.jsx("p",{className:"text-sm text-bambu-gray mt-2 ml-14",children:t("projects.subtitle")})]}),a.jsxs("div",{className:"flex gap-2",children:[a.jsxs(De,{variant:"secondary",onClick:T,disabled:!i("projects:create"),title:i("projects:create")?t("projects.importProject"):t("projects.noImportPermission"),children:[a.jsx(La,{className:"w-4 h-4 mr-2"}),t("projects.import")]}),a.jsxs(De,{variant:"secondary",onClick:A,disabled:!i("projects:read"),title:i("projects:read")?t("projects.exportAll"):t("projects.noExportPermission"),children:[a.jsx(ga,{className:"w-4 h-4 mr-2"}),t("projects.export")]}),a.jsxs(De,{onClick:()=>o(!0),className:"sm:w-auto w-full",disabled:!i("projects:create"),title:i("projects:create")?void 0:t("projects.noCreatePermission"),children:[a.jsx(sr,{className:"w-4 h-4 mr-2"}),t("projects.newProject")]})]})]}),a.jsx("div",{className:"flex gap-1 p-1 bg-bambu-dark rounded-xl w-fit",children:[{key:"active",label:t("projects.statusActive"),icon:Yn},{key:"completed",label:t("projects.statusCompleted"),icon:ul},{key:"archived",label:t("projects.statusArchived"),icon:so},{key:"all",label:t("common.all"),icon:Bs}].map(({key:te,label:ie,icon:J})=>a.jsxs("button",{onClick:()=>u(te),className:`flex items-center gap-2 px-4 py-2 text-sm rounded-lg transition-all ${d===te?"bg-bambu-card text-white shadow-sm":"text-bambu-gray hover:text-white"}`,children:[a.jsx(J,{className:"w-4 h-4"}),a.jsx("span",{children:ie}),L[te]>0&&a.jsx("span",{className:`text-xs px-1.5 py-0.5 rounded-full ${d===te?"bg-bambu-green/20 text-bambu-green":"bg-bambu-dark-tertiary"}`,children:L[te]})]},te))}),b?a.jsx("div",{className:"flex items-center justify-center py-20",children:a.jsxs("div",{className:"flex flex-col items-center gap-3",children:[a.jsx(pt,{className:"w-8 h-8 animate-spin text-bambu-green"}),a.jsx("p",{className:"text-sm text-bambu-gray",children:t("projects.loading")})]})}):v?.length===0?a.jsxs("div",{className:"flex flex-col items-center justify-center py-20 px-4",children:[a.jsx("div",{className:"p-4 bg-bambu-dark rounded-2xl mb-4",children:a.jsx(Bs,{className:"w-12 h-12 text-bambu-gray/50"})}),a.jsx("h3",{className:"text-lg font-medium text-white mb-2",children:d==="all"?t("projects.noProjects"):t("projects.noProjectsFiltered",{status:d})}),a.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"&&a.jsxs(De,{onClick:()=>o(!0),disabled:!i("projects:create"),title:i("projects:create")?void 0:t("projects.noCreatePermission"),children:[a.jsx(sr,{className:"w-4 h-4 mr-2"}),t("projects.createFirstButton")]})]}):a.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-8",children:v?.map(te=>a.jsx(ert,{project:te,onClick:()=>H(te),onEdit:()=>D(te),onDelete:()=>z(te.id),hasPermission:i,t},te.id))}),m!==null&&a.jsx(yn,{title:t("projects.deleteProject"),message:t("projects.deleteConfirm"),confirmText:t("projects.deleteProject"),variant:"danger",onConfirm:Q,onCancel:()=>p(null)}),s&&a.jsx(Hle,{project:l,onClose:()=>{o(!1),c(void 0)},onSave:k,isLoading:g.isPending||_.isPending,currencySymbol:y,t})]})}function nrt(t){const e=t.toLowerCase();return e.endsWith(".gcode")||e.endsWith(".gcode.3mf")}function rrt(t){return t>=1e3?`${(t/1e3).toFixed(2)}kg`:`${Math.round(t)}g`}function art({status:t,t:e}){const n={active:"bg-bambu-green/20 text-bambu-green",completed:"bg-blue-500/20 text-blue-400",archived:"bg-bambu-gray/20 text-bambu-gray"},r=n[t]||n.active,i={active:e("projectDetail.status.active"),completed:e("projectDetail.status.completed"),archived:e("projectDetail.status.archived")};return a.jsx("span",{className:`px-2 py-1 rounded text-sm font-medium ${r}`,children:i[t]||t.charAt(0).toUpperCase()+t.slice(1)})}function kY({icon:t,label:e,value:n,subValue:r,hint:i,color:s="text-bambu-gray"}){return a.jsx(Tt,{children:a.jsx(Mt,{className:"p-4",children:a.jsxs("div",{className:"flex items-center gap-3",title:i,children:[a.jsx("div",{className:`p-2 rounded-lg bg-bambu-dark ${s}`,children:a.jsx(t,{className:"w-5 h-5"})}),a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-bambu-gray",children:e}),a.jsx("p",{className:"text-xl font-semibold text-white",children:n}),r&&a.jsx("p",{className:"text-xs text-bambu-gray/70",children:r})]})]})})})}function irt({archives:t,t:e}){return t.length===0?a.jsxs("div",{className:"text-center py-8 text-bambu-gray",children:[a.jsx(Ra,{className:"w-12 h-12 mx-auto mb-2 opacity-50"}),a.jsx("p",{children:e("projectDetail.noPrints")})]}):a.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6 gap-3",children:t.map(n=>a.jsxs(Do,{to:`/archives?search=${encodeURIComponent(n.print_name||"")}`,className:"group relative aspect-square rounded-lg bg-bambu-dark border border-bambu-dark-tertiary overflow-hidden hover:border-bambu-green transition-colors",children:[n.thumbnail_path?a.jsx("img",{src:de.getArchiveThumbnail(n.id),alt:n.print_name||"Print",className:"w-full h-full object-cover"}):a.jsx("div",{className:"w-full h-full flex items-center justify-center text-bambu-gray",children:a.jsx(Ra,{className:"w-8 h-8"})}),n.status==="failed"&&a.jsx("div",{className:"absolute inset-0 bg-red-500/30 flex items-center justify-center",children:a.jsx(Ma,{className:"w-8 h-8 text-white"})}),n.status==="completed"&&a.jsx("div",{className:"absolute top-1 right-1",children:a.jsx(yr,{className:"w-4 h-4 text-bambu-green"})}),a.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:a.jsx("p",{className:"text-xs text-white truncate",children:n.print_name||"Unknown"})})]},n.id))})}function srt({priority:t,t:e}){const n={low:{color:"bg-gray-500/20 text-gray-400",label:e("projectDetail.priority.low")},normal:{color:"bg-blue-500/20 text-blue-400",label:e("projectDetail.priority.normal")},high:{color:"bg-orange-500/20 text-orange-400",label:e("projectDetail.priority.high")},urgent:{color:"bg-red-500/20 text-red-400",label:e("projectDetail.priority.urgent")}},{color:r,label:i}=n[t]||n.normal;return a.jsxs("span",{className:`px-2 py-1 rounded text-xs font-medium flex items-center gap-1 ${r}`,children:[t==="urgent"&&a.jsx(Dn,{className:"w-3 h-3"}),i]})}function E3(t,e){if(!t)return null;const n=Zn(t);if(!n)return null;const r=new Date,i=Math.ceil((n.getTime()-r.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 ort(){const{id:t}=Yw(),e=qo(),{t:n}=Ft(),r=nn(),{showToast:i}=hn(),{hasPermission:s}=Sr(),[o,l]=w.useState(!1),[c,d]=w.useState(!1),[u,m]=w.useState(""),[p,f]=w.useState(null),[y,v]=w.useState(null),b=parseInt(t||"0",10),{data:g,isLoading:_,error:C}=Xe({queryKey:["project",b],queryFn:()=>de.getProject(b),enabled:b>0}),{data:P,isLoading:N}=Xe({queryKey:["project-archives",b],queryFn:()=>de.getProjectArchives(b),enabled:b>0}),{data:A,isLoading:T}=Xe({queryKey:["project-bom",b],queryFn:()=>de.getProjectBOM(b),enabled:b>0}),{data:F,isLoading:k}=Xe({queryKey:["project-timeline",b],queryFn:()=>de.getProjectTimeline(b,20),enabled:b>0}),{data:D}=Xe({queryKey:["settings"],queryFn:de.getSettings}),{data:H}=Xe({queryKey:["project-folders",b],queryFn:()=>de.getLibraryFoldersByProject(b),enabled:b>0}),{data:z,isLoading:Q}=Xe({queryKey:["project-files",b],queryFn:()=>de.getLibraryFiles(null,!1,b),enabled:b>0}),L=w.useMemo(()=>{const ce=new Map;for(const xe of z??[])if(xe.folder_id!=null){const Be=ce.get(xe.folder_id)??[];Be.push(xe),ce.set(xe.folder_id,Be)}return ce},[z]),te=Eo(D?.currency||"USD"),ie=D?.time_format||"system",J=it({mutationFn:ce=>de.updateProject(b,ce),onSuccess:()=>{r.invalidateQueries({queryKey:["project",b]}),r.invalidateQueries({queryKey:["projects"]}),l(!1),d(!1),i(n("projectDetail.toast.projectUpdated"),"success")},onError:ce=>{i(ce.message,"error")}}),oe=()=>{m(g?.notes||""),d(!0)},fe=()=>{J.mutate({notes:u})},re=()=>{d(!1),m("")},[W,ne]=w.useState(""),[me,be]=w.useState(1),[Ce,q]=w.useState(""),[Y,E]=w.useState(""),[j,O]=w.useState(""),[K,U]=w.useState(!1),[ue,I]=w.useState(!1),[G,X]=w.useState(null),[V,ee]=w.useState(""),[se,ge]=w.useState(1),[he,le]=w.useState(""),[B,R]=w.useState(""),[ae,_e]=w.useState(""),[Se,ve]=w.useState({isOpen:!1,title:"",message:"",onConfirm:()=>{}}),Te=it({mutationFn:ce=>de.createBOMItem(b,ce),onSuccess:()=>{r.invalidateQueries({queryKey:["project-bom",b]}),r.invalidateQueries({queryKey:["project",b]}),ne(""),be(1),q(""),E(""),O(""),U(!1),i(n("projectDetail.toast.partAdded"),"success")},onError:ce=>i(ce.message,"error")}),ye=it({mutationFn:({itemId:ce,data:xe})=>de.updateBOMItem(b,ce,xe),onSuccess:()=>{r.invalidateQueries({queryKey:["project-bom",b]}),r.invalidateQueries({queryKey:["project",b]}),X(null)},onError:ce=>i(ce.message,"error")}),Ae=it({mutationFn:ce=>de.deleteBOMItem(b,ce),onSuccess:()=>{r.invalidateQueries({queryKey:["project-bom",b]}),r.invalidateQueries({queryKey:["project",b]}),i(n("projectDetail.toast.partRemoved"),"success")},onError:ce=>i(ce.message,"error")}),Le=ce=>{ce.preventDefault(),W.trim()&&Te.mutate({name:W.trim(),quantity_needed:me,unit_price:Ce?parseFloat(Ce):void 0,sourcing_url:Y.trim()||void 0,remarks:j.trim()||void 0})},Me=ce=>{const xe=ce.is_complete?0:ce.quantity_needed;ye.mutate({itemId:ce.id,data:{quantity_acquired:xe}})},Oe=(ce,xe)=>{ve({isOpen:!0,title:n("projectDetail.bom.deletePart"),message:n("projectDetail.bom.deleteConfirm",{name:xe}),onConfirm:()=>{ve(Be=>({...Be,isOpen:!1})),Ae.mutate(ce)}})},Re=ce=>{X(ce),ee(ce.name),ge(ce.quantity_needed),le(ce.unit_price?.toString()||""),R(ce.sourcing_url||""),_e(ce.remarks||"")},$e=ce=>{ce.preventDefault(),!(!G||!V.trim())&&ye.mutate({itemId:G.id,data:{name:V.trim(),quantity_needed:se,unit_price:he?parseFloat(he):void 0,sourcing_url:B.trim()||void 0,remarks:ae.trim()||void 0}})},Ye=()=>{X(null)},tt=async()=>{try{const{blob:ce,filename:xe}=await de.exportProjectZip(Number(b)),Be=URL.createObjectURL(ce),Qe=document.createElement("a");Qe.href=Be,Qe.download=xe||`${g?.name||"project"}_${new Date().toISOString().split("T")[0]}.zip`,Qe.click(),URL.revokeObjectURL(Be),i(n("projectDetail.toast.projectExported"),"success")}catch(ce){i(ce.message,"error")}},pe=it({mutationFn:()=>de.createTemplateFromProject(b),onSuccess:()=>{r.invalidateQueries({queryKey:["projects"]}),i(n("projectDetail.toast.templateCreated"),"success")},onError:ce=>i(ce.message,"error")}),Fe=ce=>pg(ce,ie,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"});if(_)return a.jsx("div",{className:"flex items-center justify-center py-24",children:a.jsx(pt,{className:"w-8 h-8 animate-spin text-bambu-green"})});if(C||!g)return a.jsxs("div",{className:"text-center py-24",children:[a.jsx("p",{className:"text-bambu-gray",children:C?`${n("common.error")}: ${C.message}`:n("projectDetail.notFound")}),a.jsx(De,{variant:"secondary",className:"mt-4",onClick:()=>e("/projects"),children:n("projectDetail.backToProjects")})]});const we=g.stats,Ve=we?.progress_percent??0,je=we?.parts_progress_percent??0;return a.jsxs("div",{className:"p-4 md:p-8 space-y-8",children:[a.jsxs("div",{className:"flex items-center gap-2 text-sm text-bambu-gray",children:[a.jsx(Do,{to:"/projects",className:"hover:text-white transition-colors",children:n("nav.projects")}),a.jsx(ti,{className:"w-4 h-4"}),a.jsx("span",{className:"text-white",children:g.name})]}),a.jsxs("div",{className:"flex items-start justify-between",children:[a.jsxs("div",{className:"flex items-center gap-4",children:[a.jsx("button",{onClick:()=>e("/projects"),className:"p-2 rounded-lg bg-bambu-card hover:bg-bambu-dark-tertiary transition-colors",children:a.jsx(DQ,{className:"w-5 h-5 text-bambu-gray"})}),a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:"w-4 h-4 rounded-full shrink-0",style:{backgroundColor:g.color||"#6b7280"}}),a.jsxs("div",{children:[a.jsx("h1",{className:"text-2xl font-bold text-white",children:g.name}),g.description&&a.jsx("p",{className:"text-bambu-gray mt-1",children:g.description})]})]}),a.jsx(art,{status:g.status,t:n})]}),a.jsxs("div",{className:"flex gap-2",children:[a.jsxs(De,{variant:"secondary",onClick:tt,disabled:!s("projects:read"),title:s("projects:read")?n("projectDetail.exportProject"):n("projectDetail.noExportPermission"),children:[a.jsx(ga,{className:"w-4 h-4 mr-2"}),n("projectDetail.export")]}),a.jsxs(De,{onClick:()=>l(!0),disabled:!s("projects:update"),title:s("projects:update")?void 0:n("projectDetail.noEditPermission"),children:[a.jsx(dg,{className:"w-4 h-4 mr-2"}),n("common.edit")]})]})]}),(g.target_count||g.target_parts_count)&&a.jsx(Tt,{children:a.jsxs(Mt,{className:"p-4 space-y-4",children:[g.target_count&&a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center justify-between mb-2",children:[a.jsx("span",{className:"text-sm text-bambu-gray",children:n("projectDetail.progress.platesProgress")}),a.jsxs("span",{className:"text-sm font-medium text-white",children:[we?.total_archives||0," / ",g.target_count," ",n("projectDetail.progress.printJobs")]})]}),a.jsx("div",{className:"h-3 bg-bambu-dark rounded-full overflow-hidden",children:a.jsx("div",{className:"h-full transition-all duration-500",style:{width:`${Math.min(Ve,100)}%`,backgroundColor:Ve>=100?"#22c55e":g.color||"#6b7280"}})}),a.jsxs("div",{className:"flex justify-between mt-1",children:[a.jsx("span",{className:"text-xs text-bambu-gray/70",children:n("projectDetail.progress.percentComplete",{percent:Ve.toFixed(0)})}),we?.remaining_prints!=null&&we.remaining_prints>0&&a.jsx("span",{className:"text-xs text-bambu-gray/70",children:n("projectDetail.progress.remaining",{count:we.remaining_prints})})]})]}),g.target_parts_count&&a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center justify-between mb-2",children:[a.jsx("span",{className:"text-sm text-bambu-gray",children:n("projectDetail.progress.partsProgress")}),a.jsxs("span",{className:"text-sm font-medium text-white",children:[we?.completed_prints||0," / ",g.target_parts_count," ",n("projectDetail.progress.parts")]})]}),a.jsx("div",{className:"h-3 bg-bambu-dark rounded-full overflow-hidden",children:a.jsx("div",{className:"h-full transition-all duration-500",style:{width:`${Math.min(je,100)}%`,backgroundColor:je>=100?"#22c55e":g.color||"#6b7280"}})}),a.jsxs("div",{className:"flex justify-between mt-1",children:[a.jsx("span",{className:"text-xs text-bambu-gray/70",children:n("projectDetail.progress.percentComplete",{percent:je.toFixed(0)})}),we?.remaining_parts!=null&&we.remaining_parts>0&&a.jsx("span",{className:"text-xs text-bambu-gray/70",children:n("projectDetail.progress.remaining",{count:we.remaining_parts})})]})]})]})}),we&&a.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[a.jsx(Tt,{children:a.jsx(Mt,{className:"p-4",children:a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:"p-2 rounded-lg bg-bambu-dark text-bambu-green",children:a.jsx(Ra,{className:"w-5 h-5"})}),a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-bambu-gray",children:n("projectDetail.stats.printJobs")}),a.jsxs("p",{className:"text-xl font-semibold text-white",children:[we.total_archives," ",a.jsx("span",{className:"text-sm font-normal text-bambu-gray",children:n("projectDetail.stats.total")})]}),we.failed_prints>0&&a.jsx("p",{className:"text-sm text-status-error",children:n("projectDetail.stats.failed",{count:we.failed_prints})}),a.jsx("p",{className:"text-sm text-bambu-gray",children:n("projectDetail.stats.partsPrinted",{count:we.completed_prints})})]})]})})}),a.jsx(kY,{icon:Yn,label:n("projectDetail.stats.printTime"),value:Dye(we.total_print_time_hours),color:"text-yellow-400"}),a.jsx(kY,{icon:Er,label:n("projectDetail.stats.filamentUsed"),value:rrt(we.total_filament_grams),color:"text-purple-400"})]}),we&&(()=>{const ce=we.estimated_cost+we.total_energy_cost+we.bom_cost;return we.estimated_cost>0||ce>0||g.budget!==null})()&&a.jsx(Tt,{children:a.jsxs(Mt,{className:"p-4",children:[a.jsx("h2",{className:"text-lg font-semibold text-white mb-3",children:n("projectDetail.cost.title")}),a.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-xs text-bambu-gray uppercase",children:n("projectDetail.cost.filamentCost")}),a.jsxs("p",{className:"text-lg font-semibold text-white",children:[te,we.estimated_cost.toFixed(2)]})]}),we.total_energy_kwh>0&&a.jsxs("div",{children:[a.jsx("p",{className:"text-xs text-bambu-gray uppercase",children:n("projectDetail.cost.energy")}),a.jsxs("p",{className:"text-lg font-semibold text-white",children:[we.total_energy_kwh.toFixed(3)," kWh",we.total_energy_cost>0&&a.jsxs("span",{className:"text-sm text-bambu-gray ml-1",children:["(",te,we.total_energy_cost.toFixed(2),")"]})]})]}),(()=>{const ce=we.estimated_cost+we.total_energy_cost+we.bom_cost;return ce<=0?null:a.jsxs("div",{children:[a.jsx("p",{className:"text-xs text-bambu-gray uppercase",children:n("projectDetail.cost.totalCost")}),a.jsxs("p",{className:"text-lg font-semibold text-bambu-green",children:[te,ce.toFixed(2)]}),we.bom_cost>0&&a.jsx("p",{className:"text-xs text-bambu-gray/70",children:n("projectDetail.cost.includesBom")})]})})(),g.budget!==null&&(()=>{const ce=we.estimated_cost+we.total_energy_cost+we.bom_cost,xe=g.budget-ce;return a.jsxs("div",{children:[a.jsx("p",{className:"text-xs text-bambu-gray uppercase",children:n("projectDetail.cost.budget")}),a.jsxs("p",{className:"text-sm text-bambu-gray",children:[n("projectDetail.cost.total"),": ",a.jsxs("span",{className:"text-white font-semibold",children:[te,g.budget.toFixed(2)]})]}),a.jsxs("p",{className:`text-sm ${xe>=0?"text-bambu-green":"text-red-400"}`,children:[n("projectDetail.cost.remaining"),": ",a.jsxs("span",{className:"font-semibold",children:[te,xe.toFixed(2)]})]})]})})()]})]})}),g.children&&g.children.length>0&&a.jsx(Tt,{children:a.jsxs(Mt,{className:"p-4",children:[a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2 mb-3",children:[a.jsx(yge,{className:"w-5 h-5"}),n("projectDetail.subProjects.title",{count:g.children.length})]}),a.jsx("div",{className:"space-y-2",children:g.children.map(ce=>a.jsxs(Do,{to:`/projects/${ce.id}`,className:"flex items-center justify-between p-3 bg-bambu-dark rounded-lg hover:bg-bambu-dark-tertiary transition-colors",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:"w-3 h-3 rounded-full",style:{backgroundColor:ce.color||"#6b7280"}}),a.jsx("span",{className:"text-white",children:ce.name}),a.jsx("span",{className:`text-xs px-2 py-0.5 rounded ${ce.status==="completed"?"bg-status-ok/20 text-status-ok":ce.status==="archived"?"bg-bambu-gray/20 text-bambu-gray":"bg-blue-500/20 text-blue-400"}`,children:ce.status})]}),ce.progress_percent!==null&&a.jsxs("span",{className:"text-sm text-bambu-gray",children:[ce.progress_percent.toFixed(0),"%"]})]},ce.id))})]})}),g.parent_id&&g.parent_name&&a.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[a.jsx(da,{className:"w-4 h-4 text-bambu-gray"}),a.jsx("span",{className:"text-bambu-gray",children:n("projectDetail.partOf")}),a.jsx(Do,{to:`/projects/${g.parent_id}`,className:"text-bambu-green hover:underline",children:g.parent_name})]}),(g.tags||g.due_date||g.priority!=="normal")&&a.jsxs("div",{className:"flex flex-wrap items-center gap-4",children:[g.priority&&g.priority!=="normal"&&a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:"text-xs text-bambu-gray uppercase",children:n("projectDetail.priorityLabel")}),a.jsx(srt,{priority:g.priority,t:n})]}),g.due_date&&a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(na,{className:"w-4 h-4 text-bambu-gray"}),a.jsx("span",{className:"text-sm text-white",children:hg(g.due_date,{year:"numeric",month:"short",day:"numeric"})}),E3(g.due_date,n)&&a.jsxs("span",{className:`text-xs ${E3(g.due_date,n).color}`,children:["(",E3(g.due_date,n).label,")"]})]}),g.tags&&a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(xm,{className:"w-4 h-4 text-bambu-gray"}),a.jsx("div",{className:"flex flex-wrap gap-1",children:g.tags.split(",").map((ce,xe)=>a.jsx("span",{className:"px-2 py-0.5 bg-bambu-dark-tertiary text-bambu-gray text-xs rounded",children:ce.trim()},xe))})]})]}),a.jsx(Tt,{children:a.jsxs(Mt,{className:"p-4",children:[a.jsxs("div",{className:"flex items-center justify-between mb-3",children:[a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(Us,{className:"w-5 h-5"}),n("projectDetail.notes.title")]}),c?a.jsxs("div",{className:"flex gap-2",children:[a.jsxs(De,{variant:"secondary",size:"sm",onClick:re,disabled:J.isPending,children:[a.jsx(Ht,{className:"w-4 h-4 mr-1"}),n("common.cancel")]}),a.jsxs(De,{size:"sm",onClick:fe,disabled:J.isPending,children:[J.isPending?a.jsx(pt,{className:"w-4 h-4 animate-spin mr-1"}):a.jsx(_s,{className:"w-4 h-4 mr-1"}),n("common.save")]})]}):a.jsxs(De,{variant:"secondary",size:"sm",onClick:oe,disabled:!s("projects:update"),title:s("projects:update")?void 0:n("projectDetail.notes.noEditPermission"),children:[a.jsx(dg,{className:"w-4 h-4 mr-1"}),n("common.edit")]})]}),c?a.jsx(tO,{content:u,onChange:m,placeholder:n("projectDetail.notes.placeholder")}):g.notes?a.jsx("div",{className:"prose prose-invert prose-sm max-w-none",dangerouslySetInnerHTML:{__html:hie.sanitize(g.notes)}}):a.jsx("p",{className:"text-bambu-gray/70 text-sm italic",children:n("projectDetail.notes.empty")})]})}),a.jsx(Tt,{children:a.jsxs(Mt,{className:"p-4",children:[a.jsx("div",{className:"flex items-center justify-between mb-3",children:a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(Qc,{className:"w-5 h-5"}),n("projectDetail.files.title")]})}),a.jsxs("p",{className:"text-xs text-bambu-gray mb-3",children:[a.jsx(Do,{to:"/files",className:"text-bambu-green hover:underline",children:n("projectDetail.files.linkFolders")})," ",n("projectDetail.files.forQuickAccess")]}),H&&H.length>0?a.jsx("div",{className:"space-y-4",children:H.map(ce=>{const xe=L.get(ce.id)??[],Be=Q;return a.jsxs("div",{children:[a.jsxs(Do,{to:`/files?folder=${ce.id}`,className:"flex items-center justify-between p-3 bg-bambu-dark rounded-lg hover:bg-bambu-dark-tertiary transition-colors mb-2",children:[a.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[a.jsx(Qc,{className:"w-5 h-5 text-bambu-green shrink-0"}),a.jsxs("div",{className:"min-w-0",children:[a.jsx("p",{className:"text-sm text-white truncate",children:ce.name}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("projectDetail.files.fileCount",{count:ce.file_count})})]})]}),a.jsx(ti,{className:"w-4 h-4 text-bambu-gray shrink-0"})]}),Be?a.jsx("div",{className:"flex items-center gap-2 px-3 py-2 text-bambu-gray text-sm",children:a.jsx(pt,{className:"w-4 h-4 animate-spin"})}):xe.length===0?a.jsx("p",{className:"text-bambu-gray/60 text-xs italic px-3",children:n("projectDetail.files.noFiles")}):a.jsx("div",{className:"space-y-1 pl-3",children:xe.map(Qe=>{const ht=nrt(Qe.filename);return a.jsxs("div",{className:"flex items-center gap-3 p-2 rounded-lg hover:bg-bambu-dark-tertiary transition-colors",children:[a.jsx("div",{className:"w-10 h-10 shrink-0 rounded bg-bambu-dark overflow-hidden flex items-center justify-center",children:Qe.thumbnail_path?a.jsx("img",{src:de.getLibraryFileThumbnailUrl(Qe.id),alt:Qe.print_name||Qe.filename,className:"w-full h-full object-cover"}):a.jsx(ep,{className:"w-5 h-5 text-bambu-gray/40"})}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("p",{className:"text-sm text-white truncate",title:Qe.print_name||Qe.filename,children:Qe.print_name||Qe.filename}),a.jsx("span",{className:`text-xs px-1.5 py-0.5 rounded font-medium ${Qe.file_type==="3mf"?"bg-bambu-green/20 text-bambu-green":Qe.file_type==="gcode"?"bg-blue-500/20 text-blue-400":"bg-bambu-gray/20 text-bambu-gray"}`,children:Qe.file_type.toUpperCase()})]}),ht&&a.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[a.jsx("button",{onClick:()=>f(Qe),title:n("projectDetail.files.print"),className:"p-1.5 rounded hover:bg-bambu-green/20 text-bambu-green transition-colors",children:a.jsx(es,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>v(Qe),title:n("projectDetail.files.addToQueue"),className:"p-1.5 rounded hover:bg-blue-500/20 text-blue-400 transition-colors",children:a.jsx($pe,{className:"w-4 h-4"})})]})]},Qe.id)})})]},ce.id)})}):a.jsx("p",{className:"text-bambu-gray/70 text-sm italic",children:n("projectDetail.files.empty")})]})}),a.jsx(Tt,{children:a.jsxs(Mt,{className:"p-4",children:[a.jsxs("div",{className:"flex items-center justify-between mb-4",children:[a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(qQ,{className:"w-5 h-5"}),n("projectDetail.bom.title"),we&&we.bom_total_items>0&&a.jsxs("span",{className:"text-sm font-normal text-bambu-gray",children:["(",n("projectDetail.bom.acquired",{completed:we.bom_completed_items,total:we.bom_total_items}),")"]})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[A&&A.some(ce=>ce.is_complete)&&a.jsx("button",{onClick:()=>I(!ue),className:`text-xs px-2 py-1 rounded transition-colors ${ue?"bg-bambu-green/20 text-bambu-green":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:n(ue?"projectDetail.bom.showAll":"projectDetail.bom.hideDone")}),!K&&a.jsxs(De,{variant:"secondary",size:"sm",onClick:()=>U(!0),disabled:!s("projects:update"),title:s("projects:update")?void 0:n("projectDetail.bom.noAddPermission"),children:[a.jsx(sr,{className:"w-4 h-4 mr-1"}),n("projectDetail.bom.addPart")]})]})]}),K&&a.jsxs("form",{onSubmit:Le,className:"bg-bambu-dark rounded-lg p-4 mb-4 space-y-3",children:[a.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[a.jsx("input",{type:"text",value:W,onChange:ce=>ne(ce.target.value),className:"bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:n("projectDetail.bom.partNamePlaceholder"),autoFocus:!0}),a.jsxs("div",{className:"flex gap-2",children:[a.jsx("input",{type:"number",value:me,onChange:ce=>be(parseInt(ce.target.value)||1),className:"w-20 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white focus:outline-none focus:border-bambu-green",min:"1",placeholder:n("projectDetail.bom.qty")}),a.jsx("input",{type:"number",step:"0.01",value:Ce,onChange:ce=>q(ce.target.value),className:"flex-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:n("projectDetail.bom.price",{currency:te})})]})]}),a.jsx("input",{type:"url",value:Y,onChange:ce=>E(ce.target.value),className:"w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:n("projectDetail.bom.sourcingUrlPlaceholder")}),a.jsx("input",{type:"text",value:j,onChange:ce=>O(ce.target.value),className:"w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:n("projectDetail.bom.remarksPlaceholder")}),a.jsxs("div",{className:"flex justify-end gap-2",children:[a.jsx(De,{type:"button",variant:"secondary",size:"sm",onClick:()=>U(!1),children:n("common.cancel")}),a.jsx(De,{type:"submit",size:"sm",disabled:!W.trim()||Te.isPending,children:Te.isPending?a.jsx(pt,{className:"w-4 h-4 animate-spin"}):n("projectDetail.bom.addPart")})]})]}),T?a.jsx("div",{className:"flex items-center justify-center py-4",children:a.jsx(pt,{className:"w-6 h-6 animate-spin text-bambu-green"})}):A&&A.length>0?a.jsxs("div",{className:"space-y-2",children:[A.filter(ce=>!ue||!ce.is_complete).map(ce=>a.jsx("div",{className:`p-3 rounded-lg transition-colors ${ce.is_complete?"bg-status-ok/10":"bg-bambu-dark"}`,children:G?.id===ce.id?a.jsxs("form",{onSubmit:$e,className:"space-y-3",children:[a.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[a.jsx("input",{type:"text",value:V,onChange:xe=>ee(xe.target.value),className:"bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:n("projectDetail.bom.partName"),autoFocus:!0}),a.jsxs("div",{className:"flex gap-2",children:[a.jsx("input",{type:"number",value:se,onChange:xe=>ge(parseInt(xe.target.value)||1),className:"w-20 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white focus:outline-none focus:border-bambu-green",min:"1",placeholder:n("projectDetail.bom.qty")}),a.jsx("input",{type:"number",step:"0.01",value:he,onChange:xe=>le(xe.target.value),className:"flex-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:n("projectDetail.bom.price",{currency:te})})]})]}),a.jsx("input",{type:"url",value:B,onChange:xe=>R(xe.target.value),className:"w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:n("projectDetail.bom.sourcingUrlPlaceholder")}),a.jsx("input",{type:"text",value:ae,onChange:xe=>_e(xe.target.value),className:"w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:n("projectDetail.bom.remarksPlaceholder")}),a.jsxs("div",{className:"flex justify-end gap-2",children:[a.jsx(De,{type:"button",variant:"secondary",size:"sm",onClick:Ye,children:n("common.cancel")}),a.jsx(De,{type:"submit",size:"sm",disabled:!V.trim()||ye.isPending,children:ye.isPending?a.jsx(pt,{className:"w-4 h-4 animate-spin"}):n("common.save")})]})]}):a.jsxs("div",{className:"flex items-start gap-3",children:[a.jsx("button",{onClick:()=>s("projects:update")&&Me(ce),disabled:ye.isPending||!s("projects:update"),title:s("projects:update")?void 0:n("projectDetail.bom.noUpdatePermission"),className:`w-5 h-5 mt-0.5 rounded border-2 flex items-center justify-center transition-colors shrink-0 ${ce.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:ce.is_complete&&a.jsx(yr,{className:"w-3 h-3"})}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsxs("div",{className:"flex items-center justify-between gap-2",children:[a.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[a.jsxs("p",{className:`text-sm font-medium ${ce.is_complete?"text-bambu-gray line-through":"text-white"}`,children:[ce.name,a.jsxs("span",{className:"text-bambu-gray font-normal ml-2",children:["x",ce.quantity_needed]})]}),ce.unit_price!==null&&a.jsxs("span",{className:"text-xs text-bambu-green whitespace-nowrap",children:[te,(ce.unit_price*ce.quantity_needed).toFixed(2)]})]}),a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsx("button",{onClick:()=>s("projects:update")&&Re(ce),disabled:!s("projects:update"),className:`p-1 rounded transition-colors shrink-0 ${s("projects:update")?"hover:bg-bambu-dark-tertiary text-bambu-gray hover:text-white":"text-bambu-gray/50 cursor-not-allowed"}`,title:s("projects:update")?n("common.edit"):n("projectDetail.bom.noEditPermission"),children:a.jsx(ci,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>s("projects:update")&&Oe(ce.id,ce.name),disabled:!s("projects:update"),className:`p-1 rounded transition-colors shrink-0 ${s("projects:update")?"hover:bg-bambu-dark-tertiary text-bambu-gray hover:text-red-400":"text-bambu-gray/50 cursor-not-allowed"}`,title:s("projects:update")?n("common.delete"):n("projectDetail.bom.noDeletePermission"),children:a.jsx(en,{className:"w-4 h-4"})})]})]}),ce.sourcing_url&&a.jsxs("a",{href:ce.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:xe=>xe.stopPropagation(),children:[a.jsx(la,{className:"w-3 h-3 shrink-0"}),a.jsx("span",{className:"truncate",children:(()=>{try{return new URL(ce.sourcing_url).hostname.replace("www.","")}catch{return ce.sourcing_url}})()})]}),ce.remarks&&a.jsx("p",{className:"mt-1 text-xs text-bambu-gray/80 italic",children:ce.remarks})]})]})},ce.id)),we&&we.bom_cost>0&&a.jsxs("div",{className:"pt-2 mt-2 border-t border-bambu-dark-tertiary flex justify-between text-sm",children:[a.jsx("span",{className:"text-bambu-gray",children:n("projectDetail.bom.totalCost")}),a.jsxs("span",{className:"text-white font-medium",children:[te,we.bom_cost.toFixed(2)]})]})]}):a.jsx("p",{className:"text-bambu-gray/70 text-sm italic",children:n("projectDetail.bom.empty")})]})}),a.jsx(Tt,{children:a.jsxs(Mt,{className:"p-4",children:[a.jsx("div",{className:"flex items-center justify-between mb-3",children:a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(iw,{className:"w-5 h-5"}),n("projectDetail.timeline.title")]})}),k?a.jsx("div",{className:"flex items-center justify-center py-4",children:a.jsx(pt,{className:"w-6 h-6 animate-spin text-bambu-green"})}):F&&F.length>0?a.jsx("div",{className:"space-y-3",children:F.slice(0,10).map((ce,xe)=>a.jsxs("div",{className:"flex gap-3",children:[a.jsxs("div",{className:`w-8 h-8 rounded-full flex items-center justify-center shrink-0 ${ce.event_type==="print_completed"?"bg-status-ok/20 text-status-ok":ce.event_type==="print_failed"?"bg-status-error/20 text-status-error":ce.event_type==="print_started"?"bg-yellow-500/20 text-yellow-400":"bg-bambu-dark-tertiary text-bambu-gray"}`,children:[ce.event_type==="print_completed"&&a.jsx(yr,{className:"w-4 h-4"}),ce.event_type==="print_failed"&&a.jsx(Ma,{className:"w-4 h-4"}),ce.event_type==="print_started"&&a.jsx(Er,{className:"w-4 h-4"}),ce.event_type==="queued"&&a.jsx(sF,{className:"w-4 h-4"}),ce.event_type==="project_created"&&a.jsx(sr,{className:"w-4 h-4"})]}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("p",{className:"text-sm text-white",children:ce.title}),ce.description&&a.jsx("p",{className:"text-xs text-bambu-gray truncate",children:ce.description}),a.jsx("p",{className:"text-xs text-bambu-gray/70",children:Fe(ce.timestamp)})]})]},xe))}):a.jsx("p",{className:"text-bambu-gray/70 text-sm italic",children:n("projectDetail.timeline.empty")})]})}),!g.is_template&&a.jsx("div",{className:"flex justify-end",children:a.jsxs(De,{variant:"secondary",size:"sm",onClick:()=>pe.mutate(),disabled:pe.isPending||!s("projects:create"),title:s("projects:create")?void 0:n("projectDetail.template.noCreatePermission"),children:[pe.isPending?a.jsx(pt,{className:"w-4 h-4 animate-spin mr-2"}):a.jsx(qs,{className:"w-4 h-4 mr-2"}),n("projectDetail.template.saveAsTemplate")]})}),we&&(we.queued_prints>0||we.in_progress_prints>0)&&a.jsx(Tt,{children:a.jsxs(Mt,{className:"p-4",children:[a.jsxs("div",{className:"flex items-center justify-between mb-3",children:[a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(sF,{className:"w-5 h-5"}),n("projectDetail.queue.title")]}),a.jsx(Do,{to:`/queue?project=${b}`,className:"text-sm text-bambu-green hover:underline",children:n("projectDetail.queue.viewAll")})]}),a.jsxs("div",{className:"flex items-center gap-4 text-sm",children:[we.in_progress_prints>0&&a.jsx("span",{className:"text-yellow-400",children:n("projectDetail.queue.printing",{count:we.in_progress_prints})}),we.queued_prints>0&&a.jsx("span",{className:"text-bambu-gray",children:n("projectDetail.queue.queued",{count:we.queued_prints})})]})]})}),a.jsxs("div",{children:[a.jsx("div",{className:"flex items-center justify-between mb-4",children:a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(Ra,{className:"w-5 h-5"}),n("projectDetail.prints.title",{count:P?.length||0})]})}),N?a.jsx("div",{className:"flex items-center justify-center py-8",children:a.jsx(pt,{className:"w-6 h-6 animate-spin text-bambu-green"})}):a.jsx(irt,{archives:P||[],t:n})]}),o&&a.jsx(Hle,{t:n,currencySymbol:te,project:{...g,archive_count:we?.total_archives||0,total_items:we?.total_items||0,completed_count:we?.completed_prints||0,failed_count:we?.failed_prints||0,queue_count:we?.queued_prints||0,progress_percent:we?.progress_percent||null,archives:[]},onClose:()=>l(!1),onSave:ce=>J.mutate(ce),isLoading:J.isPending}),Se.isOpen&&a.jsx(yn,{title:Se.title,message:Se.message,confirmText:n("common.delete"),variant:"danger",onConfirm:Se.onConfirm,onCancel:()=>ve(ce=>({...ce,isOpen:!1}))}),p&&a.jsx(sc,{mode:"reprint",libraryFileId:p.id,archiveName:p.print_name||p.filename,projectId:b,onClose:()=>f(null),onSuccess:()=>{f(null),r.invalidateQueries({queryKey:["archives"]})}}),y&&a.jsx(sc,{mode:"add-to-queue",libraryFileId:y.id,archiveName:y.print_name||y.filename,projectId:b,onClose:()=>v(null),onSuccess:()=>{v(null),r.invalidateQueries({queryKey:["queue"]})}})]})}function lrt({parentId:t,onClose:e,onSave:n,isLoading:r,t:i}){const[s,o]=w.useState(""),l=c=>{c.preventDefault(),n({name:s.trim(),parent_id:t})};return a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-sm border border-bambu-dark-tertiary",children:[a.jsx("div",{className:"p-4 border-b border-bambu-dark-tertiary",children:a.jsx("h2",{className:"text-lg font-semibold text-white",children:i("fileManager.newFolder")})}),a.jsxs("form",{onSubmit:l,className:"p-4 space-y-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:i("fileManager.folderName")}),a.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})]}),a.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[a.jsx(De,{type:"button",variant:"secondary",onClick:e,children:i("common.cancel")}),a.jsx(De,{type:"submit",disabled:!s.trim()||r,children:r?a.jsx(pt,{className:"w-4 h-4 animate-spin"}):i("common.create")})]})]})]})})}function crt({onClose:t,onSave:e,isLoading:n,t:r}){const[i,s]=w.useState(""),[o,l]=w.useState(""),[c,d]=w.useState(!0),[u,m]=w.useState(!1),p=f=>{f.preventDefault(),e({name:i.trim(),external_path:o.trim(),readonly:c,show_hidden:u})};return a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-md border border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"p-4 border-b border-bambu-dark-tertiary",children:[a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(SN,{className:"w-5 h-5 text-bambu-green"}),r("fileManager.linkExternalFolder")]}),a.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:r("fileManager.linkExternalFolderDescription")})]}),a.jsxs("form",{onSubmit:p,className:"p-4 space-y-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:r("fileManager.folderName")}),a.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:r("fileManager.externalFolderNamePlaceholder"),autoFocus:!0,required:!0})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:r("fileManager.externalPath")}),a.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}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:r("fileManager.externalPathHelp")})]}),a.jsxs("div",{className:"space-y-2",children:[a.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[a.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"}),a.jsx("span",{className:"text-sm text-white",children:r("fileManager.readOnly")}),a.jsxs("span",{className:"text-xs text-bambu-gray",children:["(",r("fileManager.readOnlyHelp"),")"]})]}),a.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[a.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"}),a.jsx("span",{className:"text-sm text-white",children:r("fileManager.showHiddenFiles")})]})]}),a.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[a.jsx(De,{type:"button",variant:"secondary",onClick:t,children:r("common.cancel")}),a.jsx(De,{type:"submit",disabled:!i.trim()||!o.trim()||n,children:n?a.jsx(pt,{className:"w-4 h-4 animate-spin"}):r("fileManager.linkFolder")})]})]})]})})}function drt({type:t,currentName:e,onClose:n,onSave:r,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]=w.useState(l),u=m=>{m.preventDefault();const p=t==="file"?c.trim()+o:c.trim();c.trim()&&p!==e&&r(p)};return a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-sm border border-bambu-dark-tertiary",children:[a.jsx("div",{className:"p-4 border-b border-bambu-dark-tertiary",children:a.jsx("h2",{className:"text-lg font-semibold text-white",children:s(t==="file"?"fileManager.renameFile":"fileManager.renameFolder")})}),a.jsxs("form",{onSubmit:u,className:"p-4 space-y-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("common.name")}),a.jsxs("div",{className:"flex items-center bg-bambu-dark border border-bambu-dark-tertiary rounded focus-within:border-bambu-green",children:[a.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&&a.jsx("span",{className:"pr-3 text-bambu-gray text-sm select-none whitespace-nowrap",children:o})]})]}),a.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[a.jsx(De,{type:"button",variant:"secondary",onClick:n,children:s("common.cancel")}),a.jsx(De,{type:"submit",disabled:!c.trim()||c.trim()===l||i,children:i?a.jsx(pt,{className:"w-4 h-4 animate-spin"}):s("common.rename")})]})]})]})})}function urt({folders:t,selectedFiles:e,currentFolderId:n,onClose:r,onMove:i,isLoading:s,t:o}){const[l,c]=w.useState(null),d=(m,p=0)=>{const f=[];for(const y of m)f.push({id:y.id,name:y.name,depth:p}),y.children.length>0&&f.push(...d(y.children,p+1));return f},u=[{id:null,name:o("fileManager.rootNoFolder"),depth:0},...d(t)];return a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-sm border border-bambu-dark-tertiary",children:[a.jsx("div",{className:"p-4 border-b border-bambu-dark-tertiary",children:a.jsx("h2",{className:"text-lg font-semibold text-white",children:o("fileManager.moveFiles",{count:e.length})})}),a.jsxs("div",{className:"p-4 space-y-4",children:[a.jsx("div",{className:"max-h-64 overflow-y-auto space-y-1",children:u.map(m=>a.jsxs("button",{onClick:()=>c(m.id),disabled:m.id===n,className:`w-full text-left px-3 py-2 rounded transition-colors flex items-center gap-2 ${l===m.id?"bg-bambu-green/20 text-bambu-green":m.id===n?"opacity-50 cursor-not-allowed text-bambu-gray":"hover:bg-bambu-dark text-white"}`,style:{paddingLeft:`${12+m.depth*16}px`},children:[a.jsx(Qc,{className:"w-4 h-4"}),m.name,m.id===n&&a.jsxs("span",{className:"text-xs text-bambu-gray ml-auto",children:["(",o("fileManager.current"),")"]})]},m.id??"root"))}),a.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[a.jsx(De,{type:"button",variant:"secondary",onClick:r,children:o("common.cancel")}),a.jsx(De,{onClick:()=>i(l),disabled:s,children:s?a.jsx(pt,{className:"w-4 h-4 animate-spin"}):o("common.move")})]})]})]})})}function mrt({folder:t,onClose:e,onLink:n,isLoading:r,t:i}){const[s,o]=w.useState("project"),[l,c]=w.useState(t.project_id||t.archive_id||null);w.useState(()=>{t.archive_id&&o("archive")});const{data:d}=Xe({queryKey:["projects"],queryFn:()=>de.getProjects()}),{data:u}=Xe({queryKey:["archives-for-link"],queryFn:()=>de.getArchives(void 0,void 0,100)}),m=()=>{n(s==="project"?{project_id:l,archive_id:0}:{project_id:0,archive_id:l})},p=()=>{n({project_id:0,archive_id:0})},f=t.project_id||t.archive_id;return a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-md border border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"p-4 border-b border-bambu-dark-tertiary flex items-center justify-between",children:[a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(sm,{className:"w-5 h-5 text-bambu-green"}),i("fileManager.linkFolder")]}),a.jsx("button",{onClick:e,className:"p-1 hover:bg-bambu-dark rounded",children:a.jsx(Ht,{className:"w-5 h-5 text-bambu-gray"})})]}),a.jsxs("div",{className:"p-4 space-y-4",children:[a.jsx("p",{className:"text-sm text-bambu-gray",children:i("fileManager.linkFolderDescription",{name:t.name})}),a.jsxs("div",{className:"flex gap-2",children:[a.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:[a.jsx(FQ,{className:"w-4 h-4"}),i("fileManager.project")]}),a.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:[a.jsx(so,{className:"w-4 h-4"}),i("fileManager.archive")]})]}),a.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(y=>a.jsxs("button",{onClick:()=>c(y.id),className:`w-full text-left px-3 py-2 rounded transition-colors flex items-center gap-2 ${l===y.id?"bg-bambu-green/20 text-bambu-green":"hover:bg-bambu-dark-tertiary text-white"}`,children:[a.jsx("div",{className:"w-3 h-3 rounded-full flex-shrink-0",style:{backgroundColor:y.color||"#00ae42"}}),a.jsx("span",{className:"truncate",children:y.name})]},y.id)):a.jsx("p",{className:"text-sm text-bambu-gray text-center py-4",children:i("fileManager.noProjectsFound")}):u&&u.length>0?u.map(y=>a.jsxs("button",{onClick:()=>c(y.id),className:`w-full text-left px-3 py-2 rounded transition-colors flex items-center gap-2 ${l===y.id?"bg-bambu-green/20 text-bambu-green":"hover:bg-bambu-dark-tertiary text-white"}`,children:[a.jsx(ep,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"}),a.jsx("span",{className:"truncate",children:y.print_name||y.filename})]},y.id)):a.jsx("p",{className:"text-sm text-bambu-gray text-center py-4",children:i("fileManager.noArchivesFound")})})]}),a.jsxs("div",{className:"p-4 border-t border-bambu-dark-tertiary flex justify-between",children:[f&&a.jsxs(De,{variant:"danger",onClick:p,disabled:r,children:[a.jsx(gp,{className:"w-4 h-4 mr-2"}),i("fileManager.unlink")]}),a.jsxs("div",{className:`flex gap-2 ${f?"":"ml-auto"}`,children:[a.jsx(De,{variant:"secondary",onClick:e,children:i("common.cancel")}),a.jsx(De,{onClick:m,disabled:!l||r,children:r?a.jsx(pt,{className:"w-4 h-4 animate-spin"}):i("fileManager.link")})]})]})]})})}function qle({folder:t,selectedFolderId:e,onSelect:n,onDelete:r,onLink:i,onRename:s,depth:o=0,wrapNames:l=!1,defaultExpanded:c=!0,hasPermission:d,t:u}){const[m,p]=w.useState(c),[f,y]=w.useState(!1),v=t.children.length>0,b=t.project_id||t.archive_id,g=t.is_external;return a.jsxs("div",{children:[a.jsxs("div",{className:`group flex items-center gap-1 px-2 py-1.5 rounded cursor-pointer transition-colors ${e===t.id?"bg-bambu-green/20 text-bambu-green":"hover:bg-bambu-dark text-white"}`,style:{paddingLeft:`${8+o*12}px`},onClick:()=>n(t.id),children:[v?a.jsx("button",{onClick:_=>{_.stopPropagation(),p(!m)},className:"p-0.5 hover:bg-bambu-dark-tertiary rounded",children:a.jsx(ti,{className:`w-3.5 h-3.5 transition-transform ${m?"rotate-90":""}`})}):a.jsx("div",{className:"w-4.5"}),g?a.jsx(SN,{className:"w-4 h-4 text-purple-400 flex-shrink-0"}):a.jsx(Qc,{className:"w-4 h-4 text-bambu-green flex-shrink-0"}),a.jsx("span",{className:`text-sm flex-1 min-w-0 ${l?"break-all":"truncate"}`,title:t.name,children:t.name}),b&&a.jsxs("button",{onClick:_=>{_.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:[a.jsx(sm,{className:"w-3 h-3"}),t.project_name?a.jsx(FQ,{className:"w-3 h-3"}):a.jsx(so,{className:"w-3 h-3"})]}),g&&t.external_readonly&&a.jsx("span",{title:u("fileManager.readOnly"),children:a.jsx(kd,{className:"w-3 h-3 text-amber-400 flex-shrink-0"})}),t.file_count>0&&a.jsx("span",{className:"flex-shrink-0 text-xs text-bambu-gray",children:t.file_count}),!b&&!g&&a.jsx("button",{onClick:_=>{_.stopPropagation(),i(t)},className:"flex-shrink-0 p-1 rounded hover:bg-bambu-dark-tertiary",title:u("fileManager.linkToProjectOrArchive"),children:a.jsx(sm,{className:"w-3.5 h-3.5 text-bambu-gray hover:text-bambu-green"})}),a.jsx("div",{className:`flex-shrink-0 flex items-center gap-0.5 transition-opacity ${l?"":"opacity-0 group-hover:opacity-100"}`,onClick:_=>_.stopPropagation(),children:a.jsxs("div",{className:"relative",children:[a.jsx("button",{onClick:()=>y(!f),className:"p-1 rounded hover:bg-bambu-dark-tertiary",children:a.jsx(Jh,{className:"w-3.5 h-3.5 text-bambu-gray"})}),f&&a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>y(!1)}),a.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:[a.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),y(!1))},disabled:!d("library:update_all"),title:d("library:update_all")?void 0:u("fileManager.noPermissionRenameFolder"),children:[a.jsx(ci,{className:"w-3.5 h-3.5"}),u("common.rename")]}),a.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),y(!1))},disabled:!d("library:update_all"),title:d("library:update_all")?void 0:u("fileManager.noPermissionLinkFolder"),children:[a.jsx(sm,{className:"w-3.5 h-3.5"}),u(b?"fileManager.changeLink":"fileManager.linkTo")]}),a.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")&&(r(t.id),y(!1))},disabled:!d("library:delete_all"),title:d("library:delete_all")?void 0:u("fileManager.noPermissionDeleteFolder"),children:[a.jsx(en,{className:"w-3.5 h-3.5"}),u("common.delete")]})]})]})]})})]}),v&&m&&a.jsx("div",{children:t.children.map(_=>a.jsx(qle,{folder:_,selectedFolderId:e,onSelect:n,onDelete:r,onLink:i,onRename:s,depth:o+1,wrapNames:l,defaultExpanded:c,hasPermission:d,t:u},_.id))})]})}function cO(t){const e=t.toLowerCase();return e.endsWith(".gcode")||e.endsWith(".gcode.3mf")}function hrt({file:t,isSelected:e,isMobile:n,onSelect:r,onDelete:i,onDownload:s,onAddToQueue:o,onPrint:l,onPreview3d:c,onRename:d,onGenerateThumbnail:u,thumbnailVersion:m,hasPermission:p,canModify:f,authEnabled:y,t:v}){const[b,g]=w.useState(!1);return a.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:()=>r(t.id),children:[a.jsxs("div",{className:"aspect-square bg-bambu-dark flex items-center justify-center overflow-hidden",children:[t.thumbnail_path?a.jsx("img",{src:`${de.getLibraryFileThumbnailUrl(t.id)}${m?(de.getLibraryFileThumbnailUrl(t.id).includes("?")?"&":"?")+`v=${m}`:""}`,alt:t.filename,className:"w-full h-full object-cover"}):a.jsx(ep,{className:"w-12 h-12 text-bambu-gray/30"}),a.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()})]}),a.jsxs("div",{className:"p-3",children:[a.jsx("h3",{className:"text-sm font-medium text-white truncate",title:t.print_name||t.filename,children:t.print_name||t.filename}),a.jsxs("div",{className:"flex items-center gap-3 mt-1 text-xs text-bambu-gray",children:[a.jsx("span",{children:Lo(t.file_size)}),t.print_time_seconds&&a.jsxs("span",{className:"flex items-center gap-1",children:[a.jsx(Yn,{className:"w-3 h-3"}),ws(t.print_time_seconds)]})]}),t.sliced_for_model&&a.jsxs("div",{className:"mt-1 text-xs text-bambu-gray flex items-center gap-1",children:[a.jsx(Er,{className:"w-3 h-3"}),t.sliced_for_model]}),t.print_count>0&&a.jsx("div",{className:"mt-1 text-xs text-bambu-green",children:v("fileManager.printedCount",{count:t.print_count})}),y&&t.created_by_username&&a.jsxs("div",{className:"mt-1 text-xs text-bambu-gray flex items-center gap-1",children:[a.jsx(ym,{className:"w-3 h-3"}),t.created_by_username]})]}),a.jsxs("div",{className:`absolute bottom-2 right-2 transition-opacity ${n?"opacity-100":"opacity-0 group-hover:opacity-100"}`,onClick:_=>_.stopPropagation(),children:[a.jsx("button",{onClick:()=>g(!b),className:"p-1.5 rounded bg-bambu-dark-secondary/90 hover:bg-bambu-dark-tertiary",children:a.jsx(Jh,{className:"w-4 h-4 text-bambu-gray"})}),b&&a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>g(!1)}),a.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&&cO(t.filename)&&a.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${p("printers:control")?"text-bambu-green hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{p("printers:control")&&(l(t),g(!1))},disabled:!p("printers:control"),title:p("printers:control")?void 0:v("fileManager.noPermissionPrint"),children:[a.jsx(Er,{className:"w-3.5 h-3.5"}),v("common.print")]}),o&&cO(t.filename)&&a.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${p("queue:create")?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{p("queue:create")&&(o(t.id),g(!1))},disabled:!p("queue:create"),title:p("queue:create")?void 0:v("fileManager.noPermissionAddToQueue"),children:[a.jsx(Yn,{className:"w-3.5 h-3.5"}),v("fileManager.schedulePrint")]}),c&&(t.file_type==="3mf"||t.file_type==="gcode"||t.file_type==="stl")&&a.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${p("library:read")?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{p("library:read")&&(c(t),g(!1))},disabled:!p("library:read"),title:p("library:read")?void 0:"You do not have permission to preview files",children:[a.jsx(vi,{className:"w-3.5 h-3.5"}),"3D Preview"]}),a.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${p("library:read")?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{p("library:read")&&(s(t.id),g(!1))},disabled:!p("library:read"),title:p("library:read")?void 0:v("fileManager.noPermissionDownload"),children:[a.jsx(ga,{className:"w-3.5 h-3.5"}),v("common.download")]}),d&&a.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${f("library","update",t.created_by_id)?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{f("library","update",t.created_by_id)&&(d(t),g(!1))},disabled:!f("library","update",t.created_by_id),title:f("library","update",t.created_by_id)?void 0:v("fileManager.noPermissionRenameFile"),children:[a.jsx(ci,{className:"w-3.5 h-3.5"}),v("common.rename")]}),u&&t.file_type==="stl"&&a.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${f("library","update",t.created_by_id)?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{f("library","update",t.created_by_id)&&(u(t),g(!1))},disabled:!f("library","update",t.created_by_id),title:f("library","update",t.created_by_id)?void 0:v("fileManager.noPermissionGenerateThumbnail"),children:[a.jsx(gm,{className:"w-3.5 h-3.5"}),v("fileManager.generateThumbnail")]}),a.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${f("library","delete",t.created_by_id)?"text-red-400 hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{f("library","delete",t.created_by_id)&&(i(t.id),g(!1))},disabled:!f("library","delete",t.created_by_id),title:f("library","delete",t.created_by_id)?void 0:v("fileManager.noPermissionDeleteFile"),children:[a.jsx(en,{className:"w-3.5 h-3.5"}),v("common.delete")]})]})]})]}),a.jsx("div",{className:`absolute top-2 left-2 w-5 h-5 rounded border-2 flex items-center justify-center transition-all ${e?"bg-bambu-green border-bambu-green":`border-white/30 bg-black/30 ${n?"opacity-100":"opacity-0 group-hover:opacity-100"}`}`,children:e&&a.jsx("div",{className:"w-2 h-2 bg-white rounded-sm"})})]})}function prt(){const{t}=Ft(),e=nn(),{showToast:n}=hn(),{hasPermission:r,hasAnyPermission:i,canModify:s,authEnabled:o}=Sr(),[l]=HP(),c=l.get("folder"),d=c?parseInt(c,10):null,[u,m]=w.useState(d),[p,f]=w.useState([]),[y,v]=w.useState(!1),[b,g]=w.useState(!1),[_,C]=w.useState(!1),[P,N]=w.useState(!1),[A,T]=w.useState(null),[F,k]=w.useState(null),[D,H]=w.useState(null),[z,Q]=w.useState(null),[L,te]=w.useState(null),[ie,J]=w.useState(null),[oe,fe]=w.useState({}),[re,W]=w.useState(null),[ne,me]=w.useState(()=>localStorage.getItem("library-view-mode")||"grid"),[be,Ce]=w.useState(()=>localStorage.getItem("library-wrap-folders")==="true"),[q,Y]=w.useState(()=>localStorage.getItem("library-collapse-folders")==="true"),[E,j]=w.useState(()=>{const Ke=localStorage.getItem("library-sidebar-width");return Ke?parseInt(Ke,10):256}),[O,K]=w.useState(!1),U=w.useRef(null);w.useEffect(()=>{if(!O)return;document.body.style.userSelect="none",document.body.style.cursor="col-resize";const Ke=Lt=>{if(!U.current)return;const Et=U.current.parentElement?.getBoundingClientRect();if(!Et)return;const At=Lt.clientX-Et.left,Ie=Math.min(500,Math.max(200,At));j(Ie)},at=()=>{K(!1),document.body.style.userSelect="",document.body.style.cursor="",localStorage.setItem("library-sidebar-width",String(E))};return document.addEventListener("mousemove",Ke),document.addEventListener("mouseup",at),()=>{document.removeEventListener("mousemove",Ke),document.removeEventListener("mouseup",at),document.body.style.userSelect="",document.body.style.cursor=""}},[O,E]);const[ue,I]=w.useState(""),[G,X]=w.useState("all"),[V,ee]=w.useState(""),[se,ge]=w.useState(()=>localStorage.getItem("library-sort-field")||"name"),[he,le]=w.useState(()=>localStorage.getItem("library-sort-direction")||"asc"),B=aie();w.useEffect(()=>{const Ke=l.get("folder");if(Ke){const at=parseInt(Ke,10);m(at)}},[l]);const{data:R}=Xe({queryKey:["settings"],queryFn:()=>de.getSettings()}),{data:ae,isLoading:_e}=Xe({queryKey:["library-folders"],queryFn:()=>de.getLibraryFolders()}),{data:Se,isLoading:ve}=Xe({queryKey:["library-files",u],queryFn:()=>de.getLibraryFiles(u,u===null)}),{data:Te}=Xe({queryKey:["library-stats"],queryFn:()=>de.getLibraryStats()}),{data:ye}=Xe({queryKey:["users"],queryFn:()=>de.getUsers()}),Ae=w.useMemo(()=>{if(!Se)return[];const Ke=new Set(Se.map(at=>at.file_type));return Array.from(Ke).sort()},[Se]),Le=w.useMemo(()=>{if(!Se)return[];let Ke=[...Se];if(ue.trim()){const at=ue.toLowerCase();Ke=Ke.filter(Lt=>Lt.filename.toLowerCase().includes(at)||Lt.print_name&&Lt.print_name.toLowerCase().includes(at))}if(G!=="all"&&(Ke=Ke.filter(at=>at.file_type===G)),V.trim()){const at=V.toLowerCase();Ke=Ke.filter(Lt=>Lt.created_by_username&&Lt.created_by_username.toLowerCase().includes(at))}return Ke.sort((at,Lt)=>{let Et=0;switch(se){case"name":Et=(at.print_name||at.filename).localeCompare(Lt.print_name||Lt.filename);break;case"date":Et=(Zn(at.created_at)?.getTime()??0)-(Zn(Lt.created_at)?.getTime()??0);break;case"size":Et=at.file_size-Lt.file_size;break;case"type":Et=at.file_type.localeCompare(Lt.file_type);break;case"prints":Et=at.print_count-Lt.print_count;break}return he==="asc"?Et:-Et}),Ke},[Se,ue,G,V,se,he]),Me=w.useMemo(()=>{if(!Te||!R)return!1;const Ke=(R.library_disk_warning_gb||5)*1024*1024*1024;return Te.disk_free_bytesde.createLibraryFolder(Ke),onSuccess:()=>{e.invalidateQueries({queryKey:["library-folders"]}),v(!1),n(t("fileManager.toast.folderCreated"),"success")},onError:Ke=>n(Ke.message,"error")}),Re=it({mutationFn:async Ke=>{const at=await de.createExternalFolder(Ke);return await de.scanExternalFolder(at.id),at},onSuccess:Ke=>{e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-stats"]}),g(!1),m(Ke.id),n(t("fileManager.toast.externalFolderLinked"),"success")},onError:Ke=>n(Ke.message,"error")}),$e=it({mutationFn:Ke=>de.scanExternalFolder(Ke),onSuccess:Ke=>{e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-stats"]}),n(t("fileManager.toast.folderScanned",{added:Ke.added,removed:Ke.removed}),"success")},onError:Ke=>n(Ke.message,"error")}),Ye=it({mutationFn:Ke=>de.deleteLibraryFolder(Ke),onSuccess:()=>{e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-stats"]}),u===F?.id&&m(null),k(null),n(t("fileManager.toast.folderDeleted"),"success")},onError:Ke=>{k(null),n(Ke.message,"error")}}),tt=it({mutationFn:Ke=>de.deleteLibraryFile(Ke),onSuccess:()=>{e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-stats"]}),f(Ke=>Ke.filter(at=>at!==F?.id)),k(null),n(t("fileManager.toast.fileDeleted"),"success")},onError:Ke=>{k(null),n(Ke.message,"error")}}),pe=it({mutationFn:Ke=>de.bulkDeleteLibrary(Ke,[]),onSuccess:(Ke,at)=>{e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-stats"]}),n(t("fileManager.toast.filesDeleted",{count:at.length}),"success"),f([]),k(null)},onError:Ke=>{k(null),n(Ke.message,"error")}}),Fe=it({mutationFn:({fileIds:Ke,folderId:at})=>de.moveLibraryFiles(Ke,at),onSuccess:()=>{e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-folders"]}),f([]),C(!1),n(t("fileManager.toast.filesMoved"),"success")},onError:Ke=>n(Ke.message,"error")}),we=it({mutationFn:({id:Ke,data:at})=>de.updateLibraryFolder(Ke,at),onSuccess:(Ke,at)=>{e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["project-folders"]}),e.invalidateQueries({queryKey:["archive-folders"]}),T(null);const Lt=at.data.project_id===0&&at.data.archive_id===0;n(t(Lt?"fileManager.toast.folderUnlinked":"fileManager.toast.folderLinked"),"success")},onError:Ke=>n(Ke.message,"error")}),Ve=it({mutationFn:({id:Ke,filename:at})=>de.updateLibraryFile(Ke,{filename:at}),onSuccess:()=>{e.invalidateQueries({queryKey:["library-files"]}),J(null),n(t("fileManager.toast.fileRenamed"),"success")},onError:Ke=>{J(null),n(Ke.message,"error")}}),je=it({mutationFn:({id:Ke,name:at})=>de.updateLibraryFolder(Ke,{name:at}),onSuccess:()=>{e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-files"]}),J(null),n(t("fileManager.toast.folderRenamed"),"success")},onError:Ke=>{J(null),n(Ke.message,"error")}}),ce=it({mutationFn:()=>de.batchGenerateStlThumbnails({all_missing:!0}),onSuccess:Ke=>{if(e.invalidateQueries({queryKey:["library-files"]}),Ke.succeeded>0){const at=Date.now(),Lt={};Ke.results.forEach(Et=>{Et.success&&(Lt[Et.file_id]=at)}),fe(Et=>({...Et,...Lt}))}Ke.succeeded>0&&Ke.failed===0?n(t("fileManager.toast.thumbnailsGenerated",{count:Ke.succeeded}),"success"):Ke.succeeded>0&&Ke.failed>0?n(t("fileManager.toast.thumbnailsGeneratedPartial",{succeeded:Ke.succeeded,failed:Ke.failed}),"success"):Ke.processed===0?n(t("fileManager.toast.noStlMissingThumbnails"),"info"):n(t("fileManager.toast.failedToGenerateThumbnails",{error:Ke.results[0]?.error||"Unknown error"}),"error")},onError:Ke=>n(Ke.message,"error")}),xe=it({mutationFn:Ke=>de.batchGenerateStlThumbnails({file_ids:[Ke]}),onSuccess:Ke=>{if(e.invalidateQueries({queryKey:["library-files"]}),Ke.succeeded>0){const at=Ke.results[0]?.file_id;at&&fe(Lt=>({...Lt,[at]:Date.now()})),n(t("fileManager.toast.thumbnailGenerated"),"success")}else n(t("fileManager.toast.failedToGenerateThumbnail",{error:Ke.results[0]?.error||"Unknown error"}),"error")},onError:Ke=>n(Ke.message,"error")}),Be=w.useCallback(Ke=>{const at=Ke.toLowerCase();return at.endsWith(".gcode")||at.includes(".gcode.")},[]),Qe=w.useMemo(()=>Se?Se.filter(Ke=>p.includes(Ke.id)&&Be(Ke.filename)):[],[Se,p,Be]),ht=w.useCallback(Ke=>{f(at=>at.includes(Ke)?at.filter(Lt=>Lt!==Ke):[...at,Ke])},[]),xt=w.useCallback(()=>{Le.length>0&&f(Le.map(Ke=>Ke.id))},[Le]),gt=w.useCallback(()=>{f([])},[]),Ut=()=>{e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-stats"]})},Wt=Ke=>{de.downloadLibraryFile(Ke).catch(at=>{console.error("Library file download failed:",at)})},Zt=()=>{F&&(F.type==="file"?tt.mutate(F.id):F.type==="folder"?Ye.mutate(F.id):F.type==="bulk"&&pe.mutate(p))},Kt=Ye.isPending||tt.isPending||pe.isPending,Xt=Ke=>{me(Ke),localStorage.setItem("library-view-mode",Ke)},ln=_e||ve,vn=w.useMemo(()=>{if(!u||!ae)return null;const Ke=at=>{for(const Lt of at){if(Lt.id===u)return Lt;const Et=Ke(Lt.children);if(Et)return Et}return null};return Ke(ae)},[u,ae]);return a.jsxs("div",{className:"p-4 md:p-8 min-h-[calc(100vh-64px)] lg:h-[calc(100vh-64px)] flex flex-col",children:[a.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4 mb-6",children:[a.jsxs("div",{children:[a.jsxs("h1",{className:"text-2xl font-bold text-white flex items-center gap-3",children:[a.jsx("div",{className:"p-2.5 bg-bambu-green/10 rounded-xl",children:a.jsx(Qc,{className:"w-6 h-6 text-bambu-green"})}),t("fileManager.title")]}),a.jsx("p",{className:"text-sm text-bambu-gray mt-2 ml-14",children:t("fileManager.subtitle")})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs("div",{className:"flex items-center bg-bambu-dark rounded-lg p-1",children:[a.jsx("button",{onClick:()=>Xt("grid"),className:`p-1.5 rounded transition-colors ${ne==="grid"?"bg-bambu-dark-secondary text-white":"text-bambu-gray hover:text-white"}`,title:t("fileManager.gridView"),children:a.jsx(eS,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>Xt("list"),className:`p-1.5 rounded transition-colors ${ne==="list"?"bg-bambu-dark-secondary text-white":"text-bambu-gray hover:text-white"}`,title:t("fileManager.listView"),children:a.jsx(tS,{className:"w-4 h-4"})})]}),a.jsxs(De,{variant:"secondary",onClick:()=>ce.mutate(),disabled:ce.isPending||!i("library:update_own","library:update_all"),title:i("library:update_own","library:update_all")?t("fileManager.generateThumbnailsForMissing"):t("fileManager.noPermissionGenerateThumbnail"),children:[ce.isPending?a.jsx(pt,{className:"w-4 h-4 mr-2 animate-spin"}):a.jsx(gm,{className:"w-4 h-4 mr-2"}),t("fileManager.generateThumbnails")]}),a.jsxs(De,{variant:"secondary",onClick:()=>g(!0),disabled:!r("library:upload"),title:r("library:upload")?t("fileManager.linkExternalFolder"):t("fileManager.noPermissionCreateFolder"),children:[a.jsx(SN,{className:"w-4 h-4 mr-2"}),t("fileManager.linkExternal")]}),a.jsxs(De,{variant:"secondary",onClick:()=>v(!0),disabled:!r("library:upload"),title:r("library:upload")?void 0:t("fileManager.noPermissionCreateFolder"),children:[a.jsx(gge,{className:"w-4 h-4 mr-2"}),t("fileManager.newFolder")]}),a.jsxs(De,{onClick:()=>N(!0),disabled:!r("library:upload"),title:r("library:upload")?void 0:t("fileManager.noPermissionUpload"),children:[a.jsx(La,{className:"w-4 h-4 mr-2"}),t("common.upload")]})]})]}),Me&&Te&&R&&a.jsxs("div",{className:"flex items-center gap-3 mb-4 p-3 bg-amber-500/10 border border-amber-500/30 rounded-lg",children:[a.jsx(Dn,{className:"w-5 h-5 text-amber-500 flex-shrink-0"}),a.jsxs("div",{className:"flex-1",children:[a.jsx("p",{className:"text-sm text-amber-500 font-medium",children:t("fileManager.lowDiskSpaceWarning")}),a.jsx("p",{className:"text-xs text-amber-500/80",children:t("fileManager.lowDiskSpaceDetails",{free:Lo(Te.disk_free_bytes),total:Lo(Te.disk_total_bytes),threshold:R.library_disk_warning_gb})})]})]}),Te&&a.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:[a.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[a.jsx($P,{className:"w-4 h-4 text-bambu-green"}),a.jsxs("span",{className:"text-bambu-gray",children:[t("fileManager.files"),":"]}),a.jsx("span",{className:"text-white font-medium",children:Te.total_files})]}),a.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[a.jsx(Qc,{className:"w-4 h-4 text-blue-400"}),a.jsxs("span",{className:"text-bambu-gray",children:[t("fileManager.folders"),":"]}),a.jsx("span",{className:"text-white font-medium",children:Te.total_folders})]}),a.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[a.jsx(Ig,{className:"w-4 h-4 text-amber-400"}),a.jsxs("span",{className:"text-bambu-gray",children:[t("fileManager.size"),":"]}),a.jsx("span",{className:"text-white font-medium",children:Lo(Te.total_size_bytes)})]}),a.jsxs("div",{className:"flex items-center gap-2 text-sm sm:ml-auto",children:[a.jsxs("span",{className:"text-bambu-gray",children:[t("fileManager.free"),":"]}),a.jsx("span",{className:`font-medium ${Me?"text-amber-500":"text-white"}`,children:Lo(Te.disk_free_bytes)})]})]}),a.jsxs("div",{className:"flex-1 flex flex-col lg:flex-row gap-4 lg:gap-6 min-h-0",children:[a.jsx("div",{className:"lg:hidden",children:a.jsxs("select",{value:u??"",onChange:Ke=>m(Ke.target.value?parseInt(Ke.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:[a.jsxs("option",{value:"",children:["📁 ",t("fileManager.allFiles")]}),ae&&(()=>{const Ke=(at,Lt=0)=>{const Et=[];for(const At of at)Et.push({id:At.id,name:At.name,fileCount:At.file_count,depth:Lt}),At.children.length>0&&Et.push(...Ke(At.children,Lt+1));return Et};return Ke(ae).map(at=>a.jsxs("option",{value:at.id,children:["│ ".repeat(at.depth),"📂 ",at.name," ",at.fileCount>0?`(${at.fileCount})`:""]},at.id))})()]})}),a.jsxs("div",{ref:U,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:`${E}px`},children:[a.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 ${O?"bg-bambu-green":"hover:bg-bambu-green/50"}`,onMouseDown:Ke=>{Ke.preventDefault(),K(!0)},onDoubleClick:()=>{j(256),localStorage.setItem("library-sidebar-width","256")},title:t("fileManager.dragToResizeTooltip"),children:a.jsxs("div",{className:`flex flex-col gap-1 opacity-0 group-hover/resize:opacity-100 transition-opacity ${O?"opacity-100":""}`,children:[a.jsx("div",{className:"w-0.5 h-0.5 rounded-full bg-white/70"}),a.jsx("div",{className:"w-0.5 h-0.5 rounded-full bg-white/70"}),a.jsx("div",{className:"w-0.5 h-0.5 rounded-full bg-white/70"})]})}),a.jsxs("div",{className:"p-3 border-b border-bambu-dark-tertiary flex items-center justify-between",children:[a.jsx("h2",{className:"text-sm font-medium text-white",children:t("fileManager.folders")}),a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsx("button",{onClick:()=>{const Ke=!q;Y(Ke),localStorage.setItem("library-collapse-folders",String(Ke))},className:`text-xs px-1.5 py-0.5 rounded transition-colors ${q?"bg-bambu-green/20 text-bambu-green":"text-bambu-gray hover:text-white hover:bg-bambu-dark"}`,title:t(q?"fileManager.expandFoldersByDefault":"fileManager.collapseFoldersByDefault"),children:t("fileManager.collapse")}),a.jsx("button",{onClick:()=>{const Ke=!be;Ce(Ke),localStorage.setItem("library-wrap-folders",String(Ke))},className:`text-xs px-1.5 py-0.5 rounded transition-colors ${be?"bg-bambu-green/20 text-bambu-green":"text-bambu-gray hover:text-white hover:bg-bambu-dark"}`,title:t(be?"fileManager.disableTextWrapping":"fileManager.enableTextWrapping"),children:t("fileManager.wrap")})]})]}),a.jsxs("div",{className:"flex-1 overflow-y-auto p-2",children:[a.jsxs("div",{className:`flex items-center gap-2 px-2 py-1.5 rounded cursor-pointer transition-colors ${u===null?"bg-bambu-green/20 text-bambu-green":"hover:bg-bambu-dark text-white"}`,onClick:()=>m(null),children:[a.jsx(ep,{className:"w-4 h-4"}),a.jsx("span",{className:"text-sm",children:t("fileManager.allFiles")})]}),ae?.map(Ke=>a.jsx(qle,{folder:Ke,selectedFolderId:u,onSelect:m,onDelete:at=>k({type:"folder",id:at}),onLink:T,onRename:at=>J({type:"folder",id:at.id,name:at.name}),wrapNames:be,defaultExpanded:!q,hasPermission:r,t},`${Ke.id}-${q?"c":"e"}`))]})]}),a.jsxs("div",{className:"flex-1 flex flex-col min-w-0 min-h-0",children:[vn?.is_external&&a.jsxs("div",{className:"flex items-center gap-3 mb-4 p-3 bg-purple-500/10 border border-purple-500/30 rounded-lg",children:[a.jsx(SN,{className:"w-5 h-5 text-purple-400 flex-shrink-0"}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:"text-sm font-medium text-purple-300",children:t("fileManager.externalFolder")}),vn.external_readonly&&a.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:[a.jsx(kd,{className:"w-3 h-3"}),t("fileManager.readOnly")]})]}),a.jsx("p",{className:"text-xs text-bambu-gray truncate font-mono",title:vn.external_path||"",children:vn.external_path})]}),a.jsxs(De,{variant:"secondary",size:"sm",onClick:()=>u&&$e.mutate(u),disabled:$e.isPending,title:t("fileManager.scanFolder"),children:[$e.isPending?a.jsx(pt,{className:"w-4 h-4 animate-spin"}):a.jsx(lr,{className:"w-4 h-4"}),a.jsx("span",{className:"ml-1.5",children:t("fileManager.scanFolder")})]})]}),Se&&Se.length>0&&a.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:[a.jsxs("div",{className:"relative w-full sm:w-auto sm:flex-1 sm:max-w-xs",children:[a.jsx(Pr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),a.jsx("input",{type:"text",placeholder:t("fileManager.searchFiles"),value:ue,onChange:Ke=>I(Ke.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"})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(VP,{className:"w-4 h-4 text-bambu-gray hidden sm:block"}),a.jsxs("select",{value:G,onChange:Ke=>X(Ke.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:[a.jsx("option",{value:"all",children:t("fileManager.allTypes")}),Ae.map(Ke=>a.jsx("option",{value:Ke,children:Ke.toUpperCase()},Ke))]})]}),o&&a.jsxs("div",{className:"relative",children:[a.jsx("input",{type:"text",placeholder:t("fileManager.filterByUser",{defaultValue:"Filter by user"}),value:V,onChange:Ke=>ee(Ke.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 ${V?"pr-7":""}`,style:V?{WebkitAppearance:"none",MozAppearance:"textfield"}:void 0}),V&&a.jsx("button",{onClick:()=>ee(""),className:"absolute right-2 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white z-10",children:a.jsx(Ht,{className:"w-3 h-3"})}),a.jsx("datalist",{id:"usernames-list",children:ye?.map(Ke=>a.jsx("option",{value:Ke.username},Ke.id))})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs("select",{value:se,onChange:Ke=>{const at=Ke.target.value;ge(at),localStorage.setItem("library-sort-field",at)},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:[a.jsx("option",{value:"name",children:t("common.name")}),a.jsx("option",{value:"date",children:t("common.date")}),a.jsx("option",{value:"size",children:t("fileManager.size")}),a.jsx("option",{value:"type",children:t("common.type")}),a.jsx("option",{value:"prints",children:t("fileManager.prints")})]}),a.jsx("button",{onClick:()=>le(Ke=>{const at=Ke==="asc"?"desc":"asc";return localStorage.setItem("library-sort-direction",at),at}),className:"p-1.5 rounded bg-bambu-dark border border-bambu-dark-tertiary hover:border-bambu-green transition-colors",title:t(he==="asc"?"fileManager.ascending":"fileManager.descending"),children:he==="asc"?a.jsx(Spe,{className:"w-4 h-4 text-white"}):a.jsx(fpe,{className:"w-4 h-4 text-white"})})]}),(ue||G!=="all"||V)&&a.jsx("span",{className:"text-sm text-bambu-gray hidden sm:inline",children:t("fileManager.resultsCount",{showing:Le.length,total:Se.length})})]}),Le.length>0&&a.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:[p.length===Le.length&&p.length>0?a.jsxs(De,{variant:"secondary",size:"sm",onClick:gt,children:[a.jsx(uo,{className:"w-4 h-4 sm:mr-1"}),a.jsx("span",{className:"hidden sm:inline",children:t("fileManager.deselectAll")})]}):a.jsxs(De,{variant:"secondary",size:"sm",onClick:xt,children:[a.jsx(Ns,{className:"w-4 h-4 sm:mr-1"}),a.jsx("span",{className:"hidden sm:inline",children:t("fileManager.selectAll")})]}),p.length>0&&a.jsxs(a.Fragment,{children:[a.jsx("span",{className:"text-sm text-bambu-gray ml-2",children:t("fileManager.selected",{count:p.length})}),a.jsx("div",{className:"hidden sm:block flex-1"}),a.jsxs("div",{className:"w-full sm:w-auto flex flex-wrap items-center gap-2 mt-2 sm:mt-0",children:[Qe.length===1&&a.jsxs(De,{variant:"primary",size:"sm",onClick:()=>Q(Qe[0]),disabled:!r("printers:control"),title:r("printers:control")?void 0:t("fileManager.noPermissionPrint"),children:[a.jsx(es,{className:"w-4 h-4 sm:mr-1"}),a.jsx("span",{className:"hidden sm:inline",children:t("common.print")})]}),Qe.length===1&&a.jsxs(De,{variant:"secondary",size:"sm",onClick:()=>te(Qe[0]),disabled:!r("queue:create"),title:r("queue:create")?void 0:t("fileManager.noPermissionAddToQueue"),children:[a.jsx(Yn,{className:"w-4 h-4 sm:mr-1"}),a.jsx("span",{className:"hidden sm:inline",children:t("fileManager.schedulePrint")})]}),a.jsxs(De,{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:[a.jsx(Cbe,{className:"w-4 h-4 sm:mr-1"}),a.jsx("span",{className:"hidden sm:inline",children:t("common.move")})]}),a.jsxs(De,{variant:"danger",size:"sm",onClick:()=>{p.length===1?k({type:"file",id:p[0]}):k({type:"bulk",id:0,count:p.length})},disabled:!i("library:delete_own","library:delete_all"),title:i("library:delete_own","library:delete_all")?void 0:t("fileManager.noPermissionDeleteFiles"),children:[a.jsx(en,{className:"w-4 h-4 sm:mr-1"}),a.jsx("span",{className:"hidden sm:inline",children:t("common.delete")})]}),a.jsxs(De,{variant:"secondary",size:"sm",onClick:gt,children:[a.jsx(Ht,{className:"w-4 h-4 sm:mr-1"}),a.jsx("span",{className:"hidden sm:inline",children:t("common.clear")})]})]})]})]}),ln?a.jsx("div",{className:"flex-1 flex items-center justify-center",children:a.jsxs("div",{className:"flex flex-col items-center gap-3",children:[a.jsx(pt,{className:"w-8 h-8 animate-spin text-bambu-green"}),a.jsx("p",{className:"text-sm text-bambu-gray",children:t("fileManager.loadingFiles")})]})}):Se?.length===0?a.jsxs("div",{className:"flex-1 flex flex-col items-center justify-center",children:[a.jsx("div",{className:"p-4 bg-bambu-dark rounded-2xl mb-4",children:a.jsx(ep,{className:"w-12 h-12 text-bambu-gray/50"})}),a.jsx("h3",{className:"text-lg font-medium text-white mb-2",children:t(u!==null?"fileManager.folderIsEmpty":"fileManager.noFilesYet")}),a.jsx("p",{className:"text-bambu-gray text-center max-w-md mb-6",children:t(u!==null?"fileManager.folderEmptyDescription":"fileManager.noFilesDescription")}),a.jsxs(De,{onClick:()=>N(!0),disabled:!r("library:upload"),title:r("library:upload")?void 0:t("fileManager.noPermissionUpload"),children:[a.jsx(sr,{className:"w-4 h-4 mr-2"}),t("fileManager.uploadFiles")]})]}):Le.length===0?a.jsxs("div",{className:"flex-1 flex flex-col items-center justify-center",children:[a.jsx("div",{className:"p-4 bg-bambu-dark rounded-2xl mb-4",children:a.jsx(Pr,{className:"w-12 h-12 text-bambu-gray/50"})}),a.jsx("h3",{className:"text-lg font-medium text-white mb-2",children:t("fileManager.noMatchingFiles")}),a.jsx("p",{className:"text-bambu-gray text-center max-w-md mb-6",children:t("fileManager.noMatchingFilesDescription")}),a.jsx(De,{variant:"secondary",onClick:()=>{I(""),X("all")},children:t("fileManager.clearFilters")})]}):ne==="grid"?a.jsx("div",{className:"flex-1 lg:overflow-y-auto",children:a.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:Le.map(Ke=>a.jsx(hrt,{file:Ke,isSelected:p.includes(Ke.id),isMobile:B,t,onSelect:ht,onDelete:at=>k({type:"file",id:at}),onDownload:Wt,onAddToQueue:at=>{const Lt=Se?.find(Et=>Et.id===at);Lt&&te(Lt)},onPrint:H,onPreview3d:W,onRename:at=>J({type:"file",id:at.id,name:at.filename}),onGenerateThumbnail:at=>xe.mutate(at.id),thumbnailVersion:oe[Ke.id],hasPermission:r,canModify:s,authEnabled:o},Ke.id))})}):a.jsx("div",{className:"flex-1 lg:overflow-y-auto",children:a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg border border-bambu-dark-tertiary overflow-hidden",children:[a.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:[a.jsx("div",{className:"w-6"}),a.jsx("div",{children:t("common.name")}),o&&a.jsx("div",{children:t("fileManager.uploadedBy",{defaultValue:"Uploaded By"})}),a.jsx("div",{children:t("common.type")}),a.jsx("div",{children:t("fileManager.size")}),a.jsx("div",{children:t("fileManager.prints")}),a.jsx("div",{})]}),Le.map(Ke=>a.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 ${p.includes(Ke.id)?"bg-bambu-green/10":""}`,onClick:()=>ht(Ke.id),children:[a.jsx("div",{className:`w-5 h-5 rounded border-2 flex items-center justify-center ${p.includes(Ke.id)?"bg-bambu-green border-bambu-green":"border-bambu-gray/50"}`,children:p.includes(Ke.id)&&a.jsx("div",{className:"w-2 h-2 bg-white rounded-sm"})}),a.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[a.jsxs("div",{className:"relative group/thumb",children:[a.jsx("div",{className:"w-10 h-10 rounded bg-bambu-dark flex-shrink-0 overflow-hidden",children:Ke.thumbnail_path?a.jsx("img",{src:`${de.getLibraryFileThumbnailUrl(Ke.id)}${oe[Ke.id]?(de.getLibraryFileThumbnailUrl(Ke.id).includes("?")?"&":"?")+`v=${oe[Ke.id]}`:""}`,alt:"",className:"w-full h-full object-cover"}):a.jsx("div",{className:"w-full h-full flex items-center justify-center",children:a.jsx(ep,{className:"w-5 h-5 text-bambu-gray/50"})})}),Ke.thumbnail_path&&a.jsx("div",{className:"absolute left-0 top-full mt-2 z-50 hidden group-hover/thumb:block",children:a.jsx("div",{className:"w-48 h-48 rounded-lg bg-bambu-dark-secondary border border-bambu-dark-tertiary shadow-xl overflow-hidden",children:a.jsx("img",{src:`${de.getLibraryFileThumbnailUrl(Ke.id)}${oe[Ke.id]?(de.getLibraryFileThumbnailUrl(Ke.id).includes("?")?"&":"?")+`v=${oe[Ke.id]}`:""}`,alt:Ke.filename,className:"w-full h-full object-contain"})})})]}),a.jsx("div",{className:"min-w-0",children:a.jsx("div",{className:"text-sm text-white truncate",children:Ke.print_name||Ke.filename})})]}),o&&a.jsx("div",{className:"text-sm text-bambu-gray flex items-center gap-1",children:Ke.created_by_username?a.jsxs(a.Fragment,{children:[a.jsx(ym,{className:"w-3 h-3"}),a.jsx("span",{className:"truncate",children:Ke.created_by_username})]}):"-"}),a.jsx("div",{children:a.jsx("span",{className:`text-xs px-1.5 py-0.5 rounded font-medium ${Ke.file_type==="3mf"?"bg-bambu-green/20 text-bambu-green":Ke.file_type==="gcode"?"bg-blue-500/20 text-blue-400":Ke.file_type==="stl"?"bg-purple-500/20 text-purple-400":"bg-bambu-gray/20 text-bambu-gray"}`,children:Ke.file_type.toUpperCase()})}),a.jsx("div",{className:"text-sm text-bambu-gray",children:Lo(Ke.file_size)}),a.jsx("div",{className:"text-sm text-bambu-gray",children:Ke.print_count>0?`${Ke.print_count}x`:"-"}),a.jsxs("div",{className:"flex items-center gap-1",onClick:at=>at.stopPropagation(),children:[cO(Ke.filename)&&a.jsxs(a.Fragment,{children:[a.jsx("button",{onClick:()=>r("printers:control")&&H(Ke),className:`p-1.5 rounded transition-colors ${r("printers:control")?"hover:bg-bambu-dark text-bambu-gray hover:text-bambu-green":"text-bambu-gray/50 cursor-not-allowed"}`,title:r("printers:control")?t("common.print"):t("fileManager.noPermissionPrint"),disabled:!r("printers:control"),children:a.jsx(Er,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>{r("queue:create")&&te(Ke)},className:`p-1.5 rounded transition-colors ${r("queue:create")?"hover:bg-bambu-dark text-bambu-gray hover:text-white":"text-bambu-gray/50 cursor-not-allowed"}`,title:r("queue:create")?t("fileManager.schedulePrint"):t("fileManager.noPermissionAddToQueue"),disabled:!r("queue:create"),children:a.jsx(Yn,{className:"w-4 h-4"})})]}),(Ke.file_type==="3mf"||Ke.file_type==="gcode"||Ke.file_type==="stl")&&a.jsx("button",{onClick:()=>r("library:read")&&W(Ke),className:`p-1.5 rounded transition-colors ${r("library:read")?"hover:bg-bambu-dark text-bambu-gray hover:text-bambu-green":"text-bambu-gray/50 cursor-not-allowed"}`,title:r("library:read")?"3D Preview":"You do not have permission to preview files",disabled:!r("library:read"),children:a.jsx(vi,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>r("library:read")&&Wt(Ke.id),className:`p-1.5 rounded transition-colors ${r("library:read")?"hover:bg-bambu-dark text-bambu-gray hover:text-white":"text-bambu-gray/50 cursor-not-allowed"}`,title:r("library:read")?t("common.download"):t("fileManager.noPermissionDownload"),disabled:!r("library:read"),children:a.jsx(ga,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>s("library","update",Ke.created_by_id)&&J({type:"file",id:Ke.id,name:Ke.filename}),className:`p-1.5 rounded transition-colors ${s("library","update",Ke.created_by_id)?"hover:bg-bambu-dark text-bambu-gray hover:text-white":"text-bambu-gray/50 cursor-not-allowed"}`,title:s("library","update",Ke.created_by_id)?t("common.rename"):t("fileManager.noPermissionRenameFile"),disabled:!s("library","update",Ke.created_by_id),children:a.jsx(ci,{className:"w-4 h-4"})}),Ke.file_type==="stl"&&a.jsx("button",{onClick:()=>s("library","update",Ke.created_by_id)&&xe.mutate(Ke.id),className:`p-1.5 rounded transition-colors ${s("library","update",Ke.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",Ke.created_by_id)?t("fileManager.generateThumbnail"):t("fileManager.noPermissionGenerateThumbnail"),disabled:xe.isPending||!s("library","update",Ke.created_by_id),children:a.jsx(gm,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>s("library","delete",Ke.created_by_id)&&k({type:"file",id:Ke.id}),className:`p-1.5 rounded transition-colors ${s("library","delete",Ke.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",Ke.created_by_id)?t("common.delete"):t("fileManager.noPermissionDeleteFile"),disabled:!s("library","delete",Ke.created_by_id),children:a.jsx(en,{className:"w-4 h-4"})})]})]},Ke.id))]})})]})]}),y&&a.jsx(lrt,{parentId:u,onClose:()=>v(!1),onSave:Ke=>Oe.mutate(Ke),isLoading:Oe.isPending,t}),b&&a.jsx(crt,{onClose:()=>g(!1),onSave:Ke=>Re.mutate(Ke),isLoading:Re.isPending,t}),_&&ae&&a.jsx(urt,{folders:ae,selectedFiles:p,currentFolderId:u,onClose:()=>C(!1),onMove:Ke=>Fe.mutate({fileIds:p,folderId:Ke}),isLoading:Fe.isPending,t}),P&&a.jsx(Yae,{folderId:u,onClose:()=>N(!1),onUploadComplete:Ut}),A&&a.jsx(mrt,{folder:A,onClose:()=>T(null),onLink:Ke=>we.mutate({id:A.id,data:Ke}),isLoading:we.isPending,t}),F&&a.jsx(yn,{title:F.type==="folder"?t("fileManager.deleteFolder"):F.type==="bulk"?t("fileManager.deleteFilesCount",{count:F.count}):t("fileManager.deleteFile"),message:F.type==="folder"?t("fileManager.deleteFolderConfirm"):F.type==="bulk"?t("fileManager.deleteFilesConfirm",{count:F.count}):t("fileManager.deleteFileConfirm"),confirmText:t("common.delete"),variant:"danger",isLoading:Kt,loadingText:t("fileManager.deleting"),onConfirm:Zt,onCancel:()=>k(null)}),D&&a.jsx(sc,{mode:"reprint",libraryFileId:D.id,archiveName:D.print_name||D.filename,onClose:()=>H(null),onSuccess:()=>{H(null),e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["archives"]})}}),z&&a.jsx(sc,{mode:"reprint",libraryFileId:z.id,archiveName:z.print_name||z.filename,onClose:()=>Q(null),onSuccess:()=>{Q(null),f([]),e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["archives"]})}}),L&&a.jsx(sc,{mode:"add-to-queue",libraryFileId:L.id,archiveName:L.print_name||L.filename,onClose:()=>te(null),onSuccess:()=>{te(null),f([]),e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["queue"]}),e.invalidateQueries({queryKey:["archives"]})}}),re&&a.jsx(_z,{libraryFileId:re.id,title:re.print_name||re.filename,fileType:re.file_type,onClose:()=>W(null)}),ie&&a.jsx(drt,{type:ie.type,currentName:ie.name,onClose:()=>J(null),onSave:Ke=>{ie.type==="file"?Ve.mutate({id:ie.id,filename:Ke}):je.mutate({id:ie.id,name:Ke})},isLoading:Ve.isPending||je.isPending,t})]})}function frt(t,e){const n=`token=${encodeURIComponent(e)}`;let r=0;return t.querySelectorAll('img[src*="/api/v1/"], video[src*="/api/v1/"]').forEach(i=>{const s=i.getAttribute("src")||"";if(s.includes(n))return;const o=s.replace(/([?&])token=[^&]*(&|$)/,(c,d,u)=>u==="&"?d:""),l=o.includes("?")?"&":"?";i.src=`${o}${l}${n}`,r+=1}),r}function $le(){const{authEnabled:t,user:e}=Sr(),n=nn(),r=w.useRef(!1),{data:i}=Xe({queryKey:["camera-stream-token",e?.id??null],queryFn:()=>de.getCameraStreamToken(),enabled:t?!!e:!0,staleTime:3e3*1e3,refetchInterval:3e3*1e3});w.useEffect(()=>{const s=i?.token??null;return jH(s),s&&frt(document,s),()=>jH(null)},[i?.token]),w.useEffect(()=>{if(!t)return;const s=o=>{const l=o.target;if(!(l instanceof HTMLImageElement||l instanceof HTMLVideoElement))return;const c=l.src||"",d=QQ();!d||!c.includes(`token=${encodeURIComponent(d)}`)||r.current||(r.current=!0,n.invalidateQueries({queryKey:["camera-stream-token"]}),setTimeout(()=>{r.current=!1},5e3))};return document.addEventListener("error",s,!0),()=>document.removeEventListener("error",s,!0)},[t,n])}const Lk=5,grt=2e3,brt=3e4,xrt=5e3;function yrt(){const{t}=Ft(),e=nn(),{showToast:n}=hn(),{hasPermission:r,authEnabled:i,user:s}=Sr(),{printerId:o}=Yw(),l=parseInt(o||"0",10);$le();const{data:c}=Xe({queryKey:["camera-stream-token",s?.id??null],queryFn:()=>de.getCameraStreamToken(),enabled:i?!!s:!0,staleTime:3e3*1e3}),d=c?.token??QQ(),[u,m]=w.useState("stream"),[p,f]=w.useState(!1),[y,v]=w.useState(!1),[b,g]=w.useState(!0),[_,C]=w.useState(Date.now()),[P,N]=w.useState(!1),[A,T]=w.useState(!1),[F,k]=w.useState(0),[D,H]=w.useState(!1),[z,Q]=w.useState(0),[L,te]=w.useState(1),[ie,J]=w.useState({x:0,y:0}),[oe,fe]=w.useState(!1),[re,W]=w.useState({x:0,y:0}),[ne,me]=w.useState(null),[be,Ce]=w.useState(null),q=w.useRef(null),Y=w.useRef(null),E=w.useRef(null),j=w.useRef(null),O=w.useRef(null),{data:K}=Xe({queryKey:["printer",l],queryFn:()=>de.getPrinter(l),enabled:l>0}),{data:U}=Xe({queryKey:["printerStatus",l],queryFn:()=>de.getPrinterStatus(l),refetchInterval:3e4,enabled:l>0}),ue=it({mutationFn:Fe=>de.setChamberLight(l,Fe),onMutate:async Fe=>{await e.cancelQueries({queryKey:["printerStatus",l]});const we=e.getQueryData(["printerStatus",l]);return e.setQueryData(["printerStatus",l],Ve=>({...Ve,chamber_light:Fe})),{previousStatus:we}},onSuccess:(Fe,we)=>{n(`Chamber light ${we?"on":"off"}`)},onError:(Fe,we,Ve)=>{Ve?.previousStatus&&e.setQueryData(["printerStatus",l],Ve.previousStatus),n(Fe.message||t("printers.toast.failedToControlChamberLight"),"error")}}),I=(U?.state==="RUNNING"||U?.state==="PAUSE")&&(U?.printable_objects_count??0)>=2;w.useEffect(()=>(K&&(document.title=`${K.name} - Camera`),()=>{document.title="Bambuddy"}),[K]);const G=w.useRef(!1);w.useEffect(()=>{const Fe=`/api/v1/printers/${l}/camera/stop`;G.current=!1;const we=()=>{if(l>0&&!G.current){G.current=!0;const ce={},xe=vm();xe&&(ce.Authorization=`Bearer ${xe}`),fetch(Fe,{method:"POST",keepalive:!0,headers:ce}).catch(()=>{})}},Ve=()=>{we()};window.addEventListener("beforeunload",Ve);const je=q.current;return()=>{window.removeEventListener("beforeunload",Ve),je&&(je.src=""),we()}},[l]),w.useEffect(()=>{if(b&&!P){const we=setTimeout(()=>{g(!1)},u==="stream"?3e3:2e4);return()=>clearTimeout(we)}},[u,b,_,P]),w.useEffect(()=>{const Fe=()=>{const we=!!document.fullscreenElement;T(we),te(1),J({x:0,y:0}),u==="stream"&&!P&&(q.current&&(q.current.src=""),setTimeout(()=>{g(!0),C(Date.now())},200))};return document.addEventListener("fullscreenchange",Fe),()=>document.removeEventListener("fullscreenchange",Fe)},[u,P]),w.useEffect(()=>{let Fe;const we=()=>{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",we),()=>{clearTimeout(Fe),window.removeEventListener("resize",we)}},[]),w.useEffect(()=>()=>{E.current&&clearTimeout(E.current),j.current&&clearInterval(j.current),O.current&&clearInterval(O.current)},[]);const X=w.useCallback(()=>{if(F>=Lk){H(!1),v(!0);return}const Fe=Math.min(grt*Math.pow(2,F),brt);H(!0),Q(Math.ceil(Fe/1e3)),j.current=setInterval(()=>{Q(we=>we<=1?(j.current&&clearInterval(j.current),0):we-1)},1e3),E.current=setTimeout(()=>{k(we=>we+1),H(!1),g(!0),v(!1),q.current&&(q.current.src=""),C(Date.now())},Fe)},[F]);w.useEffect(()=>{if(u!=="stream"||b||D||P){O.current&&(clearInterval(O.current),O.current=null);return}return O.current=setInterval(async()=>{try{const Fe=await de.getCameraStatus(l);(Fe.stalled||!Fe.active&&!y)&&(console.log(`Stream issue detected: stalled=${Fe.stalled}, active=${Fe.active}, reconnecting...`),O.current&&(clearInterval(O.current),O.current=null),g(!1),X())}catch{}},xrt),()=>{O.current&&(clearInterval(O.current),O.current=null)}},[u,b,y,D,P,l,X]);const V=()=>{g(!1),u==="stream"&&F{if(g(!1),v(!1),k(0),H(!1),E.current&&clearTimeout(E.current),j.current&&clearInterval(j.current),q.current&&!localStorage.getItem("cameraWindowState")){const Fe=q.current,we=Fe.naturalWidth,Ve=Fe.naturalHeight;if(we>0&&Ve>0){const xe=window.outerWidth-window.innerWidth,Be=window.outerHeight-window.innerHeight,Qe=we+16+xe,ht=Ve+45+16+Be;try{window.resizeTo(Qe,ht)}catch{}}}},se=()=>{if(l>0){const Fe={},we=vm();we&&(Fe.Authorization=`Bearer ${we}`),fetch(`/api/v1/printers/${l}/camera/stop`,{method:"POST",headers:Fe}).catch(()=>{})}},ge=Fe=>{u===Fe||P||(N(!0),g(!0),v(!1),k(0),H(!1),te(1),J({x:0,y:0}),E.current&&clearTimeout(E.current),j.current&&clearInterval(j.current),q.current&&(q.current.src=""),u==="stream"&&se(),setTimeout(()=>{m(Fe),C(Date.now()),N(!1)},100))},he=()=>{P||(N(!0),g(!0),v(!1),k(0),H(!1),E.current&&clearTimeout(E.current),j.current&&clearInterval(j.current),q.current&&(q.current.src=""),u==="stream"&&se(),setTimeout(()=>{C(Date.now()),N(!1)},100))},le=()=>{Y.current&&(document.fullscreenElement?document.exitFullscreen():Y.current.requestFullscreen())},B=()=>{te(Fe=>Math.min(Fe+.5,4))},R=()=>{te(Fe=>{const we=Math.max(Fe-.5,1);return we===1&&J({x:0,y:0}),we})},ae=Fe=>{Fe.preventDefault(),Fe.deltaY<0?B():R()},_e=Fe=>{L>1&&(Fe.preventDefault(),fe(!0),W({x:Fe.clientX-ie.x,y:Fe.clientY-ie.y}))},Se=w.useCallback(()=>{if(!Y.current)return{x:300,y:200};const Fe=Y.current.getBoundingClientRect(),we=Fe.width*(L-1)/2,Ve=Fe.height*(L-1)/2;return{x:Math.max(50,we),y:Math.max(50,Ve)}},[L]),ve=Fe=>{if(oe&&L>1){const we=Fe.clientX-re.x,Ve=Fe.clientY-re.y,je=Se();J({x:Math.max(-je.x,Math.min(je.x,we)),y:Math.max(-je.y,Math.min(je.y,Ve))})}},Te=()=>{fe(!1)},ye=Fe=>{if(Fe.length<2)return 0;const we=Fe[0].clientX-Fe[1].clientX,Ve=Fe[0].clientY-Fe[1].clientY;return Math.sqrt(we*we+Ve*Ve)},Ae=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},Le=Fe=>{Fe.touches.length===2?(Fe.preventDefault(),me(ye(Fe.touches)),Ce(Ae(Fe.touches))):Fe.touches.length===1&&L>1&&(Fe.preventDefault(),fe(!0),W({x:Fe.touches[0].clientX-ie.x,y:Fe.touches[0].clientY-ie.y}))},Me=Fe=>{if(Fe.touches.length===2&&ne!==null){Fe.preventDefault();const we=ye(Fe.touches),Ve=we/ne;te(ce=>{const xe=Math.max(1,Math.min(4,ce*Ve));return xe===1&&J({x:0,y:0}),xe}),me(we);const je=Ae(Fe.touches);if(be){const ce=Se();J(xe=>({x:Math.max(-ce.x,Math.min(ce.x,xe.x+(je.x-be.x))),y:Math.max(-ce.y,Math.min(ce.y,xe.y+(je.y-be.y)))}))}Ce(je)}else if(Fe.touches.length===1&&oe&&L>1){Fe.preventDefault();const we=Fe.touches[0].clientX-re.x,Ve=Fe.touches[0].clientY-re.y,je=Se();J({x:Math.max(-je.x,Math.min(je.x,we)),y:Math.max(-je.y,Math.min(je.y,Ve))})}},Oe=Fe=>{Fe.touches.length<2&&(me(null),Ce(null)),Fe.touches.length===0&&fe(!1)},Re=()=>{te(1),J({x:0,y:0})},$e=i&&!d,Ye=Fe=>d?`${Fe}&token=${encodeURIComponent(d)}`:Ga(Fe),tt=P||$e?"":Ye(u==="stream"?`/api/v1/printers/${l}/camera/stream?fps=15&t=${_}`:`/api/v1/printers/${l}/camera/snapshot?t=${_}`),pe=b||P||D;return l?a.jsxs("div",{ref:Y,className:"min-h-screen bg-black flex flex-col",children:[a.jsxs("div",{className:"flex items-center justify-between px-4 py-2 bg-bambu-dark-secondary border-b border-bambu-dark-tertiary",children:[a.jsxs("h1",{className:"text-sm font-medium text-white flex items-center gap-2",children:[a.jsx(qx,{className:"w-4 h-4"}),K?.name||`Printer ${l}`]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs("div",{className:"flex bg-bambu-dark rounded p-0.5",children:[a.jsx("button",{onClick:()=>ge("stream"),disabled:pe,className:`px-3 py-1 text-xs rounded transition-colors ${u==="stream"?"bg-bambu-green text-white":"text-bambu-gray hover:text-white disabled:opacity-50"}`,children:t("camera.live")}),a.jsx("button",{onClick:()=>ge("snapshot"),disabled:pe,className:`px-3 py-1 text-xs rounded transition-colors ${u==="snapshot"?"bg-bambu-green text-white":"text-bambu-gray hover:text-white disabled:opacity-50"}`,children:t("camera.snapshot")})]}),a.jsx("button",{onClick:()=>ue.mutate(!U?.chamber_light),disabled:!U?.connected||ue.isPending||!r("printers:control"),className:`p-1.5 rounded disabled:opacity-50 ${U?.chamber_light?"bg-yellow-500/20 hover:bg-yellow-500/30":"hover:bg-bambu-dark-tertiary"}`,title:r("printers:control")?t("camera.chamberLight"):t("printers.permission.noControl"),children:a.jsx(xI,{on:U?.chamber_light??!1,className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>f(!0),disabled:!I||!r("printers:control"),className:`p-1.5 rounded disabled:opacity-50 ${I&&r("printers:control")?"hover:bg-bambu-dark-tertiary":""}`,title:r("printers:control")?t(I?"printers.skipObjects.tooltip":"printers.skipObjects.onlyWhilePrinting"):t("printers.permission.noControl"),children:a.jsx(sT,{className:"w-4 h-4 text-bambu-gray"})}),a.jsx("button",{onClick:he,disabled:pe,className:"p-1.5 hover:bg-bambu-dark-tertiary rounded disabled:opacity-50",title:t(u==="stream"?"camera.restartStream":"camera.refreshSnapshot"),children:a.jsx(lr,{className:`w-4 h-4 text-bambu-gray ${pe?"animate-spin":""}`})}),a.jsx("button",{onClick:le,className:"p-1.5 hover:bg-bambu-dark-tertiary rounded",title:t(A?"camera.exitFullscreen":"camera.fullscreen"),children:A?a.jsx(zQ,{className:"w-4 h-4 text-bambu-gray"}):a.jsx(fbe,{className:"w-4 h-4 text-bambu-gray"})})]})]}),a.jsx("div",{className:"flex-1 flex items-center justify-center p-2 overflow-hidden",onWheel:ae,onMouseMove:ve,onMouseUp:Te,onMouseLeave:Te,onTouchStart:Le,onTouchMove:Me,onTouchEnd:Oe,style:{touchAction:"none"},children:a.jsxs("div",{className:"relative w-full h-full flex items-center justify-center",children:[(b||P)&&!D&&a.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/50 z-10",children:a.jsxs("div",{className:"text-center",children:[a.jsx(lr,{className:"w-8 h-8 text-bambu-gray animate-spin mx-auto mb-2"}),a.jsx("p",{className:"text-sm text-bambu-gray",children:t(u==="stream"?"camera.connectingToCamera":"camera.capturingSnapshot")})]})}),D&&a.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/80 z-10",children:a.jsxs("div",{className:"text-center p-4",children:[a.jsx(Bd,{className:"w-10 h-10 text-orange-400 mx-auto mb-3"}),a.jsx("p",{className:"text-white mb-2",children:t("camera.connectionLost")}),a.jsx("p",{className:"text-sm text-bambu-gray mb-3",children:t("camera.reconnecting",{countdown:z,attempt:Math.min(F+1,Lk),max:Lk})}),a.jsx("button",{onClick:he,className:"px-4 py-2 bg-bambu-green text-white text-sm rounded hover:bg-bambu-green/80 transition-colors",children:t("camera.reconnectNow")})]})}),y&&!D&&a.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black z-10",children:a.jsxs("div",{className:"text-center p-4",children:[a.jsx(Dn,{className:"w-12 h-12 text-orange-400 mx-auto mb-3"}),a.jsx("p",{className:"text-white mb-2",children:t("camera.cameraUnavailable")}),a.jsx("p",{className:"text-xs text-bambu-gray mb-4 max-w-md",children:t("camera.cameraUnavailableDesc")}),a.jsx("button",{onClick:he,className:"px-4 py-2 bg-bambu-green text-white rounded hover:bg-bambu-green/80 transition-colors",children:t("camera.retry")})]})}),a.jsx("img",{ref:q,src:tt,alt:t("camera.cameraStream"),className:"max-w-full max-h-full object-contain select-none",style:{transform:`scale(${L}) translate(${ie.x/L}px, ${ie.y/L}px) rotate(${K?.camera_rotation||0}deg)`,...K?.camera_rotation===90||K?.camera_rotation===270?{maxWidth:"100vh",maxHeight:"100vw"}:{},cursor:L>1?oe?"grabbing":"grab":"default"},onError:tt?V:void 0,onLoad:tt?ee:void 0,onMouseDown:_e,draggable:!1},_),a.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:[a.jsx("button",{onClick:R,disabled:L<=1,className:"p-1.5 hover:bg-white/10 rounded disabled:opacity-30",title:t("camera.zoomOut"),children:a.jsx(zO,{className:"w-4 h-4 text-white"})}),a.jsxs("button",{onClick:Re,className:"px-2 py-1 text-sm text-white hover:bg-white/10 rounded min-w-[48px]",title:t("camera.resetZoom"),children:[Math.round(L*100),"%"]}),a.jsx("button",{onClick:B,disabled:L>=4,className:"p-1.5 hover:bg-white/10 rounded disabled:opacity-30",title:t("camera.zoomIn"),children:a.jsx(IO,{className:"w-4 h-4 text-white"})})]})]})}),a.jsx(yI,{printerId:l,isOpen:p,onClose:()=>f(!1)})]}):a.jsx("div",{className:"min-h-screen bg-black flex items-center justify-center",children:a.jsx("p",{className:"text-white",children:t("camera.invalidPrinterId")})})}function vrt(t,e,n){if(!t)return"";if(!e)return t;const r=e.match(/plate_(\d+)\.gcode/);return r&&parseInt(r[1],10)>1?`${t} — ${n("printers.plateNumber","Plate {{number}}",{number:r[1]})}`:t}function wrt(t){const e=t.get("show")?.split(",")||["progress","layers","eta","filename","status"],n=parseInt(t.get("fps")||"15",10),r=Math.min(Math.max(isNaN(n)?15:n,1),30),i=t.get("camera"),s=i!=="false"&&i!=="0";return{size:t.get("size")||"medium",fps:r,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 Srt(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 _rt(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 krt(){const{printerId:t}=Yw(),[e]=HP(),{t:n}=Ft(),r=nn(),i=parseInt(t||"0",10),[s,o]=w.useState(Date.now()),l=w.useMemo(()=>wrt(e),[e]),c=_rt(l.size),{data:d}=Xe({queryKey:["printer",i],queryFn:()=>de.getPrinter(i),enabled:i>0}),{data:u}=Xe({queryKey:["printerStatus",i],queryFn:()=>de.getPrinterStatus(i),enabled:i>0,refetchInterval:2e3}),{data:m}=Xe({queryKey:["settings"],queryFn:de.getSettings}),p=m?.time_format||"system";w.useEffect(()=>{if(!i)return;const _=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/api/v1/ws`,C=new WebSocket(_);return C.onmessage=P=>{try{const N=JSON.parse(P.data);N.type==="printer_status"&&N.printer_id===i&&r.setQueryData(["printerStatus",i],N.status)}catch{}},C.onerror=()=>{},()=>{C.close()}},[i,r]),w.useEffect(()=>(document.title=d?`${d.name} - ${n("streamOverlay.title")}`:n("streamOverlay.title"),()=>{document.title="Bambuddy"}),[d,n]);const f=()=>{setTimeout(()=>{o(Date.now())},3e3)};if(!i)return a.jsx("div",{className:"min-h-screen bg-black flex items-center justify-center",children:a.jsx("p",{className:"text-white",children:n("streamOverlay.invalidPrinterId")})});if(!u)return a.jsx("div",{className:"min-h-screen bg-black flex items-center justify-center",children:a.jsx("p",{className:"text-gray-400",children:n("common.loading")})});const y=u.state==="RUNNING"||u.state==="PAUSE",v=u.progress||0,b=Ga(`/api/v1/printers/${i}/camera/stream?fps=${l.fps}&t=${s}`);return a.jsxs("div",{className:"min-h-screen bg-black relative overflow-hidden",children:[l.showCamera&&a.jsx("img",{src:b,alt:n("streamOverlay.cameraStream"),className:"absolute inset-0 w-full h-full object-contain",style:d?.camera_rotation?{transform:`rotate(${d.camera_rotation}deg)`}:void 0,onError:f},s),a.jsx("a",{href:"https://github.com/maziggy/bambuddy",target:"_blank",rel:"noopener noreferrer",className:"absolute top-4 right-4 z-10",children:a.jsx("img",{src:"/img/bambuddy_logo_dark_transparent.png",alt:"Bambuddy",className:`${c.logoHeight} object-contain drop-shadow-lg hover:scale-105 transition-transform`})}),a.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:a.jsxs("div",{className:`${c.container}`,children:[l.showPrinter&&d&&a.jsxs("div",{className:`flex items-center ${c.gap} mb-2`,children:[a.jsx(Er,{className:`${c.icon} text-white/70`}),a.jsx("span",{className:`${c.text} text-white font-medium`,children:d.name})]}),l.showFilename&&u.current_print&&a.jsx("div",{className:`${c.textLarge} text-white font-semibold mb-2 truncate drop-shadow-md`,children:vrt(u.current_print.replace(/\.gcode\.3mf$|\.3mf$|\.gcode$/i,""),u.gcode_file,n)}),l.showStatus&&a.jsx("div",{className:`${c.text} text-white/70 mb-2`,children:Srt(u,n)}),l.showProgress&&y&&a.jsxs("div",{className:"mb-3",children:[a.jsxs("div",{className:`flex items-center justify-between mb-1 ${c.text}`,children:[a.jsx("span",{className:"text-white/70",children:n("streamOverlay.progress")}),a.jsxs("span",{className:"text-white font-bold",children:[Math.round(v),"%"]})]}),a.jsx("div",{className:`w-full bg-white/20 rounded-full ${c.progressHeight}`,children:a.jsx("div",{className:`bg-bambu-green ${c.progressHeight} rounded-full transition-all duration-500`,style:{width:`${v}%`}})})]}),y&&(l.showLayers||l.showEta)&&a.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&&a.jsxs("div",{className:`flex items-center ${c.gap} text-white/70`,children:[a.jsx(da,{className:c.icon}),a.jsxs("span",{className:c.text,children:[a.jsx("span",{className:"text-white",children:u.layer_num}),a.jsx("span",{className:"mx-1",children:"/"}),a.jsx("span",{children:u.total_layers})]})]}),l.showEta&&u.remaining_time!=null&&u.remaining_time>0&&a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:`flex items-center ${c.gap} text-white/70`,children:[a.jsx(jd,{className:c.icon}),a.jsx("span",{className:`${c.text} text-white`,children:ws(u.remaining_time*60)})]}),a.jsxs("div",{className:`flex items-center ${c.gap} text-white/70`,children:[a.jsx(Yn,{className:c.icon}),a.jsxs("span",{className:`${c.text} text-white`,children:[n("streamOverlay.eta")," ",qO(u.remaining_time,p,n)]})]})]})]}),!y&&a.jsx("div",{className:`${c.text} text-white/70 py-2`,children:u.connected?n("streamOverlay.printerIdle"):n("streamOverlay.printerOffline")})]})})]})}function Nrt(){const{t}=Ft(),{id:e}=Yw(),{mode:n}=zg(),{data:r,isLoading:i,error:s}=Xe({queryKey:["external-link",e],queryFn:()=>de.getExternalLink(Number(e)),enabled:!!e});return i?a.jsx("div",{className:"flex items-center justify-center h-full",children:a.jsx(pt,{className:"w-8 h-8 text-bambu-green animate-spin"})}):s||!r?a.jsxs("div",{className:"flex flex-col items-center justify-center h-full gap-4 text-bambu-gray",children:[a.jsx(Dn,{className:"w-12 h-12"}),a.jsx("p",{children:t("common.linkNotFound")})]}):a.jsx("iframe",{src:r.url,className:"h-full w-full border-0",style:{colorScheme:n},title:r.name,sandbox:"allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox"})}function NY(){const{id:t}=Yw(),e=qo(),n=nn(),{t:r}=Ft(),{showToast:i}=hn(),s=!!t,[o,l]=w.useState(""),[c,d]=w.useState(""),[u,m]=w.useState([]),[p,f]=w.useState(""),[y,v]=w.useState(!1),{data:b,isLoading:g}=Xe({queryKey:["group",t],queryFn:()=>de.getGroup(Number(t)),enabled:s}),{data:_,isLoading:C}=Xe({queryKey:["permissions"],queryFn:()=>de.getPermissions()});s&&b&&!y&&(l(b.name),d(b.description||""),m(b.permissions),v(!0));const P=it({mutationFn:J=>de.createGroup(J),onSuccess:()=>{n.invalidateQueries({queryKey:["groups"]}),i(r("groups.toast.created")),e("/settings?tab=users")},onError:J=>{i(J.message,"error")}}),N=it({mutationFn:J=>de.updateGroup(Number(t),J),onSuccess:()=>{n.invalidateQueries({queryKey:["groups"]}),i(r("groups.toast.updated")),e("/settings?tab=users")},onError:J=>{i(J.message,"error")}}),A=P.isPending||N.isPending,T=()=>{if(!o.trim()){i(r("groups.toast.enterGroupName"),"error");return}s?N.mutate({name:o!==b?.name?o:void 0,description:c,permissions:u}):P.mutate({name:o,description:c||void 0,permissions:u})},F=J=>{m(oe=>oe.includes(J)?oe.filter(fe=>fe!==J):[...oe,J])},k=(J,oe)=>{const fe=J.permissions.map(re=>re.value);m(re=>{const W=re.filter(ne=>!fe.includes(ne));return oe?[...W,...fe]:W})},D=J=>J.permissions.every(oe=>u.includes(oe.value)),H=J=>{const oe=J.permissions.filter(fe=>u.includes(fe.value)).length;return oe>0&&oe{_&&m(_.all_permissions)},Q=()=>{m([])},L=p.toLowerCase(),te=w.useMemo(()=>_?L?_.categories.map(J=>({...J,permissions:J.permissions.filter(oe=>oe.label.toLowerCase().includes(L))})).filter(J=>J.permissions.length>0):_.categories:[],[_,L]),ie=_?.all_permissions.length??0;return g||C?a.jsx("div",{className:"flex items-center justify-center py-16",children:a.jsx(pt,{className:"w-8 h-8 text-bambu-green animate-spin"})}):a.jsxs("div",{className:"space-y-6 max-w-5xl mx-auto",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.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:a.jsx(DQ,{className:"w-5 h-5"})}),a.jsx("h1",{className:"text-xl font-bold text-white",children:r(s?"groups.editor.title":"groups.editor.createTitle")})]}),s&&b?.is_system&&a.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:[a.jsx(Dn,{className:"w-4 h-4 shrink-0"}),r("groups.form.systemGroupWarning")]}),a.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:r("groups.form.groupName")}),a.jsx("input",{type:"text",value:o,onChange:J=>l(J.target.value),disabled:s&&b?.is_system,className:"w-full px-4 py-3 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors disabled:opacity-50",placeholder:r("groups.form.groupNamePlaceholder")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:r("groups.form.description")}),a.jsx("input",{type:"text",value:c,onChange:J=>d(J.target.value),className:"w-full px-4 py-3 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors",placeholder:r("groups.form.descriptionPlaceholder")})]})]}),a.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-3",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsxs("span",{className:"text-sm text-bambu-gray",children:[r("groups.editor.permissionsSelected",{count:u.length})," / ",ie]}),a.jsx(De,{size:"sm",variant:"ghost",onClick:z,children:r("groups.editor.selectAll")}),a.jsx(De,{size:"sm",variant:"ghost",onClick:Q,children:r("groups.editor.clearAll")})]}),a.jsxs("div",{className:"relative",children:[a.jsx(Pr,{className:"w-4 h-4 absolute left-3 top-1/2 -translate-y-1/2 text-bambu-gray"}),a.jsx("input",{type:"text",value:p,onChange:J=>f(J.target.value),placeholder:r("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"})]})]}),te.length===0?a.jsx("div",{className:"text-center py-12 text-bambu-gray",children:r("groups.editor.noResults")}):a.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:te.map(J=>{const oe=_.categories.find(me=>me.name===J.name),fe=oe.permissions.filter(me=>u.includes(me.value)).length,re=oe.permissions.length,W=D(oe),ne=H(oe);return a.jsxs(Tt,{children:[a.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:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsxs("button",{type:"button",onClick:()=>k(oe,!W),className:`w-5 h-5 rounded border flex items-center justify-center transition-colors shrink-0 ${W?"bg-bambu-green border-bambu-green":ne?"bg-bambu-green/50 border-bambu-green":"border-bambu-gray hover:border-white"}`,children:[W&&a.jsx(Ur,{className:"w-3 h-3 text-white"}),ne&&!W&&a.jsx(kN,{className:"w-3 h-3 text-white"})]}),a.jsx(Gu,{className:"w-4 h-4 text-bambu-gray shrink-0"}),a.jsx("span",{className:"text-white font-medium text-sm",children:J.name})]}),a.jsxs("span",{className:"text-xs text-bambu-gray tabular-nums",children:[fe,"/",re]})]}),a.jsx("div",{className:"p-3 space-y-1",children:J.permissions.map(me=>a.jsxs("label",{className:"flex items-center gap-3 px-2 py-1.5 rounded hover:bg-bambu-dark-secondary cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:u.includes(me.value),onChange:()=>F(me.value),className:"w-4 h-4 rounded border-bambu-gray text-bambu-green focus:ring-bambu-green focus:ring-offset-0 bg-bambu-dark-secondary"}),a.jsx("span",{className:"text-sm text-bambu-gray",children:me.label})]},me.value))})]},J.name)})}),a.jsx("div",{className:"h-16"}),a.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:[a.jsx(De,{variant:"secondary",onClick:()=>e("/settings?tab=users"),children:r("common.cancel")}),a.jsx(De,{onClick:T,disabled:A||!o.trim(),children:A?a.jsxs(a.Fragment,{children:[a.jsx(pt,{className:"w-4 h-4 animate-spin"}),r("common.saving")]}):a.jsxs(a.Fragment,{children:[a.jsx(_s,{className:"w-4 h-4"}),r("common.save")]})})]})]})}const dO={material:"",subtype:"",brand:"",color_name:"",rgba:"808080FF",label_weight:1e3,core_weight:250,core_weight_catalog_id:null,weight_used:0,slicer_filament:"",note:"",cost_per_kg:null};function Vle(t,e=!1){const n={};return e?(t.material||(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 Gle=["PLA","PETG","ABS","TPU","ASA","PC","PA","PVA","HIPS","PA-CF","PETG-CF","PLA-CF"],Crt=["Bambu","PolyLite","PolyTerra","eSUN","Overture","Fiberon","SUNLU","Inland","Hatchbox","Generic"],J0=["Basic","Matte","Silk","Silk+","Tough","Tough+","HF","High Flow","Engineering","Galaxy","Glow","Marble","Metal","Rainbow","Sparkle","Wood","Translucent","Transparent","Clear","Lite","Pro","Plus","Max","Super","Ultra","Flex","Soft","Hard","Strong","Impact","Heat Resistant","UV Resistant","ESD","Conductive","Magnetic","Gradient","Dual Color","Tri Color","Multicolor"],Wle=[{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"}],Prt=[{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"}],CY=[...Wle,...Prt],Kle="bambuddy-recent-colors",Trt=8,Art=[{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 Cp(t){let e=t.replace(/@.*$/,"").trim();e=e.replace(/\(Custom\)/i,"").trim(),e=e.replace(/^[#*]+\s*/,"").trim();const n=["PLA-CF","PETG-CF","ABS-GF","ASA-CF","PA-CF","PAHT-CF","PA6-CF","PA6-GF","PPA-CF","PPA-GF","PET-CF","PPS-CF","PC-CF","PC-ABS","ABS-GF","PCTG","PETG","PLA","ABS","ASA","PC","PA","TPU","PVA","HIPS","BVOH","PPS","PEEK","PEI"];let r="",i=-1;for(const c of n){const d=e.toUpperCase().indexOf(c.toUpperCase());if(d!==-1){r=c,i=d;break}}let s="";i>0&&(s=e.substring(0,i).trim(),s=s.replace(/[-_\s]+$/,""));let o="";i!==-1&&r&&(o=e.substring(i+r.length).trim(),o=o.replace(/^[-_\s]+/,""));let l="";for(const c of J0)if(o.toLowerCase().includes(c.toLowerCase())){l=c;break}if(!l&&s)for(const c of J0){const d=new RegExp(`\\s+${c}$`,"i");if(d.test(s)){l=c,s=s.replace(d,"").trim();break}}return{brand:s,material:r,variant:l}}function Xle(t,e){const n=new Set(Crt);for(const r of t){const{brand:i}=Cp(r.name);i&&i.length>1&&n.add(i)}if(e)for(const r of e)if(r.filament_vendor&&r.filament_vendor.length>1)n.add(r.filament_vendor);else{const{brand:i}=Cp(r.name);i&&i.length>1&&n.add(i)}return Array.from(n).sort((r,i)=>r.localeCompare(i))}function jrt(t){const e=t.filter(r=>r.preset_type==="filament");if(e.length===0)return[];const n=new Map;for(const r of e){const i=r.name.replace(/@.*$/,"").trim(),s=n.get(i);if(s)s.allCodes.push(String(r.id));else{const o=r.filament_type||String(r.id);n.set(i,{code:o,name:i,displayName:i,isCustom:!1,allCodes:[o]})}}return Array.from(n.values()).sort((r,i)=>r.displayName.localeCompare(i.displayName))}function Yle(t,e,n){if(t.length>0){const r=[],i=new Map;for(const s of t)if(s.is_custom){const o=s.name.toUpperCase();(e.size===0||Array.from(e).some(c=>o.includes(c))||!o.includes("@"))&&r.push({code:s.setting_id,name:s.name,displayName:`${s.name} (Custom)`,isCustom:!0,allCodes:[s.setting_id]})}else{const o=s.name.replace(/@.*$/,"").trim(),l=i.get(o);l?l.allCodes.push(s.setting_id):i.set(o,{code:s.setting_id,name:o,displayName:o,isCustom:!1,allCodes:[s.setting_id]})}return[...r,...Array.from(i.values())].sort((s,o)=>s.displayName.localeCompare(o.displayName))}if(n&&n.length>0){const r=jrt(n);if(r.length>0)return r}return Art}function Qle(t,e){if(!t)return;let n=e.find(r=>r.code===t);if(n||(n=e.find(r=>r.allCodes.includes(t))),!n){const r=t.toLowerCase();n=e.find(i=>i.code.toLowerCase()===r||i.allCodes.some(s=>s.toLowerCase()===r))}return n}function Zle(){try{const t=localStorage.getItem(Kle);if(t)return JSON.parse(t)}catch{}return[]}function Jle(t,e){const n=e.filter(i=>i.hex.toUpperCase()!==t.hex.toUpperCase()),r=[t,...n].slice(0,Trt);try{localStorage.setItem(Kle,JSON.stringify(r))}catch{}return r}function D3(t,e){if(!e.material)return!1;const r=(t.name||"").replace(/^High Flow[_\s]+/i,"").replace(/^Standard[_\s]+/i,"").replace(/^HF[_\s]+/i,"").replace(/^S[_\s]+/i,"").trim(),i=Cp(r);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())||r.toLowerCase().includes(e.subtype.toLowerCase())))}function ece({formData:t,updateField:e,cloudAuthenticated:n,loadingCloudPresets:r,presetInputValue:i,setPresetInputValue:s,selectedPresetOption:o,filamentOptions:l,availableBrands:c,availableMaterials:d,quickAdd:u,quantity:m,onQuantityChange:p,errors:f}){const{t:y}=Ft(),[v,b]=w.useState(!1),[g,_]=w.useState(!1),[C,P]=w.useState(!1),[N,A]=w.useState(!1),[T,F]=w.useState(""),[k,D]=w.useState(""),[H,z]=w.useState(""),[Q,L]=w.useState(String(t.label_weight)),[te,ie]=w.useState(!1),J=w.useRef(null),oe=w.useRef(null),fe=w.useRef(null),re=w.useRef(null);w.useEffect(()=>{const q=Y=>{J.current&&!J.current.contains(Y.target)&&b(!1),re.current&&!re.current.contains(Y.target)&&A(!1),oe.current&&!oe.current.contains(Y.target)&&_(!1),fe.current&&!fe.current.contains(Y.target)&&P(!1)};return document.addEventListener("mousedown",q),()=>document.removeEventListener("mousedown",q)},[]);const W=w.useMemo(()=>{if(!i)return l;const q=i.toLowerCase();return l.filter(Y=>Y.displayName.toLowerCase().includes(q)||Y.code.toLowerCase().includes(q))},[l,i]),ne=w.useMemo(()=>{if(!T)return c;const q=T.toLowerCase();return c.filter(E=>E.toLowerCase().includes(q)).sort((E,j)=>{const O=E.toLowerCase()===q,K=j.toLowerCase()===q;return O&&!K?-1:!O&&K?1:E.localeCompare(j)})},[c,T]),me=w.useMemo(()=>{if(!k)return J0;const q=k.toLowerCase();return J0.filter(Y=>Y.toLowerCase().includes(q))},[k]),be=w.useMemo(()=>{if(!H)return d;const q=H.toLowerCase();return d.filter(E=>E.toLowerCase().includes(q)).sort((E,j)=>{const O=E.toLowerCase()===q,K=j.toLowerCase()===q;return O&&!K?-1:!O&&K?1:E.localeCompare(j)})},[H,d]);w.useEffect(()=>{te||L(String(t.label_weight))},[t.label_weight,te]);const Ce=q=>{e("slicer_filament",q.code),s(q.displayName),b(!1);const Y=Cp(q.name);Y.material&&e("material",Y.material),Y.brand&&e("brand",Y.brand),Y.variant&&e("subtype",Y.variant)};return a.jsxs("div",{className:"space-y-4",children:[!u&&a.jsx("div",{className:"flex items-center gap-2 text-xs text-bambu-gray",children:r?a.jsxs(a.Fragment,{children:[a.jsx(pt,{className:"w-3 h-3 animate-spin"})," ",y("inventory.loadingPresets")]}):n?a.jsxs(a.Fragment,{children:[a.jsx(vy,{className:"w-3 h-3 text-bambu-green"})," ",y("inventory.cloudConnected")]}):a.jsxs(a.Fragment,{children:[a.jsx(xfe,{className:"w-3 h-3"})," ",y("inventory.cloudNotConnected")]})}),!u&&a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:[y("inventory.slicerPreset")," *"]}),a.jsxs("div",{className:"relative",ref:J,children:[a.jsx(Pr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50 pointer-events-none"}),a.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:y("inventory.searchPresets"),value:i,onChange:q=>{s(q.target.value),b(!0)},onFocus:()=>{b(!0),s("")}}),v&&a.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:W.length===0?a.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:y("inventory.noPresetsFound")}):W.map(q=>a.jsx("button",{type:"button",className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary truncate ${o?.code===q.code?"bg-bambu-green/10 text-bambu-green":"text-white"}`,onClick:()=>Ce(q),children:q.displayName},q.code))})]}),o&&a.jsxs("div",{className:"mt-1 text-xs text-bambu-gray",children:[y("inventory.selectedPreset"),": ",a.jsx("span",{className:"font-mono text-bambu-green",children:o.code})]}),f?.slicer_filament&&a.jsx("p",{className:"mt-1 text-xs text-red-400",children:f.slicer_filament})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:[y("inventory.material")," *"]}),a.jsxs("div",{className:"relative",ref:re,children:[a.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:y("inventory.selectMaterial"),value:N?H:t.material,onChange:q=>{z(q.target.value),A(!0)},onFocus:()=>{A(!0),z("")}}),a.jsx(On,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50 pointer-events-none"}),N&&a.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:[be.length===0?a.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:y("inventory.noResults")}):be.map(q=>a.jsx("button",{type:"button",className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary ${t.material===q?"bg-bambu-green/10 text-bambu-green":"text-white"}`,onClick:()=>{e("material",q),A(!1),z("")},children:q},q)),H&&!be.includes(H)&&a.jsx("button",{type:"button",className:"w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary text-bambu-green border-t border-bambu-dark-tertiary",onClick:()=>{e("material",H),A(!1),z("")},children:y("inventory.useCustomMaterial",{material:H})})]})]}),f?.material&&a.jsx("p",{className:"mt-1 text-xs text-red-400",children:f.material})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:[y("inventory.brand"),!u&&" *"]}),a.jsxs("div",{className:"relative",ref:oe,children:[a.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:y("inventory.searchBrand"),value:g?T:t.brand,onChange:q=>{F(q.target.value),_(!0)},onFocus:()=>{_(!0),F("")}}),a.jsx(On,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50 pointer-events-none"}),g&&a.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:[ne.length===0?a.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:y("inventory.noResults")}):ne.map(q=>a.jsx("button",{type:"button",className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary ${t.brand===q?"bg-bambu-green/10 text-bambu-green":"text-white"}`,onClick:()=>{e("brand",q),_(!1),F("")},children:q},q)),T&&!ne.includes(T)&&a.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",T),_(!1),F("")},children:y("inventory.useCustomBrand",{brand:T})})]})]}),f?.brand&&a.jsx("p",{className:"mt-1 text-xs text-red-400",children:f.brand})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:[y("inventory.subtype"),!u&&" *"]}),a.jsxs("div",{className:"relative",ref:fe,children:[a.jsx("input",{type:"text",value:C?k:t.subtype,onChange:q=>{D(q.target.value),P(!0)},onFocus:()=>{P(!0),D("")},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"}),a.jsx(On,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50 pointer-events-none"}),C&&a.jsxs("div",{className:"absolute z-50 w-full mt-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-lg max-h-48 overflow-y-auto",children:[me.length===0?a.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:y("inventory.noResults")}):me.map(q=>a.jsx("button",{type:"button",className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary ${t.subtype===q?"bg-bambu-green/10 text-bambu-green":"text-white"}`,onClick:()=>{e("subtype",q),P(!1),D("")},children:q},q)),k&&!J0.some(q=>q.toLowerCase()===k.toLowerCase().trim())&&a.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),P(!1),D("")},children:y("inventory.useCustomBrand",{brand:k})})]})]}),f?.subtype&&a.jsx("p",{className:"mt-1 text-xs text-red-400",children:f.subtype})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:y("inventory.labelWeight")}),a.jsxs("div",{className:"relative",children:[a.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:Q,min:0,onFocus:()=>ie(!0),onChange:q=>L(q.target.value),onBlur:()=>{ie(!1);const q=Q.trim(),Y=Number(q);if(!q||!Number.isFinite(Y)||Y<0){L(String(t.label_weight));return}const E=Math.round(Y);e("label_weight",E),L(String(E))}}),a.jsx("span",{className:"absolute right-2 top-1/2 -translate-y-1/2 text-xs text-bambu-gray",children:"g"})]})]}),u&&a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:y("inventory.quantity")}),a.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:q=>{const Y=Math.max(1,Math.min(100,parseInt(q.target.value)||1));p(Y)}})]})]})}function tce({formData:t,updateField:e,recentColors:n,onColorUsed:r,catalogColors:i}){const{t:s}=Ft(),[o,l]=w.useState(!1),[c,d]=w.useState(""),u=t.rgba.replace("#","").substring(0,6),m=g=>u.toUpperCase()===g.toUpperCase(),p=(g,_)=>{e("rgba",g.toUpperCase()+"FF"),e("color_name",_),r({name:_,hex:g})},f=w.useMemo(()=>{if(i.length===0)return[];const g=t.brand?.trim(),_=t.material?.toLowerCase().trim(),C=t.subtype?.toLowerCase().trim();if(!g&&!_)return[];const P=g?g.toLowerCase().split(/[\s\-_]+/).filter(T=>T.length>=2):[],N=T=>{if(P.length===0)return!0;const F=T.toLowerCase();return P.some(k=>F.includes(k))};if(g&&!_){const T=i.filter(F=>N(F.manufacturer));if(T.length>0)return T.map(F=>({name:F.color_name,hex:F.hex_color.replace("#","").substring(0,6),manufacturer:F.manufacturer,material:typeof F.material=="string"?F.material:void 0}))}const A=_&&C?`${_} ${C}`:"";if(A){const T=i.filter(k=>N(k.manufacturer)&&k.material?.toLowerCase()===A);if(T.length>0)return T.map(k=>({name:k.color_name,hex:k.hex_color.replace("#","").substring(0,6),manufacturer:k.manufacturer,material:typeof k.material=="string"?k.material:void 0}));const F=A.replace(/\+$/,"");if(F!==A){const k=i.filter(D=>N(D.manufacturer)&&D.material?.toLowerCase()===F);if(k.length>0)return k.map(D=>({name:D.color_name,hex:D.hex_color.replace("#","").substring(0,6),manufacturer:D.manufacturer,material:typeof D.material=="string"?D.material:void 0}))}}if(_){const T=i.filter(F=>N(F.manufacturer)&&(!F.material||F.material.toLowerCase().startsWith(_)));if(T.length>0)return T.map(F=>({name:F.color_name,hex:F.hex_color.replace("#","").substring(0,6),manufacturer:F.manufacturer,material:typeof F.material=="string"?F.material:void 0}))}return[]},[i,t.brand,t.material,t.subtype]),y=w.useMemo(()=>{if(!c)return f;if(f.length===0)return[];const g=c.toLowerCase();return f.filter(C=>C.name.toLowerCase().includes(g)||(C.manufacturer?.toLowerCase().includes(g)??!1)||(C.material?.toLowerCase().includes(g)??!1))},[c,f]),v=f.length>0,b=w.useMemo(()=>c?CY.filter(g=>g.name.toLowerCase().includes(c.toLowerCase())):o?CY:Wle,[c,o]);return a.jsxs("div",{className:"space-y-3",children:[a.jsx("div",{className:"h-10 rounded-lg border border-bambu-dark-tertiary",style:{backgroundColor:`#${u}`}}),n.length>0&&a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-bambu-gray shrink-0",children:[a.jsx(Yn,{className:"w-3 h-3"}),a.jsx("span",{children:s("inventory.recentColors")})]}),a.jsx("div",{className:"flex flex-wrap gap-1.5",children:n.map(g=>a.jsx("button",{type:"button",onClick:()=>p(g.hex,g.name),className:`w-6 h-6 rounded border-2 transition-all hover:scale-110 ${m(g.hex)?"border-bambu-green ring-1 ring-bambu-green/30 scale-110":"border-bambu-dark-tertiary"}`,style:{backgroundColor:`#${g.hex}`},title:g.name},g.hex))})]}),a.jsxs("div",{className:"relative",children:[a.jsx(Pr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50 pointer-events-none"}),a.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:g=>d(g.target.value)})]}),v?a.jsxs("div",{className:"space-y-1.5",children:[a.jsx("span",{className:"text-xs text-bambu-gray",children:c?s("inventory.searchResults"):`${t.brand}${t.material?` ${t.material}`:""}`}),a.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[y.map(g=>a.jsx("button",{type:"button",onClick:()=>p(g.hex,g.name),className:`w-6 h-6 rounded border-2 transition-all hover:scale-110 hover:z-20 relative group ${m(g.hex)?"border-bambu-green ring-1 ring-bambu-green/30 scale-110":"border-bambu-dark-tertiary"}`,style:{backgroundColor:`#${g.hex}`},title:g.manufacturer&&g.material?`${g.name} (${g.manufacturer} — ${g.material})`:g.manufacturer?`${g.name} (${g.manufacturer})`:g.name,children:a.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:g.manufacturer&&g.material?`${g.name} (${g.manufacturer} — ${g.material})`:g.manufacturer?`${g.name} (${g.manufacturer})`:g.name})},`${g.hex}-${g.name}-${g.manufacturer??""}`)),y.length===0&&a.jsx("p",{className:"text-sm text-bambu-gray py-1",children:s("inventory.noColorsFound")})]})]}):a.jsxs("div",{className:"space-y-1.5",children:[a.jsxs("div",{className:"flex items-center justify-between text-xs text-bambu-gray",children:[a.jsx("span",{children:s(c?"inventory.searchResults":o?"inventory.allColors":"inventory.commonColors")}),!c&&a.jsx("button",{type:"button",onClick:()=>l(!o),className:"flex items-center gap-1 hover:text-white transition-colors",children:o?a.jsxs(a.Fragment,{children:[s("inventory.showLess")," ",a.jsx(dc,{className:"w-3 h-3"})]}):a.jsxs(a.Fragment,{children:[s("inventory.showAll")," ",a.jsx(On,{className:"w-3 h-3"})]})})]}),a.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[b.map(g=>a.jsx("button",{type:"button",onClick:()=>p(g.hex,g.name),className:`w-6 h-6 rounded border-2 transition-all hover:scale-110 hover:z-20 relative group ${m(g.hex)?"border-bambu-green ring-1 ring-bambu-green/30 scale-110":"border-bambu-dark-tertiary"}`,style:{backgroundColor:`#${g.hex}`},title:g.name,children:a.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:g.name})},g.hex)),b.length===0&&a.jsx("p",{className:"text-sm text-bambu-gray py-1",children:s("inventory.noColorsFound")})]})]}),a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:s("inventory.colorName")}),a.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:g=>e("color_name",g.target.value)})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:s("inventory.hexColor")}),a.jsxs("div",{className:"flex gap-2",children:[a.jsxs("div",{className:"relative flex-1",children:[a.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-bambu-gray",children:"#"}),a.jsx("input",{type:"text",className:"w-full pl-7 pr-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm font-mono uppercase focus:outline-none focus:border-bambu-green",placeholder:"RRGGBB",value:u.toUpperCase(),onChange:g=>{const _=g.target.value.replace("#","").replace(/[^0-9A-Fa-f]/g,"").toUpperCase();if(_.length>8)return;const C=_.length===8?_:_.length===7?_.substring(0,6)+"FF":_.padEnd(6,"0")+"FF";e("rgba",C)}})]}),a.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:g=>{const _=g.target.value.replace("#","").toUpperCase();e("rgba",_+"FF")},title:s("inventory.pickColor")})]})]})]})]})}function Mrt({catalog:t,value:e,onChange:n,catalogId:r,onCatalogIdChange:i}){const{t:s}=Ft(),[o,l]=w.useState(!1),[c,d]=w.useState(""),u=w.useRef(null),m=w.useRef(null);w.useEffect(()=>{const v=b=>{u.current&&!u.current.contains(b.target)&&l(!1)};return document.addEventListener("mousedown",v),()=>document.removeEventListener("mousedown",v)},[]),w.useEffect(()=>{if(t.length===0)return;const v=t.filter(b=>b.weight===e);if(r){const b=t.find(g=>g.id===r);if(b&&b.weight===e)return}v.length===1?i(v[0].id):v.length===0&&r!==null&&i(null)},[e,t,r,i]);const p=w.useMemo(()=>{if(!c)return t;const v=c.toLowerCase();return t.filter(b=>b.name.toLowerCase().includes(v)||b.weight.toString().includes(v))},[t,c]),f=w.useMemo(()=>t.filter(v=>v.weight===e),[t,e]),y=w.useMemo(()=>{if(o)return c;if(r){const v=t.find(b=>b.id===r);if(v)return v.name}return f.length>0?f[0].name:""},[o,c,r,t,f]);return a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:a.jsxs("span",{className:"flex items-center gap-2",children:[a.jsx(BQ,{className:"w-3.5 h-3.5 text-bambu-gray"}),s("inventory.coreWeight")]})}),a.jsxs("div",{className:"flex gap-2 items-center",children:[a.jsxs("div",{className:"flex-1 min-w-0 relative",ref:u,children:[a.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:y,onFocus:()=>{l(!0),d("")},onChange:v=>{d(v.target.value),l(!0)}}),o&&a.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?a.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:s("inventory.noResults")}):p.map(v=>a.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 ${(r?v.id===r:v.weight===e)?"bg-bambu-green/10 text-bambu-green":"text-white"}`,onClick:()=>{i(v.id),n(v.weight),l(!1),d("")},children:[a.jsx("span",{className:"truncate",children:v.name}),a.jsxs("span",{className:"font-mono text-xs text-bambu-gray ml-2 shrink-0",children:[v.weight,"g"]})]},v.id))})]}),a.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[a.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:v=>{const b=parseInt(v.target.value);!isNaN(b)&&b>=0&&n(b)}}),a.jsx("span",{className:"text-bambu-gray text-sm",children:"g"})]})]})]})}function nce({formData:t,updateField:e,spoolCatalog:n,currencySymbol:r}){const{t:i}=Ft(),{showToast:s}=hn(),[o,l]=w.useState(""),[c,d]=w.useState(!1),[u,m]=w.useState(""),[p,f]=w.useState(!1),y=Math.max(0,t.label_weight-t.weight_used),v=t.core_weight+y;return w.useEffect(()=>{c||l(String(v))},[c,v]),w.useEffect(()=>{p||m(String(y))},[p,y]),a.jsxs("div",{className:"space-y-4",children:[a.jsx(Mrt,{catalog:n,value:t.core_weight,onChange:b=>e("core_weight",b),catalogId:t.core_weight_catalog_id,onCatalogIdChange:b=>e("core_weight_catalog_id",b)}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:i("inventory.currentWeight")}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs("div",{className:"relative flex-1",children:[a.jsx("input",{type:"number",value:u,min:0,max:t.label_weight,onFocus:()=>f(!0),onChange:b=>{m(b.target.value)},onBlur:()=>{f(!1);const b=u.trim(),g=Number(b);if(!b||!Number.isFinite(g)||g<0||g>t.label_weight){m(String(y));return}const _=Math.round(g);e("weight_used",Math.max(0,t.label_weight-_)),m(String(_))},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"}),a.jsx("span",{className:"absolute right-2 top-1/2 -translate-y-1/2 text-xs text-bambu-gray",children:"g"})]}),a.jsxs("span",{className:"text-xs text-bambu-gray shrink-0",children:["/ ",t.label_weight,"g"]})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:i("inventory.measuredWeight")}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs("div",{className:"relative flex-1",children:[a.jsx("input",{type:"number",value:o,min:0,onFocus:()=>d(!0),onChange:b=>{l(b.target.value)},onBlur:()=>{d(!1);const b=o.trim(),g=Number(b),_=t.core_weight,C=t.core_weight+t.label_weight;if(!b||!Number.isFinite(g)||g<_||g>C){s(i("inventory.measuredWeightError",{min:_,max:C}),"error"),l(String(v));return}const P=Math.round(g),N=Math.max(0,Math.min(t.label_weight,P-t.core_weight));e("weight_used",Math.max(0,t.label_weight-N)),l(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"}),a.jsx("span",{className:"absolute right-2 top-1/2 -translate-y-1/2 text-xs text-bambu-gray",children:"g"})]}),a.jsxs("span",{className:"text-xs text-bambu-gray shrink-0",children:["/ ",t.core_weight+t.label_weight,"g"]})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:i("inventory.costPerKg","Cost per kg")}),a.jsx("div",{className:"flex items-center gap-2",children:a.jsxs("div",{className:"relative flex-1",children:[a.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-bambu-gray text-sm pointer-events-none",children:r}),a.jsx("input",{type:"number",value:t.cost_per_kg??"",min:0,step:.01,placeholder:"0.00",onChange:b=>{const g=b.target.value===""?null:parseFloat(b.target.value);e("cost_per_kg",g)},style:{paddingLeft:`${Math.max(2,r.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"})]})})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:i("inventory.note")}),a.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:i("inventory.notePlaceholder"),value:t.note,onChange:b=>e("note",b.target.value)})]})]})}function rce({formData:t,printersWithCalibrations:e,selectedProfiles:n,setSelectedProfiles:r,expandedPrinters:i,setExpandedPrinters:s}){const{t:o}=Ft(),l=p=>{s(f=>{const y=new Set(f);return y.has(p)?y.delete(p):y.add(p),y})},c=(p,f,y)=>{const v=`${p}:${f}:${y??"null"}`,b=`${p}:${y??"null"}`;r(g=>{const _=new Set(g);if(_.has(v))_.delete(v);else{for(const C of Array.from(_)){const P=C.split(":");`${P[0]}:${P[2]}`===b&&_.delete(C)}_.add(v)}return _})},d=()=>{const p=new Set;for(const{printer:f,calibrations:y}of e){if(!f.connected)continue;const v=y.filter(g=>D3(g,t)),b=new Map;for(const g of v){const _=`${g.extruder_id??"null"}`;b.has(_)||b.set(_,[]),b.get(_).push(g)}for(const[g,_]of b)if(_.length>0){const P=[..._].sort((N,A)=>A.k_value-N.k_value)[0];p.add(`${f.id}:${P.cali_idx}:${g}`)}}r(p)};if(!t.material)return a.jsx("div",{className:"p-6 bg-bambu-dark rounded-lg text-center",children:a.jsx("p",{className:"text-bambu-gray",children:o("inventory.selectMaterialFirst")})});if(e.length===0)return a.jsx("div",{className:"p-6 bg-bambu-dark rounded-lg text-center",children:a.jsx("p",{className:"text-bambu-gray",children:o("inventory.noPrintersConfigured")})});const u=e.reduce((p,{printer:f,calibrations:y})=>f.connected?p+y.filter(v=>D3(v,t)).length:p,0),m=(p,f)=>{const y=`${p.id}:${f.cali_idx}:${f.extruder_id??"null"}`,v=n.has(y);return a.jsxs("label",{className:`flex items-center gap-3 p-3 rounded-lg cursor-pointer transition-all border ${v?"bg-bambu-green/10 border-bambu-green/30":"bg-bambu-dark border-transparent hover:bg-bambu-dark/80"}`,children:[a.jsx("input",{type:"checkbox",checked:v,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"}),a.jsx("div",{className:"flex-1 min-w-0",children:a.jsx("span",{className:`text-sm font-medium ${v?"text-bambu-green":"text-white"}`,children:f.name||f.filament_id})}),a.jsx("div",{className:"flex items-center gap-2 shrink-0",children:a.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 a.jsxs("div",{className:"space-y-4",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.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&&a.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:[a.jsx($x,{className:"w-3.5 h-3.5"}),o("inventory.autoSelect")," (",u,")"]})]}),a.jsx("div",{className:"space-y-3",children:e.map(({printer:p,calibrations:f})=>{const y=i.has(String(p.id)),v=f.filter(P=>D3(P,t)),b=v.length,g=v.some(P=>P.extruder_id!==void 0&&P.extruder_id!==null&&P.extruder_id>0),_=v.filter(P=>P.extruder_id===1),C=v.filter(P=>P.extruder_id===0||P.extruder_id===void 0||P.extruder_id===null);return a.jsxs("div",{className:"border border-bambu-dark-tertiary rounded-lg overflow-hidden",children:[a.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:[a.jsxs("div",{className:"flex items-center gap-3",children:[y?a.jsx(On,{className:"w-4 h-4 text-bambu-gray"}):a.jsx(ti,{className:"w-4 h-4 text-bambu-gray"}),a.jsx("span",{className:"font-medium text-white",children:p.name}),b>0?a.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")]}):a.jsx("span",{className:"text-xs px-2 py-0.5 rounded-full bg-bambu-dark-tertiary text-bambu-gray",children:o("inventory.noMatches")})]}),a.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")})]}),y&&a.jsx("div",{className:"px-4 py-3 space-y-3 bg-bambu-dark border-t border-bambu-dark-tertiary",children:p.connected?b===0?a.jsx("p",{className:"text-sm text-bambu-gray italic py-2",children:o("inventory.noKProfilesMatch")}):g?a.jsxs(a.Fragment,{children:[_.length>0&&a.jsxs("div",{className:"space-y-2",children:[a.jsx("p",{className:"text-xs font-medium text-bambu-gray uppercase tracking-wide",children:o("inventory.leftNozzle")}),a.jsx("div",{className:"space-y-2",children:_.map(P=>m(p,P))})]}),C.length>0&&a.jsxs("div",{className:"space-y-2",children:[a.jsx("p",{className:"text-xs font-medium text-bambu-gray uppercase tracking-wide",children:o("inventory.rightNozzle")}),a.jsx("div",{className:"space-y-2",children:C.map(P=>m(p,P))})]})]}):a.jsx("div",{className:"space-y-2",children:v.map(P=>m(p,P))}):a.jsx("p",{className:"text-sm text-bambu-gray italic py-2",children:o("inventory.printerOffline")})})]},p.id)})}),n.size>0&&a.jsx("div",{className:"p-3 bg-bambu-green/10 border border-bambu-green/30 rounded-lg",children:a.jsxs("p",{className:"text-sm text-white",children:[a.jsx("span",{className:"font-semibold",children:n.size})," ",o("inventory.profilesSelected")]})})]})}function Ert(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 Drt={completed:"text-bambu-green",failed:"text-red-400",aborted:"text-yellow-400"};function Frt({spoolId:t}){const{t:e}=Ft(),n=nn(),{showToast:r}=hn(),{data:i,isLoading:s}=Xe({queryKey:["spool-usage",t],queryFn:()=>de.getSpoolUsageHistory(t)}),o=it({mutationFn:()=>de.clearSpoolUsageHistory(t),onSuccess:()=>{n.invalidateQueries({queryKey:["spool-usage",t]}),r(e("inventory.historyCleared"),"success")}});return s?a.jsx("div",{className:"flex justify-center py-4",children:a.jsx(pt,{className:"w-5 h-5 animate-spin text-bambu-green"})}):!i||i.length===0?a.jsxs("div",{className:"text-center py-4 text-bambu-gray text-sm",children:[a.jsx(Yn,{className:"w-5 h-5 mx-auto mb-2 opacity-50"}),e("inventory.noUsageHistory")]}):a.jsxs("div",{className:"space-y-2",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("h4",{className:"text-sm font-medium text-white",children:e("inventory.usageHistory")}),a.jsxs(De,{variant:"ghost",size:"sm",onClick:()=>o.mutate(),disabled:o.isPending,className:"text-xs text-bambu-gray hover:text-red-400",children:[a.jsx(en,{className:"w-3 h-3 mr-1"}),e("inventory.clearHistory")]})]}),a.jsx("div",{className:"max-h-48 overflow-y-auto space-y-1",children:i.map(l=>a.jsxs("div",{className:"flex items-center justify-between p-2 rounded bg-bambu-dark/50 text-xs",children:[a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("span",{className:"text-bambu-gray",children:Ert(l.created_at)}),l.print_name&&a.jsx("span",{className:"text-white ml-2 truncate",title:l.print_name,children:l.print_name})]}),a.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0 ml-2",children:[a.jsxs("span",{className:"text-white font-medium",children:[l.weight_used.toFixed(1),"g"]}),a.jsxs("span",{className:"text-bambu-gray",children:["(",l.percent_used,"%)"]}),a.jsx("span",{className:Drt[l.status]||"text-bambu-gray",children:l.status})]})]},l.id))})]})}function Rrt({isOpen:t,onClose:e,spool:n,printersWithCalibrations:r=[],currencySymbol:i,onSpoolsCreated:s}){const{t:o}=Ft(),l=nn(),{showToast:c}=hn(),d=!!n,[u,m]=w.useState(dO),[p,f]=w.useState({}),[y,v]=w.useState("filament"),[b,g]=w.useState(!1),[_,C]=w.useState(!1),[P,N]=w.useState(1),[A,T]=w.useState(!1),[F,k]=w.useState(!1),[D,H]=w.useState([]),[z,Q]=w.useState(""),[L,te]=w.useState([]),[ie,J]=w.useState([]),[oe,fe]=w.useState([]),[re,W]=w.useState([]),[ne,me]=w.useState([]),[be,Ce]=w.useState(new Set),[q,Y]=w.useState(new Set),E=r.length>0?r:ne,j=w.useMemo(()=>be.size,[be]);w.useEffect(()=>{W(Zle())},[]),w.useEffect(()=>{t&&((async()=>{k(!0);try{const Le=await de.getCloudStatus();if(T(Le.is_authenticated),Le.is_authenticated){const Me=await de.getFilamentPresets();H(Me)}}catch(Le){console.error("Failed to fetch cloud presets:",Le),T(!1)}finally{k(!1)}})(),de.getSpoolCatalog().then(te).catch(console.error),de.getColorCatalog().then(fe).catch(console.error),de.getLocalPresets().then(Le=>J(Le.filament)).catch(console.error),r.length===0&&(async()=>{try{const Le=await de.getPrinters(),Me=await Promise.all(Le.map(Re=>de.getPrinterStatus(Re.id).catch(()=>null))),Oe=[];for(let Re=0;Re({cali_idx:we.slot_id,filament_id:we.filament_id,setting_id:we.setting_id||"",name:we.name,k_value:parseFloat(we.k_value)||0,n_coef:parseFloat(we.n_coef)||0,extruder_id:we.extruder_id,nozzle_diameter:we.nozzle_diameter}))}catch{}Oe.push({printer:{...$e,connected:tt},calibrations:pe})}me(Oe)}catch(Le){console.error("Failed to fetch printer calibrations:",Le)}})())},[t,r.length]);const O=w.useMemo(()=>Yle(D,new Set,ie),[D,ie]),K=w.useMemo(()=>{const Ae=Xle(D,ie),Le=oe.map(Oe=>Oe.manufacturer?.trim()).filter(Oe=>!!Oe),Me=new Set([...Ae,...Le]);return Array.from(Me).sort((Oe,Re)=>Oe.localeCompare(Re))},[D,ie,oe]),U=w.useMemo(()=>{const Ae=oe.map(Me=>Me.material?.trim()).filter(Me=>!!Me),Le=new Set([...Gle,...Ae]);return Array.from(Le).sort((Me,Oe)=>Me.localeCompare(Oe))},[oe]),ue=w.useMemo(()=>{const Ae=[];for(const Le of oe){const Me=Le.manufacturer?.trim(),Oe=Le.material?.trim();Me&&Oe&&Ae.push({brand:Me,material:Oe})}for(const Le of D){const Me=Cp(Le.name);Me.brand&&Me.material&&Ae.push({brand:Me.brand,material:Me.material})}for(const Le of ie){const Me=Cp(Le.name),Oe=Le.filament_vendor?.trim()||Me.brand,Re=Me.material;Oe&&Re&&Ae.push({brand:Oe,material:Re})}return Ae},[D,oe,ie]),I=w.useMemo(()=>{const Ae=new Map;for(const Le of ue){const Me=Le.brand.toLowerCase(),Oe=Le.material.toLowerCase();Ae.has(Me)||Ae.set(Me,new Set),Ae.get(Me).add(Oe)}return Ae},[ue]),G=w.useMemo(()=>{const Ae=new Map;for(const Le of ue){const Me=Le.brand.toLowerCase(),Oe=Le.material.toLowerCase();Ae.has(Oe)||Ae.set(Oe,new Set),Ae.get(Oe).add(Me)}return Ae},[ue]),X=w.useMemo(()=>{if(!u.material)return K;const Ae=u.material.toLowerCase(),Le=G.get(Ae);return!Le||Le.size===0?K:K.filter(Me=>Le.has(Me.toLowerCase()))},[K,u.material,G]),V=w.useMemo(()=>{if(!u.brand)return U;const Ae=u.brand.toLowerCase(),Le=I.get(Ae);return!Le||Le.size===0?U:U.filter(Me=>Le.has(Me.toLowerCase()))},[U,u.brand,I]),ee=w.useMemo(()=>Qle(u.slicer_filament,O),[u.slicer_filament,O]);w.useEffect(()=>{if(t){if(n){const Ae=n.rgba&&/^[0-9A-Fa-f]{8}$/.test(n.rgba)?n.rgba:"808080FF";if(m({material:n.material||"",subtype:n.subtype||"",brand:n.brand||"",color_name:n.color_name||"",rgba:Ae,label_weight:n.label_weight||1e3,core_weight:n.core_weight||250,core_weight_catalog_id:n.core_weight_catalog_id??null,weight_used:n.weight_used||0,slicer_filament:n.slicer_filament||"",note:n.note||"",cost_per_kg:n.cost_per_kg??null}),Q(n.slicer_filament_name||n.slicer_filament||""),n.k_profiles&&n.k_profiles.length>0){const Le=new Set;for(const Me of n.k_profiles)Me.cali_idx!==null&&Me.cali_idx!==void 0&&Le.add(`${Me.printer_id}:${Me.cali_idx}:${Me.extruder??"null"}`);Ce(Le)}else Ce(new Set)}else m(dO),Q(""),Ce(new Set),C(!1),N(1);f({}),v("filament"),g(!1)}},[t,n]),w.useEffect(()=>{t&&E.length>0&&Y(new Set(E.map(Ae=>String(Ae.printer.id))))},[t,E]);const se=(Ae,Le)=>{m(Me=>({...Me,[Ae]:Le})),Ae==="weight_used"&&g(!0),p[Ae]&&f(Me=>({...Me,[Ae]:void 0}))},ge=Ae=>{W(Le=>Jle(Ae,Le))},he=it({mutationFn:Ae=>de.createSpool(Ae),onSuccess:async Ae=>{be.size>0&&Ae?.id&&await ve(Ae.id),await l.invalidateQueries({queryKey:["inventory-spools"]}),s&&s([Ae]),c(o("inventory.spoolCreated"),"success"),e()},onError:Ae=>{c(Ae.message,"error")}}),le=it({mutationFn:({data:Ae,qty:Le})=>de.bulkCreateSpools(Ae,Le),onSuccess:async Ae=>{if(be.size>0)for(const Le of Ae)await ve(Le.id);await l.invalidateQueries({queryKey:["inventory-spools"]}),s&&s(Ae),c(o("inventory.spoolsCreated",{count:Ae.length}),"success"),e()},onError:Ae=>{c(Ae.message,"error")}}),B=it({mutationFn:Ae=>de.updateSpool(n.id,Ae),onSuccess:async()=>{n?.id&&await ve(n.id),await l.invalidateQueries({queryKey:["inventory-spools"]}),c(o("inventory.spoolUpdated"),"success"),e()},onError:Ae=>{c(Ae.message,"error")}}),R=it({mutationFn:()=>de.updateSpool(n.id,{tag_uid:null,tray_uuid:null,tag_type:null,data_origin:null}),onSuccess:async()=>{await l.invalidateQueries({queryKey:["inventory-spools"]}),c(o("inventory.tagDeleted","Tag removed"),"success"),e()},onError:Ae=>{c(Ae.message,"error")}}),{data:ae}=Xe({queryKey:["spool-assignments"],queryFn:()=>de.getAssignments(),enabled:t&&d}),_e=n?ae?.find(Ae=>Ae.spool_id===n.id):void 0,Se=it({mutationFn:()=>{if(!_e)throw new Error("No assignment");return de.unassignSpool(_e.printer_id,_e.ams_id,_e.tray_id)},onSuccess:async()=>{await l.invalidateQueries({queryKey:["spool-assignments"]}),c(o("inventory.unassignSuccess","Spool unassigned"),"success"),e()},onError:Ae=>{c(Ae.message,"error")}}),ve=async Ae=>{if(be.size===0){try{await de.saveSpoolKProfiles(Ae,[])}catch{}return}const Le=[];for(const Me of be){const[Oe,Re,$e]=Me.split(":"),Ye=parseInt(Oe),tt=parseInt(Re),pe=$e==="null"?0:parseInt($e),Fe=E.find(we=>we.printer.id===Ye);if(Fe){const we=Fe.calibrations.find(Ve=>Ve.cali_idx===tt);we&&Le.push({printer_id:Ye,extruder:pe,nozzle_diameter:we.nozzle_diameter||"0.4",k_value:we.k_value,name:we.name||null,cali_idx:we.cali_idx,setting_id:we.setting_id||null})}}if(Le.length>0)try{await de.saveSpoolKProfiles(Ae,Le)}catch(Me){console.error("Failed to save K-profiles:",Me)}};if(w.useEffect(()=>{if(!t)return;const Ae=Le=>{Le.key==="Escape"&&e()};return document.addEventListener("keydown",Ae),()=>document.removeEventListener("keydown",Ae)},[t,e]),!t)return null;const Te=()=>{const Ae=Vle(u,_);if(!Ae.isValid){f(Ae.errors),(Ae.errors.slicer_filament||Ae.errors.material||Ae.errors.brand||Ae.errors.subtype)&&v("filament");return}const Le=ee?.displayName||z||null,Me={material:u.material,subtype:u.subtype||null,brand:u.brand||null,color_name:u.color_name||null,rgba:u.rgba||null,label_weight:u.label_weight,core_weight:u.core_weight,core_weight_catalog_id:u.core_weight_catalog_id,slicer_filament:u.slicer_filament||null,slicer_filament_name:Le,nozzle_temp_min:null,nozzle_temp_max:null,note:u.note||null,cost_per_kg:u.cost_per_kg};(!d||b)&&(Me.weight_used=u.weight_used),d?B.mutate(Me):P>1?le.mutate({data:Me,qty:P}):he.mutate(Me)},ye=he.isPending||le.isPending||B.isPending||R.isPending||Se.isPending;return a.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[a.jsx("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-sm",onClick:e}),a.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:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary flex-shrink-0",children:[a.jsx("h2",{className:"text-lg font-semibold text-white",children:o(d?"inventory.editSpool":"inventory.addSpool")}),a.jsx("button",{onClick:e,className:"p-1 text-bambu-gray hover:text-white rounded transition-colors",children:a.jsx(Ht,{className:"w-5 h-5"})})]}),!d&&a.jsxs("div",{className:"flex items-center justify-between px-4 py-2 border-b border-bambu-dark-tertiary flex-shrink-0",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(uc,{className:"w-4 h-4 text-amber-400"}),a.jsx("span",{className:"text-sm text-white",children:o("inventory.quickAdd")})]}),a.jsx("button",{type:"button",onClick:()=>{C(!_),_||v("filament")},className:`relative inline-flex h-5 w-9 items-center rounded-full transition-colors ${_?"bg-bambu-green":"bg-bambu-dark-tertiary"}`,children:a.jsx("span",{className:`inline-block h-3.5 w-3.5 rounded-full bg-white transition-transform ${_?"translate-x-4":"translate-x-0.5"}`})})]}),a.jsxs("div",{className:"flex border-b border-bambu-dark-tertiary flex-shrink-0",children:[a.jsxs("button",{onClick:()=>v("filament"),className:`flex-1 px-4 py-2.5 text-sm font-medium flex items-center justify-center gap-2 transition-colors ${y==="filament"?"text-bambu-green border-b-2 border-bambu-green":"text-bambu-gray hover:text-white"}`,children:[a.jsx(nS,{className:"w-4 h-4"}),o("inventory.filamentInfoTab")]}),!_&&a.jsxs("button",{onClick:()=>v("pa-profile"),className:`flex-1 px-4 py-2.5 text-sm font-medium flex items-center justify-center gap-2 transition-colors ${y==="pa-profile"?"text-bambu-green border-b-2 border-bambu-green":"text-bambu-gray hover:text-white"}`,children:[a.jsx(Npe,{className:"w-4 h-4"}),o("inventory.paProfileTab"),j>0&&a.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded-full bg-bambu-green/20 text-bambu-green",children:j})]})]}),a.jsx("div",{className:"p-4 overflow-y-auto flex-1",style:{scrollbarGutter:"stable"},children:y==="filament"?a.jsxs("div",{className:"space-y-6",children:[a.jsxs("div",{children:[a.jsx("h3",{className:"text-sm font-semibold text-bambu-gray uppercase tracking-wide mb-3",children:o("inventory.filamentInfo")}),a.jsx(ece,{formData:u,updateField:se,cloudAuthenticated:A,loadingCloudPresets:F,presetInputValue:z,setPresetInputValue:Q,selectedPresetOption:ee,filamentOptions:O,availableBrands:X,availableMaterials:V,quickAdd:_,quantity:P,onQuantityChange:N,errors:p})]}),a.jsxs("div",{children:[a.jsx("h3",{className:"text-sm font-semibold text-bambu-gray uppercase tracking-wide mb-3",children:o("inventory.color")}),a.jsx(tce,{formData:u,updateField:se,recentColors:re,onColorUsed:ge,catalogColors:oe})]}),a.jsxs("div",{children:[a.jsx("h3",{className:"text-sm font-semibold text-bambu-gray uppercase tracking-wide mb-3",children:o("inventory.additional")}),a.jsx(nce,{formData:u,updateField:se,spoolCatalog:L,currencySymbol:i})]}),d&&n&&a.jsx("div",{children:a.jsx(Frt,{spoolId:n.id})})]}):a.jsx(rce,{formData:u,updateField:se,printersWithCalibrations:E,selectedProfiles:be,setSelectedProfiles:Ce,expandedPrinters:q,setExpandedPrinters:Y})}),a.jsxs("div",{className:"flex gap-2 p-4 border-t border-bambu-dark-tertiary flex-shrink-0",children:[d&&a.jsxs("div",{className:"flex gap-2 mr-auto",children:[a.jsxs(De,{variant:"secondary",onClick:()=>R.mutate(),disabled:ye||!n?.tag_uid,children:[a.jsx(xm,{className:"w-4 h-4"}),o("inventory.deleteTag","Delete Tag")]}),a.jsxs(De,{variant:"secondary",onClick:()=>Se.mutate(),disabled:ye||!_e,children:[a.jsx(gp,{className:"w-4 h-4"}),o("inventory.unassignSpool","Unassign")]})]}),a.jsxs("div",{className:"flex gap-2 ml-auto",children:[a.jsx(De,{variant:"secondary",onClick:e,children:o("common.cancel")}),a.jsx(De,{onClick:Te,disabled:ye,children:ye?a.jsxs(a.Fragment,{children:[a.jsx(pt,{className:"w-4 h-4 animate-spin"}),o("common.saving")]}):a.jsxs(a.Fragment,{children:[a.jsx(_s,{className:"w-4 h-4"}),o(d?"common.save":"inventory.addSpool")]})})]})]})]})]})}function Lrt({isOpen:t,onClose:e,columns:n,defaultColumns:r,onSave:i}){const{t:s}=Ft(),[o,l]=w.useState(n),[c,d]=w.useState(null),u=w.useRef(null);if(w.useEffect(()=>{t&&l(n.map(P=>({...P})))},[t,n]),w.useEffect(()=>{if(!t)return;const P=N=>{N.key==="Escape"&&e()};return window.addEventListener("keydown",P),()=>window.removeEventListener("keydown",P)},[t,e]),!t)return null;const m=P=>{l(N=>N.map((A,T)=>T===P?{...A,visible:!A.visible}:A))},p=(P,N)=>{N<0||N>=o.length||l(A=>{const T=[...A],[F]=T.splice(P,1);return T.splice(N,0,F),T})},f=(P,N)=>{u.current=N,d(N),P.dataTransfer.effectAllowed="move"},y=(P,N)=>{P.preventDefault(),P.dataTransfer.dropEffect="move";const A=u.current;A!==null&&A!==N&&(p(A,N),u.current=N,d(N))},v=P=>{P.preventDefault()},b=()=>{u.current=null,d(null)},g=()=>{l(r.map(P=>({...P})))},_=()=>{i(o),e()},C=o.filter(P=>P.visible).length;return a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",onClick:e,children:a.jsx(Tt,{className:"w-full max-w-md max-h-[80vh] flex flex-col",onClick:P=>P.stopPropagation(),children:a.jsxs(Mt,{className:"p-6 flex flex-col min-h-0",children:[a.jsx("h3",{className:"text-lg font-semibold text-white mb-2",children:s("inventory.configureColumns")}),a.jsxs("p",{className:"text-sm text-bambu-gray mb-4",children:[s("inventory.configureColumnsDesc"),a.jsxs("span",{className:"ml-2 text-bambu-gray/60",children:["(",C," ",s("inventory.of")," ",o.length," ",s("inventory.visible"),")"]})]}),a.jsx("div",{className:"space-y-1 overflow-y-auto flex-1 min-h-0 pr-1",children:o.map((P,N)=>a.jsxs("div",{className:`flex items-center gap-2 p-2 rounded-lg border transition-colors ${c===N?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary bg-bambu-dark-tertiary/50"} ${P.visible?"":"opacity-50"}`,draggable:!0,onDragStart:A=>f(A,N),onDragOver:A=>y(A,N),onDrop:v,onDragEnd:b,children:[a.jsx("div",{className:"cursor-grab text-bambu-gray/50 hover:text-bambu-gray",children:a.jsx(np,{className:"w-4 h-4"})}),a.jsx("span",{className:"flex-1 font-medium text-sm text-white",children:P.label}),a.jsxs("div",{className:"flex items-center gap-0.5",children:[a.jsx("button",{onClick:()=>p(N,N-1),disabled:N===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:a.jsx(dc,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>p(N,N+1),disabled:N===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:a.jsx(On,{className:"w-4 h-4"})})]}),a.jsx("button",{onClick:()=>m(N),className:`p-1.5 rounded transition-colors ${P.visible?"text-bambu-green hover:bg-bambu-green/10":"text-bambu-gray/50 hover:bg-bambu-dark-secondary"}`,title:P.visible?s("inventory.hideColumn"):s("inventory.showColumn"),children:P.visible?a.jsx(vl,{className:"w-4 h-4"}):a.jsx(Og,{className:"w-4 h-4"})})]},P.id))}),a.jsxs("div",{className:"flex items-center gap-3 mt-4 pt-4 border-t border-bambu-dark-tertiary",children:[a.jsxs(De,{variant:"secondary",onClick:g,className:"mr-auto",children:[a.jsx(co,{className:"w-4 h-4"}),s("inventory.reset")]}),a.jsx(De,{variant:"secondary",onClick:e,children:s("inventory.cancel")}),a.jsx(De,{onClick:_,children:s("inventory.applyChanges")})]})]})})})}function PY(t){return`${t.material}|${t.subtype||""}|${t.brand||""}|${t.color_name||""}|${t.rgba||""}|${t.label_weight}`}const ace="bambuddy-inventory-columns",uN=[{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:"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 Ort(){try{const t=localStorage.getItem(ace);if(t){const e=JSON.parse(t),n=new Set(uN.map(o=>o.id)),r=new Set(e.map(o=>o.id)),i=e.filter(o=>n.has(o.id)),s=uN.filter(o=>!r.has(o.id));return[...i,...s]}}catch{}return uN.map(t=>({...t}))}function Irt(t){try{localStorage.setItem(ace,JSON.stringify(t))}catch{}}function Rd(t,e=!1){return e&&t>=1e3?`${(t/1e3).toFixed(1)}kg`:`${Math.round(t)}g`}const zrt={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 F3(t,e="system"){if(!t)return"-";const n=Zn(t);return n?mF(n,e):"-"}const Urt={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",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")},uO={id:({spool:t})=>a.jsx("span",{className:"text-sm font-medium text-white",children:t.id}),added_time:({spool:t,dateFormat:e})=>a.jsx("span",{className:"text-sm text-bambu-gray",children:F3(t.created_at,e)}),encode_time:({spool:t,dateFormat:e})=>a.jsx("span",{className:"text-sm text-bambu-gray",children:F3(t.encode_time,e)}),last_used_time:({spool:t,dateFormat:e})=>a.jsx("span",{className:"text-sm text-bambu-gray",children:t.last_used?F3(t.last_used,e):"Never"}),rgba:({spool:t})=>a.jsx("div",{className:"flex items-center justify-center",children:a.jsx("span",{className:"w-5 h-5 rounded-full border border-black/20 flex-shrink-0",style:{backgroundColor:t.rgba?`#${t.rgba.substring(0,6)}`:"#808080"},title:t.rgba?`#${t.rgba.substring(0,6)}`:void 0})}),material:({spool:t})=>a.jsx("span",{className:"text-sm text-white",children:t.material}),subtype:({spool:t})=>a.jsx("span",{className:"text-sm text-bambu-gray",children:t.subtype||"-"}),color_name:({spool:t})=>a.jsx("span",{className:"text-sm text-bambu-gray",children:XP(t.color_name,t.rgba)||"-"}),brand:({spool:t})=>a.jsx("span",{className:"text-sm text-bambu-gray",children:t.brand||"-"}),slicer_filament:({spool:t})=>a.jsx("span",{className:"text-sm text-bambu-gray",title:t.slicer_filament||void 0,children:t.slicer_filament_name||t.slicer_filament||"-"}),location:({spool:t,assignmentMap:e})=>{const n=e[t.id];if(!n)return a.jsx("span",{className:"text-sm text-bambu-gray",children:"-"});const r=n.printer_name||`Printer ${n.printer_id}`,i=n.ams_id===254||n.ams_id===255,s=!i&&n.ams_id>=128,o=RS(n.ams_id,n.tray_id,s,i);return a.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:[r," ",o,n.ams_label?` (${n.ams_label})`:""]})},label_weight:({spool:t})=>a.jsx("span",{className:"text-sm text-white",children:Rd(t.label_weight)}),net:({remaining:t})=>a.jsx("span",{className:"text-sm text-white",children:Rd(t)}),gross:({spool:t,remaining:e})=>a.jsx("span",{className:"text-sm text-bambu-gray",children:Rd(e+t.core_weight)}),added_full:({spool:t})=>a.jsx("span",{className:"text-sm text-bambu-gray",children:t.added_full==null?"-":t.added_full?"Yes":"No"}),used:({spool:t})=>a.jsx("span",{className:"text-sm text-bambu-gray",children:t.weight_used>0?Rd(t.weight_used):"-"}),printed_total:()=>a.jsx("span",{className:"text-sm text-bambu-gray/50",children:"-"}),printed_since_weight:()=>a.jsx("span",{className:"text-sm text-bambu-gray/50",children:"-"}),note:({spool:t})=>a.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?a.jsx("span",{className:"text-sm text-bambu-gray",children:"-"}):a.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?a.jsx("span",{className:"text-sm text-bambu-gray font-mono",title:e,children:e.length>12?`${e.slice(0,6)}...${e.slice(-4)}`:e}):a.jsx("span",{className:"text-sm text-bambu-gray/50",children:"-"})},data_origin:({spool:t})=>a.jsx("span",{className:"text-sm text-bambu-gray",children:t.data_origin||"-"}),tag_type:({spool:t})=>a.jsx("span",{className:"text-sm text-bambu-gray",children:t.tag_type||"-"}),stock:({spool:t,t:e})=>t.slicer_filament?a.jsx("span",{className:"text-sm text-bambu-gray",children:"-"}):a.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})=>a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("div",{className:"flex-1 h-2 bg-bambu-dark-tertiary rounded-full overflow-hidden",children:a.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)}%`}})}),a.jsxs("span",{className:"text-xs text-bambu-gray min-w-[40px] text-right",children:[Math.round(t),"g"]})]}),spool_name:({spool:t,catalogMap:e})=>{const n=t.core_weight_catalog_id!=null?e[t.core_weight_catalog_id]:void 0;return a.jsx("span",{className:"text-sm text-bambu-gray",children:n?.name||"-"})},cost_per_kg:({spool:t,currencySymbol:e})=>a.jsx("span",{className:"text-sm text-bambu-gray",children:t.cost_per_kg!=null?`${e}${t.cost_per_kg.toFixed(2)}`:"-"}),weight_check:({spool:t,onSyncWeight:e})=>{const n=t.last_scale_weight;if(n==null)return a.jsx("span",{className:"text-sm text-bambu-gray/50",title:"No scale measurement",children:"-"});const r=t.core_weight||0,i=Math.max(0,t.label_weight-t.weight_used)+r;let s,o;n0?`+${Math.round(s)}`:`${Math.round(s)}`,c=o?`Scale: ${Math.round(n)}g Calculated: ${Math.round(i)}g Difference: ${l}g (within tolerance)`:`Scale: ${Math.round(n)}g Calculated: ${Math.round(i)}g diff --git a/static/index.html b/static/index.html index 5f0c57ec4..1277cb295 100644 --- a/static/index.html +++ b/static/index.html @@ -26,7 +26,7 @@ - +