diff --git a/CHANGELOG.md b/CHANGELOG.md index b7c819519..a32c46626 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,8 @@ All notable changes to Bambuddy will be documented in this file. - **Spoolman weight tracking now uses per-print grams for all spools, matching the internal Filament Inventory** ([#1119](https://github.com/maziggy/bambuddy/issues/1119), reported by @Moskito99) — Spoolman previously had two mutually-exclusive weight paths: AMS remain%×tray_weight auto-sync (default; only worked for Bambu Lab spools with valid RFID tray_weight) and per-print 3MF-grams tracking (only enabled when "Disable AMS Weight Sync" was toggled on). Non-BL spools without RFID fell through both paths — AMS auto-sync had no tray_weight to multiply, and the inventory_remaining fallback was wiped because activating Spoolman deletes the internal `spool_assignment` table — so Spoolman never saw a weight update for them. The internal Filament Inventory has no such gap: it always uses per-print 3MF grams as the primary path with AMS-remain% delta as fallback, and it works for every spool type. Spoolman now does the same: per-print tracking runs whenever Spoolman is enabled and is the only writer of `remaining_weight`. AMS auto-sync continues to maintain spool metadata and slot assignments but no longer touches weight (eliminating the double-count that would otherwise occur for BL spools with both paths active). `store_print_data` ([`spoolman_tracking.py:159`](backend/app/services/spoolman_tracking.py)) had its `disable_weight_sync` early-return removed; the three `sync_ams_tray` callsites (`main.py:1450` auto-sync, `spoolman.py:318` per-printer manual, `spoolman.py:517` sync-all) now hard-code `disable_weight_sync=True`. The `spoolman_disable_weight_sync` setting is now deprecated and a no-op — kept in the DB/UI for backwards compat. Behavioral consequence for existing users on the default flag (False): live AMS-based remaining_weight updates between prints stop happening; weight updates now arrive once per print completion with 3MF gram precision. Regression test in `test_spoolman_tracking.py::test_stores_tracking_when_disable_weight_sync_is_false` proves the early-return is gone. ### Fixed +- **Spoolman inventory: editing a spool's color name no longer "reverts" to the subtype on save** ([#1319](https://github.com/maziggy/bambuddy/issues/1319), reported by @MartinNYHC) — On Spoolman-backed inventory, changing a spool's color name in the edit dialog appeared to accept the new value but the inventory list column and the next edit-dialog open showed it back to the subtype string. **Three layers stacked on top of each other to produce this:** (1) `find_or_create_filament` at [`backend/app/services/spoolman.py:609`](backend/app/services/spoolman.py) matches existing Spoolman filaments by `material / name / color_hex / vendor` — `color_name` is intentionally not part of the match key (Spoolman doesn't standardise the field and most installs leave it null) — but when a match was found it returned the existing filament's id unchanged, silently dropping the new `color_name` value. The write never reached Spoolman. (2) On re-read, the helper at [`_spoolman_helpers.py:279`](backend/app/api/routes/_spoolman_helpers.py) falls back to `subtype` when `filament.color_name` is empty (without the fallback, Spoolman installs that don't fill the field would render every spool as "Unknown color"). The persisted value was still empty, so the read synthesised the column from `subtype`. (3) The edit form prefilled `color_name` from `spool.color_name` — which on Spoolman installs without `color_name` was the synth value (= subtype). If the user changed `subtype` but not `color_name`, the form silently round-tripped the OLD subtype back to Spoolman as if it were a real user-set `color_name`, which then started showing up as the persisted value on the next render — the exact "color reverts to subtype" pattern in the bug report. **Fixes:** (1) `find_or_create_filament` now patches the matched filament's `color_name` via the existing `patch_filament` PATCH wrapper when the request differs from what's stored. Convention on the parameter: `None` = "don't touch", `""` = explicit clear (patches Spoolman to `null`), any other string = set/update. (2) The PATCH route at [`spoolman_inventory.py:567`](backend/app/api/routes/spoolman_inventory.py) now uses Pydantic's `model_fields_set` to distinguish "field omitted" from "field explicitly set to null" — only the latter is a clear (mirrors the existing `storage_location` pattern at the same site). (3) The map helper now also returns `color_name_is_synthesized: bool` on every inventory record, and [`SpoolFormModal.tsx`](frontend/src/components/SpoolFormModal.tsx) checks it on prefill so the input starts blank when the value was synthesised from subtype — the user sees the real stored state and can't accidentally round-trip the synth value back. The read-side fallback is kept on purpose (the list-display "Unknown color" problem hasn't gone away — it's just that the form no longer treats the fallback as a real value). A `patch_filament` failure is caught and logged but doesn't block the match — the spool still links to the correct filament, only the colour-name update is dropped, which is the safer failure mode. **Regression tests:** 5 in [`test_spoolman_inventory_methods.py::TestFindOrCreateFilament`](backend/tests/unit/test_spoolman_inventory_methods.py) — patch-on-change, no-patch-when-unchanged, no-patch-when-`None`, clear-when-`""`-passed, and patch-failure-still-returns-match-id. 2 in [`test_spoolman_inventory_helpers.py::TestMapSpoolmanSpool`](backend/tests/unit/test_spoolman_inventory_helpers.py) — `color_name_is_synthesized` flag is `False` when a real value is stored, `True` when the fallback fires. 2 integration tests in [`test_spoolman_inventory_api.py`](backend/tests/integration/test_spoolman_inventory_api.py) — wire-level `color_name=null` clears (route translates to `""`), and `color_name` omitted from the PATCH body keeps the current value (route passes `None`). All 564 spoolman-tagged tests pass; ruff clean; frontend build clean. + - **Deleting an SSO user left orphan OIDC/MFA/camera-token rows on SQLite — blocked re-login and leaked auth state** ([#1285](https://github.com/maziggy/bambuddy/issues/1285), [PR #1295](https://github.com/maziggy/bambuddy/pull/1295) by @netscout2001) — On SQLite (default deployment) the `delete_user` route left orphan rows in `user_oidc_links`, `user_totp`, `user_otp_codes`, and `long_lived_tokens` because the project intentionally runs with `PRAGMA foreign_keys=OFF`, so the `ON DELETE CASCADE` declared on those tables never fired. **Reported symptom:** an admin deleted an OIDC-provisioned user, the user tried to re-login via SSO, the OIDC callback found the orphan `UserOIDCLink` pointing at the (now missing) user, failed to resolve it, and redirected to `account_inactive` instead of triggering `auto_create_users`. The same root cause was leaking MFA secrets (`user_totp`), pending email OTP codes (`user_otp_codes`), and per-user camera-stream tokens (`long_lived_tokens` — `verify()` would happily match by `lookup_prefix` even after the owning user was gone). PostgreSQL deployments were unaffected — cascade was firing there. **Fix:** mirrors the existing `APIKey` cleanup pattern in `delete_user` (introduced in PR #1182). `backend/app/api/routes/users.py:delete_user` now explicitly deletes `UserOIDCLink`, `UserTOTP`, `UserOTPCode`, and `LongLivedToken` rows owned by the user; also folds in `PrintBatch.created_by_id` cleanup (same `ondelete=SET NULL` SQLite-FK-off root cause, the `SET NULL` block at `users.py:393-407` was missing it). `backend/app/core/database.py:run_migrations` gains an idempotent startup orphan-cleanup that sweeps the four auth tables (`DELETE FROM WHERE user_id NOT IN (SELECT id FROM users)`), wrapped in `begin_nested()`, logged at INFO only when rows actually drop — so installations carrying orphans from before the fix are healed automatically without manual DB intervention. No-op on Postgres (cascade already fired) and idempotent on SQLite (second run finds nothing). `backend/app/api/routes/mfa.py:list_oidc_links` returns `""` for `provider_name` when `link.provider` is null instead of raising `AttributeError` — covers the symmetric edge case where a `UserOIDCLink` could reference an orphaned provider. **Tests:** 14 new/extended. `test_users_auth_cleanup.py` (new): 5 tests verify `delete_user` removes OIDC/TOTP/OTP/long-lived-token rows individually + combined-cleanup atomically. `test_oidc_relogin.py` (new): full end-to-end test reproducing the #1285 symptom — mocked IdP, first OIDC login, admin delete, second OIDC login proves `auto_create_users` fires again (and pinned the regression boundary by confirming the test fails without the fix). `test_orphan_auth_cleanup_migration.py` (new): 7 tests for per-table cleanup across all four auth tables, idempotency, no-op on fresh install, and survival of rows belonging to real users. `test_mfa_api.py` adds `TestListOidcLinksDefensiveProviderNull` for the null-check. `test_auth_api.py::test_delete_user` extended to assert all five auth-table side effects (`UserOIDCLink`, `UserTOTP`, `UserOTPCode`, `APIKey`, `LongLivedToken`). All 13 PR-added tests + 194 tests in extended files pass; ruff clean. **Reported and patched by @netscout2001.** - **Slicer bundle import 400/502/503 errors now land in the log so support bundles tell us why** ([#1312](https://github.com/maziggy/bambuddy/issues/1312), reported by @hasmar04) — Reporter hit `400 Bad Request` from `POST /api/v1/slicer/bundles` when uploading a Bambu Studio Printer Preset Bundle (`.bbscfg`); a second contributor had reported the same shape the day before. Same bundle file uploaded fine on Martin's dev machine, which strongly points at sidecar-side differences (image version, write permissions on `DATA_PATH/bundles`, TrueNAS Docker volume perms, etc.) — but triage was blocked because the sidecar's actual reject reason only made it as far as the FE toast. Bambuddy logged just the uvicorn-access line (`POST /api/v1/slicer/bundles HTTP/1.1 400`), with no detail in the support bundle. The route at `backend/app/api/routes/slicer_presets.py:import_slicer_bundle` now emits a `logger.warning` for each of the three failure shapes: **400 (`SlicerInputError`)** — sidecar's reject string is logged alongside the filename and byte count, so we can see "bundle rejected because `manifest.json` is missing" in the next support bundle without asking the reporter to copy the toast text. **503 (`SlicerApiUnavailableError`)** — logs the configured sidecar URL plus the exception detail (separates "URL wrong" from "sidecar offline"). **502 (`SlicerApiError`)** — logs filename + byte count + error string, useful when the sidecar's `DATA_PATH/bundles` write fails (the typical 5xx cause on this path). The 400 case is `WARNING` rather than `INFO` deliberately — it's an unexpected end-user-visible failure, not a routine event. Existing `test_import_bundle_sidecar_400_passes_through` now also asserts the reject reason AND the filename appear in caplog, so the support-bundle-includes-the-diagnostic contract is pinned. Doesn't fix #1312's actual root cause (sidecar-side, still under investigation with reporter) — but the next reporter we get on this code path will produce a bundle that contains the answer. diff --git a/backend/app/api/routes/_spoolman_helpers.py b/backend/app/api/routes/_spoolman_helpers.py index b3563f589..8578283b7 100644 --- a/backend/app/api/routes/_spoolman_helpers.py +++ b/backend/app/api/routes/_spoolman_helpers.py @@ -26,6 +26,7 @@ class MappedSpoolFields(TypedDict): subtype: str | None brand: str | None color_name: str | None + color_name_is_synthesized: bool rgba: str | None label_weight: int | None core_weight: int | None @@ -276,7 +277,12 @@ def _map_spoolman_spool(spool: dict) -> MappedSpoolFields: # prefix (the same string the `subtype` field already carries — typically # "Basic Red" / "PLA+ Black" / etc.) so the user can tell spools apart at # a glance even on Spoolman installs that don't fill color_name. - color_name: str | None = filament.get("color_name") or subtype or None + # color_name_is_synthesized: surfaced so the edit form can avoid prefilling + # the synth value back into the input, which would otherwise round-trip the + # subtype string as if it were a user-set color_name (#1319). + stored_color_name = filament.get("color_name") or None + color_name: str | None = stored_color_name or subtype or None + color_name_is_synthesized: bool = stored_color_name is None and color_name is not None nozzle_temp_raw = filament.get("settings_extruder_temp") nozzle_temp_min: int | None = _safe_int(nozzle_temp_raw, 0) or None @@ -286,6 +292,7 @@ def _map_spoolman_spool(spool: dict) -> MappedSpoolFields: "material": material, "subtype": subtype, "color_name": color_name, + "color_name_is_synthesized": color_name_is_synthesized, "rgba": rgba, "brand": vendor.get("name") or None, "label_weight": label_weight, diff --git a/backend/app/api/routes/spoolman_inventory.py b/backend/app/api/routes/spoolman_inventory.py index 1c5c4fd8a..cf20fd96b 100644 --- a/backend/app/api/routes/spoolman_inventory.py +++ b/backend/app/api/routes/spoolman_inventory.py @@ -564,7 +564,13 @@ async def update_spool( material = data.material if data.material is not None else cur_mat subtype = data.subtype if data.subtype is not None else cur_subtype brand = data.brand if data.brand is not None else (cur_vendor.get("name") or None) - color_name = data.color_name if data.color_name is not None else (cur_filament.get("color_name") or None) + # color_name uses model_fields_set so explicit null (clear) is distinguishable + # from "field omitted" (don't touch). find_or_create_filament's convention: + # None = don't touch, "" = explicit clear, "value" = set. + if "color_name" in data.model_fields_set: + color_name = data.color_name if data.color_name is not None else "" + else: + color_name = cur_filament.get("color_name") or None cur_color = (cur_filament.get("color_hex") or "808080").upper().removeprefix("#") rgba = data.rgba if data.rgba is not None else (cur_color + "FF") label_weight = data.label_weight if data.label_weight is not None else int(cur_filament.get("weight") or 1000) diff --git a/backend/app/services/spoolman.py b/backend/app/services/spoolman.py index 0a9fbcaf2..65055ac96 100644 --- a/backend/app/services/spoolman.py +++ b/backend/app/services/spoolman.py @@ -637,6 +637,26 @@ class SpoolmanClient: vendor_match = (not brand) or f_vendor_name == (brand or "").strip().lower() if material_match and name_match and color_match and vendor_match: + # #1319: color_name is not part of the match key, but if the + # caller passed a value that differs from what's stored, update + # the filament — otherwise the user's edit is silently dropped + # and the inventory read falls back to subtype, making it look + # like color_name "reverts" to the subtype on every save. + # Convention: None = "don't touch"; "" = explicit clear; any + # other string = set/update. + if color_name is not None: + existing = (f.get("color_name") or "").strip() + requested = color_name.strip() + if requested != existing: + payload_value: str | None = requested if requested else None + try: + await self.patch_filament(f["id"], {"color_name": payload_value}) + except Exception as e: + logger.warning( + "Failed to update color_name on filament %s: %s", + f["id"], + e, + ) return f["id"] filament = await self.create_filament( diff --git a/backend/tests/integration/test_spoolman_inventory_api.py b/backend/tests/integration/test_spoolman_inventory_api.py index 5c28d6d58..71fb1fd25 100644 --- a/backend/tests/integration/test_spoolman_inventory_api.py +++ b/backend/tests/integration/test_spoolman_inventory_api.py @@ -321,6 +321,42 @@ class TestSpoolmanInventoryCRUD: assert response.status_code == 200 mock_spoolman_client.update_spool_full.assert_called_once() + @pytest.mark.asyncio + @pytest.mark.integration + async def test_update_with_explicit_null_color_name_clears( + self, + async_client: AsyncClient, + spoolman_settings, + mock_spoolman_client, + ): + """#1319 follow-up: explicit color_name=null in the PATCH body means + "clear" — route translates it to "" so find_or_create_filament patches + the matched filament with color_name=None.""" + payload = {"color_name": None} + response = await async_client.patch("/api/v1/spoolman/inventory/spools/42", json=payload) + assert response.status_code == 200 + mock_spoolman_client.find_or_create_filament.assert_called_once() + kwargs = mock_spoolman_client.find_or_create_filament.call_args.kwargs + assert kwargs["color_name"] == "" + + @pytest.mark.asyncio + @pytest.mark.integration + async def test_update_without_color_name_keeps_current( + self, + async_client: AsyncClient, + spoolman_settings, + mock_spoolman_client, + ): + """#1319 follow-up: when color_name is omitted from the PATCH body the + current value is kept — None passed to find_or_create_filament means + "don't touch".""" + payload = {"note": "only updating note"} + response = await async_client.patch("/api/v1/spoolman/inventory/spools/42", json=payload) + assert response.status_code == 200 + kwargs = mock_spoolman_client.find_or_create_filament.call_args.kwargs + # SAMPLE_SPOOLMAN_SPOOL has no color_name field, so cur fallback is None. + assert kwargs["color_name"] is None + @pytest.mark.asyncio @pytest.mark.integration async def test_update_spool_not_found( diff --git a/backend/tests/unit/test_spoolman_inventory_helpers.py b/backend/tests/unit/test_spoolman_inventory_helpers.py index 93613528f..f11665f99 100644 --- a/backend/tests/unit/test_spoolman_inventory_helpers.py +++ b/backend/tests/unit/test_spoolman_inventory_helpers.py @@ -179,6 +179,23 @@ class TestMapSpoolmanSpool: } result = _map_spoolman_spool(spool) assert result["color_name"] == "Sunrise Orange" + # Real stored value — not synthesised from subtype. + assert result["color_name_is_synthesized"] is False + + def test_color_name_flags_synthesized_when_falling_back_to_subtype(self): + """#1319: when the read falls back to subtype, the response must flag it + so the edit form doesn't round-trip the synth value back to Spoolman.""" + spool = { + **MINIMAL_SPOOL, + "filament": { + **MINIMAL_SPOOL["filament"], + "name": "PLA Basic Red", + # No color_name field. + }, + } + result = _map_spoolman_spool(spool) + assert result["color_name"] == "Basic Red" + assert result["color_name_is_synthesized"] is True def test_color_name_falls_back_to_subtype_when_field_missing(self): """Spoolman doesn't standardise color_name; the LinkSpoolModal would @@ -216,6 +233,8 @@ class TestMapSpoolmanSpool: result = _map_spoolman_spool(spool) assert result["subtype"] is None assert result["color_name"] is None + # No synth happened — nothing to fall back to. + assert result["color_name_is_synthesized"] is False def test_color_hex_with_hash_prefix_stripped(self): spool = {**MINIMAL_SPOOL, "filament": {**MINIMAL_SPOOL["filament"], "color_hex": "#00FF00"}} diff --git a/backend/tests/unit/test_spoolman_inventory_methods.py b/backend/tests/unit/test_spoolman_inventory_methods.py index 7b3098229..fb0d050ce 100644 --- a/backend/tests/unit/test_spoolman_inventory_methods.py +++ b/backend/tests/unit/test_spoolman_inventory_methods.py @@ -322,6 +322,81 @@ class TestFindOrCreateFilament: result = await client.find_or_create_filament("PLA", "Basic", "Bambu Lab", "FF0000", 1000) assert result == 7 + @pytest.mark.asyncio + async def test_patches_color_name_on_existing_filament_when_changed(self, client): + """#1319: color_name is not part of the match key, so when a caller + updates a spool with a new color_name and the material/name/color/vendor + still match an existing filament, the existing filament's color_name + must be patched — otherwise the user's edit is silently dropped.""" + existing = {**SAMPLE_FILAMENT, "color_name": None} + with ( + patch.object(client, "find_or_create_vendor", AsyncMock(return_value=3)), + patch.object(client, "get_filaments", AsyncMock(return_value=[existing])), + patch.object(client, "patch_filament", AsyncMock(return_value={"id": 7})) as mock_patch, + ): + result = await client.find_or_create_filament( + "PLA", "Basic", "Bambu Lab", "FF0000", 1000, color_name="Sunny Yellow" + ) + assert result == 7 + mock_patch.assert_called_once_with(7, {"color_name": "Sunny Yellow"}) + + @pytest.mark.asyncio + async def test_does_not_patch_when_color_name_unchanged(self, client): + existing = {**SAMPLE_FILAMENT, "color_name": "Sunny Yellow"} + with ( + patch.object(client, "find_or_create_vendor", AsyncMock(return_value=3)), + patch.object(client, "get_filaments", AsyncMock(return_value=[existing])), + patch.object(client, "patch_filament", AsyncMock()) as mock_patch, + ): + result = await client.find_or_create_filament( + "PLA", "Basic", "Bambu Lab", "FF0000", 1000, color_name="Sunny Yellow" + ) + assert result == 7 + mock_patch.assert_not_called() + + @pytest.mark.asyncio + async def test_does_not_patch_when_color_name_empty(self, client): + """An empty/None color_name should not clobber an existing value.""" + existing = {**SAMPLE_FILAMENT, "color_name": "Sunny Yellow"} + with ( + patch.object(client, "find_or_create_vendor", AsyncMock(return_value=3)), + patch.object(client, "get_filaments", AsyncMock(return_value=[existing])), + patch.object(client, "patch_filament", AsyncMock()) as mock_patch, + ): + result = await client.find_or_create_filament("PLA", "Basic", "Bambu Lab", "FF0000", 1000, color_name=None) + assert result == 7 + mock_patch.assert_not_called() + + @pytest.mark.asyncio + async def test_clears_color_name_when_empty_string_passed(self, client): + """#1319 follow-up: empty string means "explicit clear" — the route + layer translates a wire-level null into "" so the user can blank the + field on a previously-set spool.""" + existing = {**SAMPLE_FILAMENT, "color_name": "Sunny Yellow"} + with ( + patch.object(client, "find_or_create_vendor", AsyncMock(return_value=3)), + patch.object(client, "get_filaments", AsyncMock(return_value=[existing])), + patch.object(client, "patch_filament", AsyncMock(return_value={"id": 7})) as mock_patch, + ): + result = await client.find_or_create_filament("PLA", "Basic", "Bambu Lab", "FF0000", 1000, color_name="") + assert result == 7 + mock_patch.assert_called_once_with(7, {"color_name": None}) + + @pytest.mark.asyncio + async def test_patch_failure_does_not_block_match(self, client): + """A patch_filament failure must not prevent returning the matched id — + save should still link the spool to the correct filament.""" + existing = {**SAMPLE_FILAMENT, "color_name": None} + with ( + patch.object(client, "find_or_create_vendor", AsyncMock(return_value=3)), + patch.object(client, "get_filaments", AsyncMock(return_value=[existing])), + patch.object(client, "patch_filament", AsyncMock(side_effect=SpoolmanUnavailableError("boom"))), + ): + result = await client.find_or_create_filament( + "PLA", "Basic", "Bambu Lab", "FF0000", 1000, color_name="Sunny Yellow" + ) + assert result == 7 + @pytest.mark.asyncio async def test_creates_filament_when_no_match(self, client): new_filament = {"id": 99, "name": "PETG Pro"} diff --git a/frontend/src/api/client.ts b/frontend/src/api/client.ts index 4a2e37cbd..a24b28299 100644 --- a/frontend/src/api/client.ts +++ b/frontend/src/api/client.ts @@ -2345,6 +2345,11 @@ export interface InventorySpool { material: string; subtype: string | null; color_name: string | null; + // True when color_name was synthesised from subtype because Spoolman has no + // stored value (Spoolman-backed inventory only). The edit form uses this to + // leave the input blank, so the user doesn't round-trip the synth value + // back to Spoolman as if it were a real user-set color_name (#1319). + color_name_is_synthesized?: boolean; rgba: string | null; // Multi-colour gradient stops (#1154): comma-separated 6/8-char hex. extra_colors: string | null; diff --git a/frontend/src/components/SpoolFormModal.tsx b/frontend/src/components/SpoolFormModal.tsx index f97261fa5..75ca938cf 100644 --- a/frontend/src/components/SpoolFormModal.tsx +++ b/frontend/src/components/SpoolFormModal.tsx @@ -303,7 +303,11 @@ export function SpoolFormModal({ material: spool.material || '', subtype: spool.subtype || '', brand: spool.brand || '', - color_name: spool.color_name || '', + // #1319: leave color_name blank when the backend reports it was + // synthesised from subtype — otherwise the form would round-trip + // the synth value to Spoolman on save as if the user had set it, + // which is what produced the "color reverts to subtype" symptom. + color_name: spool.color_name_is_synthesized ? '' : (spool.color_name || ''), rgba: validRgba, extra_colors: spool.extra_colors || '', effect_type: spool.effect_type || '', diff --git a/static/assets/index-BfJWmysU.js b/static/assets/index-D5ddq2Sh.js similarity index 99% rename from static/assets/index-BfJWmysU.js rename to static/assets/index-D5ddq2Sh.js index 3d90442d8..bbf75bfb3 100644 --- a/static/assets/index-BfJWmysU.js +++ b/static/assets/index-D5ddq2Sh.js @@ -8722,7 +8722,7 @@ Accuracy: ${t.time_accuracy.toFixed(0)}%`:t.actual_time_seconds?`Actual: ${ds(t. `+a.map(([s,o])=>n+" "+JSON.stringify(s)+": "+KI(o,e+1)).join(`, `)+` `+n+"}"}return String(t)}function Mat({setting:t,onClose:e,onDeleted:n,onDuplicate:a,onEdit:i,hasPermission:s,t:o}){const{showToast:l}=rn(),c=en(),[d,u]=v.useState(!1),{data:m,isLoading:p}=We({queryKey:["cloudSettingDetail",t.setting_id],queryFn:()=>se.getCloudSettingDetail(t.setting_id)}),f=it({mutationFn:()=>se.deleteCloudSetting(t.setting_id),onSuccess:()=>{l(o("profiles.presets.toast.deleted")),c.invalidateQueries({queryKey:["cloudSettings"]}),n()},onError:g=>l(g.message,"error")}),b=vS(t.setting_id),w=aU(t.name,m?.setting?.inherits);return r.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:r.jsx(Ct,{className:"w-full max-w-3xl max-h-[90vh] flex flex-col overflow-hidden",children:r.jsxs(At,{className:"p-0 flex flex-col min-h-0 flex-1",children:[r.jsxs("div",{className:"flex-shrink-0 flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("h2",{className:"text-xl font-semibold text-white truncate",children:t.name}),b&&r.jsx("span",{className:"px-2 py-0.5 text-xs font-medium bg-bambu-green/20 text-bambu-green rounded-full",children:o("profiles.presets.editable")})]}),r.jsxs("div",{className:"flex items-center gap-2 mt-1 text-sm text-bambu-gray",children:[r.jsx("span",{className:"capitalize",children:o(`profiles.presets.types.${t.type}`)}),w.printer&&r.jsxs(r.Fragment,{children:[r.jsx("span",{children:"•"}),r.jsx("span",{children:w.printer})]})]})]}),r.jsx("button",{onClick:e,className:"p-2 text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary rounded-lg transition-colors",children:r.jsx(Bt,{className:"w-5 h-5"})})]}),r.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto p-4",children:p?r.jsx("div",{className:"flex items-center justify-center py-16",children:r.jsx(ut,{className:"w-8 h-8 text-bambu-green animate-spin"})}):m?r.jsx("pre",{className:"text-xs text-bambu-gray font-mono whitespace-pre-wrap break-all bg-bambu-dark p-4 rounded-lg border border-bambu-dark-tertiary overflow-x-auto max-w-full",children:KI(m)}):r.jsx("div",{className:"text-center py-16 text-bambu-gray",children:o("profiles.presets.failedToLoadDetails")})}),d?r.jsxs("div",{className:"flex-shrink-0 p-4 border-t border-bambu-dark-tertiary bg-red-500/5",children:[r.jsxs("div",{className:"flex items-center gap-2 mb-3 text-red-400",children:[r.jsx(Nn,{className:"w-5 h-5"}),r.jsx("span",{className:"font-medium",children:o("profiles.presets.deleteConfirm")})]}),r.jsx("p",{className:"text-sm text-bambu-gray mb-4",children:o("profiles.presets.deleteWarning",{name:t.name})}),r.jsxs("div",{className:"flex gap-2",children:[r.jsx(Me,{variant:"secondary",onClick:()=>u(!1),disabled:f.isPending,className:"flex-1",children:o("common.cancel")}),r.jsxs(Me,{variant:"danger",onClick:()=>f.mutate(),disabled:f.isPending,className:"flex-1",children:[f.isPending?r.jsx(ut,{className:"w-4 h-4 animate-spin"}):r.jsx(Jt,{className:"w-4 h-4"}),o("common.delete")]})]})]}):r.jsx("div",{className:"flex-shrink-0 p-4 border-t border-bambu-dark-tertiary",children:r.jsxs("div",{className:"flex gap-2",children:[r.jsx(Me,{variant:"secondary",onClick:e,className:"flex-1",children:o("common.close")}),r.jsxs(Me,{variant:"secondary",onClick:a,disabled:!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.presets.noDuplicatePermission"),children:[r.jsx(Mi,{className:"w-4 h-4"}),o("profiles.presets.duplicate")]}),b&&r.jsxs(r.Fragment,{children:[r.jsxs(Me,{variant:"secondary",onClick:i,disabled:p||!m||!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.presets.noEditPermission"),children:[r.jsx(oi,{className:"w-4 h-4"}),o("common.edit")]}),r.jsx(Me,{variant:"danger",onClick:()=>u(!0),disabled:!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.presets.noDeletePermission"),children:r.jsx(Jt,{className:"w-4 h-4"})})]})]})})]})})})}function Ece(){try{const t=localStorage.getItem("bambusy_preset_templates");return t?JSON.parse(t):[]}catch{return[]}}function Dce(t){localStorage.setItem("bambusy_preset_templates",JSON.stringify(t))}function Eat({onClose:t,onApply:e,t:n}){const{showToast:a}=rn(),[i,s]=v.useState(Ece),[o,l]=v.useState("all"),[c,d]=v.useState(null),[u,m]=v.useState(""),[p,f]=v.useState(""),[b,w]=v.useState("{}"),[g,x]=v.useState(null),[_,N]=v.useState(null),C=o==="all"?i:i.filter(H=>H.type===o),P=H=>{s(H),Dce(H)},T=H=>{const R=i.filter(Z=>Z.id!==H);P(R),N(null),a(n("profiles.templates.toast.deleted"))},A=H=>{d(H.id),m(H.name),f(H.description),w(JSON.stringify(H.settings,null,2)),x(null)},F=()=>{if(!(!c||!u.trim()))try{const H=JSON.parse(b),R=i.map(Z=>Z.id===c?{...Z,name:u.trim(),description:p.trim(),settings:H}:Z);P(R),d(null),a(n("profiles.templates.toast.updated"))}catch(H){x(H.message)}},S=()=>{d(null),m(""),f(""),w("{}"),x(null)},M=H=>{const R=i.map(Z=>Z.id===H?{...Z,showInModal:!Z.showInModal}:Z);P(R)},z={filament:{label:n("profiles.presets.types.filament"),icon:ST,color:"text-amber-400"},print:{label:n("profiles.presets.types.process"),icon:uu,color:"text-blue-400"},printer:{label:n("profiles.presets.types.printer"),icon:pr,color:"text-purple-400"}},I=_?i.find(H=>H.id===_):null;return v.useEffect(()=>{const H=R=>{R.key==="Escape"&&(_?N(null):c?S():t())};return window.addEventListener("keydown",H),()=>window.removeEventListener("keydown",H)},[_,c,t]),r.jsxs("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:[I&&r.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-60",children:r.jsx(Ct,{className:"w-full max-w-md",children:r.jsxs(At,{className:"p-6",children:[r.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[r.jsx("div",{className:"p-2 bg-red-500/20 rounded-lg",children:r.jsx(Nn,{className:"w-6 h-6 text-red-400"})}),r.jsxs("div",{children:[r.jsx("h3",{className:"text-lg font-semibold text-white",children:n("profiles.templates.deleteTitle")}),r.jsx("p",{className:"text-sm text-bambu-gray",children:n("profiles.templates.deleteWarning")})]})]}),r.jsx("p",{className:"text-white mb-6",children:n("profiles.templates.deleteConfirm",{name:I.name})}),r.jsxs("div",{className:"flex gap-2",children:[r.jsx(Me,{variant:"secondary",onClick:()=>N(null),className:"flex-1",children:n("common.cancel")}),r.jsxs(Me,{onClick:()=>T(_),className:"flex-1 bg-red-500 hover:bg-red-600",children:[r.jsx(Jt,{className:"w-4 h-4"}),n("common.delete")]})]})]})})}),r.jsx(Ct,{className:"w-full max-w-2xl max-h-[80vh] flex flex-col",children:r.jsxs(At,{className:"p-0 flex flex-col h-full",children:[r.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[r.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[r.jsx(Dg,{className:"w-5 h-5 text-amber-400"}),n("profiles.templates.title")]}),r.jsx("button",{onClick:t,className:"text-bambu-gray hover:text-white",children:r.jsx(Bt,{className:"w-5 h-5"})})]}),r.jsxs("div",{className:"flex items-center gap-2 p-4 border-b border-bambu-dark-tertiary",children:[r.jsx("span",{className:"text-sm text-bambu-gray",children:n("profiles.templates.typeFilter")}),["all","filament","print","printer"].map(H=>r.jsx("button",{onClick:()=>l(H),className:`px-3 py-1 text-sm rounded-lg transition-colors ${o===H?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:H==="all"?n("common.all"):z[H].label},H))]}),r.jsx("div",{className:"flex-1 overflow-y-auto p-4",children:C.length===0?r.jsxs("div",{className:"text-center py-12 text-bambu-gray",children:[r.jsx(Dg,{className:"w-12 h-12 mx-auto mb-4 opacity-30"}),r.jsx("p",{children:n("profiles.templates.noTemplates")}),r.jsx("p",{className:"text-sm mt-1",children:n("profiles.templates.createFirst")})]}):r.jsx("div",{className:"space-y-2",children:C.map(H=>{const R=z[H.type],Z=R.icon;return c===H.id?r.jsxs("div",{className:"p-4 bg-bambu-dark rounded-lg border border-bambu-green",children:[r.jsxs("div",{className:"grid grid-cols-2 gap-3 mb-3",children:[r.jsx("input",{type:"text",value:u,onChange:re=>m(re.target.value),placeholder:n("profiles.templates.namePlaceholder"),className:"px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none",autoFocus:!0}),r.jsx("input",{type:"text",value:p,onChange:re=>f(re.target.value),placeholder:n("profiles.templates.descriptionPlaceholder"),className:"px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none"})]}),r.jsxs("div",{className:"mb-3",children:[r.jsx("label",{className:"text-xs text-bambu-gray mb-1 block",children:n("profiles.templates.settingsJson")}),r.jsx("textarea",{value:b,onChange:re=>{w(re.target.value),x(null)},rows:6,className:`w-full px-3 py-2 bg-bambu-dark-secondary border rounded text-white text-sm font-mono focus:outline-none ${g?"border-red-500":"border-bambu-dark-tertiary focus:border-bambu-green"}`}),g&&r.jsx("p",{className:"text-xs text-red-400 mt-1",children:g})]}),r.jsxs("div",{className:"flex gap-2",children:[r.jsxs(Me,{size:"sm",onClick:F,disabled:!u.trim(),children:[r.jsx(us,{className:"w-4 h-4"}),"Save"]}),r.jsx(Me,{size:"sm",variant:"secondary",onClick:S,children:"Cancel"})]})]},H.id):r.jsxs("div",{className:"flex items-center gap-3 p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary hover:border-bambu-gray-dark transition-colors",children:[r.jsx(Z,{className:`w-5 h-5 ${R.color} flex-shrink-0`}),r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsx("p",{className:"text-sm font-medium text-white",children:H.name}),r.jsx("p",{className:"text-xs text-bambu-gray truncate",children:H.description})]}),r.jsx("span",{className:"text-xs text-bambu-gray-dark px-2 py-1 bg-bambu-dark-secondary rounded",children:n("profiles.templates.fieldsCount",{count:Object.keys(H.settings).length})}),r.jsx("button",{onClick:()=>M(H.id),className:`p-1 transition-colors ${H.showInModal?"text-bambu-green hover:text-bambu-green/70":"text-bambu-gray hover:text-white"}`,title:H.showInModal?n("profiles.templates.shownInModals"):n("profiles.templates.hiddenInModals"),children:H.showInModal?r.jsx(Dl,{className:"w-4 h-4"}):r.jsx(sb,{className:"w-4 h-4"})}),r.jsx("button",{onClick:()=>e(H),className:"px-3 py-1 text-xs bg-bambu-green/20 text-bambu-green rounded hover:bg-bambu-green/30 transition-colors",children:n("profiles.templates.apply")}),r.jsx("button",{onClick:()=>A(H),className:"p-1 text-bambu-gray hover:text-white",title:n("common.edit"),children:r.jsx(oi,{className:"w-4 h-4"})}),r.jsx("button",{onClick:()=>N(H.id),className:"p-1 text-bambu-gray hover:text-red-400",title:n("common.delete"),children:r.jsx(Jt,{className:"w-4 h-4"})})]},H.id)})})})]})})]})}function Fce({onClose:t,leftPreset:e,rightPreset:n,leftLabel:a,rightLabel:i,t:s}){const[o,l]=v.useState("changes"),[c,d]=v.useState(""),u=v.useMemo(()=>{const b=new Set([...Object.keys(e),...Object.keys(n)]),w=[];for(const g of b){if(g==="inherits"||g==="version")continue;const x=e[g],_=n[g],N=g in e,C=g in n;let P;!N&&C?P="added":N&&!C?P="removed":JSON.stringify(x)!==JSON.stringify(_)?P="changed":P="same",w.push({key:g,left:x,right:_,status:P})}return w.sort((g,x)=>{const _={changed:0,added:1,removed:2,same:3};return _[g.status]!==_[x.status]?_[g.status]-_[x.status]:g.key.localeCompare(x.key)})},[e,n]),m=v.useMemo(()=>{let b=[...u];if(o==="changes"&&(b=b.filter(w=>w.status!=="same")),c){const w=c.toLowerCase();b=b.filter(g=>g.key.toLowerCase().includes(w)||String(g.left).toLowerCase().includes(w)||String(g.right).toLowerCase().includes(w))}return b},[u,o,c]),p=v.useMemo(()=>({added:u.filter(b=>b.status==="added").length,removed:u.filter(b=>b.status==="removed").length,changed:u.filter(b=>b.status==="changed").length,same:u.filter(b=>b.status==="same").length}),[u]),f=b=>{if(b===void 0)return"—";if(b===null)return"null";if(Array.isArray(b))return b.length===0?"[]":b.length===1?String(b[0]):b.join(", ");if(typeof b=="object")return JSON.stringify(b);const w=String(b);if(w.includes("\\n")||w.length>100){const g=w.split("\\n").length;if(g>1)return`[${g} lines of G-code/script]`;if(w.length>100)return w.substring(0,100)+"…"}return w};return v.useEffect(()=>{const b=w=>{w.key==="Escape"&&t()};return window.addEventListener("keydown",b),()=>window.removeEventListener("keydown",b)},[t]),r.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:r.jsx(Ct,{className:"w-full max-w-4xl max-h-[85vh] flex flex-col overflow-hidden",children:r.jsxs(At,{className:"p-0 flex flex-col min-h-0 flex-1",children:[r.jsxs("div",{className:"flex-shrink-0 flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[r.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[r.jsx(Zx,{className:"w-5 h-5 text-blue-400"}),s("profiles.diff.title")]}),r.jsx("button",{onClick:t,className:"text-bambu-gray hover:text-white",children:r.jsx(Bt,{className:"w-5 h-5"})})]}),r.jsxs("div",{className:"flex-shrink-0 grid grid-cols-2 gap-4 p-4 border-b border-bambu-dark-tertiary bg-bambu-dark",children:[r.jsxs("div",{className:"text-center",children:[r.jsx("span",{className:"text-sm text-bambu-gray",children:s("profiles.diff.left")}),r.jsx("p",{className:"text-white font-medium truncate",children:a})]}),r.jsxs("div",{className:"text-center",children:[r.jsx("span",{className:"text-sm text-bambu-gray",children:s("profiles.diff.right")}),r.jsx("p",{className:"text-white font-medium truncate",children:i})]})]}),r.jsxs("div",{className:"flex-shrink-0 flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"flex items-center gap-4 text-sm",children:[r.jsxs("span",{className:"flex items-center gap-1 text-green-400",children:[r.jsx(ar,{className:"w-3.5 h-3.5"}),p.added," ",s("profiles.diff.added")]}),r.jsxs("span",{className:"flex items-center gap-1 text-red-400",children:[r.jsx(tC,{className:"w-3.5 h-3.5"}),p.removed," ",s("profiles.diff.removed")]}),r.jsxs("span",{className:"flex items-center gap-1 text-amber-400",children:[r.jsx(XN,{className:"w-3.5 h-3.5"}),p.changed," ",s("profiles.diff.changed")]}),r.jsxs("span",{className:"flex items-center gap-1 text-bambu-gray",children:[r.jsx(sE,{className:"w-3.5 h-3.5"}),p.same," ",s("profiles.diff.same")]})]}),r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsxs("div",{className:"relative",children:[r.jsx(Sr,{className:"absolute left-2 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),r.jsx("input",{type:"text",value:c,onChange:b=>d(b.target.value),placeholder:s("profiles.diff.searchFields"),className:"pl-8 pr-3 py-1.5 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none w-48"})]}),p.same>0&&r.jsxs("div",{className:"flex rounded overflow-hidden border border-bambu-dark-tertiary",children:[r.jsx("button",{onClick:()=>l("changes"),className:`px-3 py-1.5 text-sm transition-colors ${o==="changes"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:s("profiles.diff.changes")}),r.jsx("button",{onClick:()=>l("all"),className:`px-3 py-1.5 text-sm transition-colors ${o==="all"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:s("common.all")})]})]})]}),r.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto",children:m.length===0?r.jsxs("div",{className:"text-center py-12 text-bambu-gray",children:[r.jsx(sE,{className:"w-12 h-12 mx-auto mb-4 opacity-30"}),r.jsx("p",{children:s(o==="changes"?"profiles.diff.noDifferences":"profiles.diff.noFieldsMatch")})]}):r.jsxs("table",{className:"w-full",children:[r.jsx("thead",{className:"sticky top-0 bg-bambu-dark-secondary",children:r.jsxs("tr",{className:"text-sm text-bambu-gray border-b border-bambu-dark-tertiary",children:[r.jsx("th",{className:"text-left p-3 w-1/3",children:s("profiles.diff.field")}),r.jsx("th",{className:"text-left p-3 w-1/3",children:a}),r.jsx("th",{className:"text-left p-3 w-1/3",children:i})]})}),r.jsx("tbody",{children:m.map(b=>{const w={added:"bg-green-500/10",removed:"bg-red-500/10",changed:"bg-amber-500/10",same:""}[b.status],g={added:r.jsx(ar,{className:"w-3.5 h-3.5 text-green-400"}),removed:r.jsx(tC,{className:"w-3.5 h-3.5 text-red-400"}),changed:r.jsx(XN,{className:"w-3.5 h-3.5 text-amber-400"}),same:r.jsx(sE,{className:"w-3.5 h-3.5 text-bambu-gray-dark"})}[b.status];return r.jsxs("tr",{className:`border-b border-bambu-dark-tertiary ${w}`,children:[r.jsx("td",{className:"p-3",children:r.jsxs("div",{className:"flex items-center gap-2",children:[g,r.jsx("span",{className:"text-sm text-white font-mono",children:b.key})]})}),r.jsx("td",{className:"p-3",children:r.jsx("span",{className:`text-sm font-mono break-all ${b.status==="removed"?"text-red-300":b.status==="changed"?"text-white":"text-bambu-gray"}`,children:f(b.left)})}),r.jsx("td",{className:"p-3",children:r.jsx("span",{className:`text-sm font-mono break-all ${b.status==="added"?"text-green-300":b.status==="changed"?"text-white":"text-bambu-gray"}`,children:f(b.right)})})]},b.key)})})]})})]})})})}function Dat({onClose:t,initialData:e,allPresets:n,t:a}){const{showToast:i}=rn(),s=en(),o=!!e?.setting_id,[l,c]=v.useState("common"),[d,u]=v.useState(e?.type||"filament"),[m,p]=v.useState(e?.name?o?e.name:`${e.name} (Copy)`:""),[f,b]=v.useState(e?.base_id||""),[w,g]=v.useState(""),[x,_]=v.useState(e?.setting||{inherits:""}),[N,C]=v.useState(JSON.stringify(e?.setting||{inherits:""},null,2)),[P,T]=v.useState(null),[A,F]=v.useState(""),[S,M]=v.useState(!1),[z,I]=v.useState(""),[H,R]=v.useState(!1),[Z,re]=v.useState(Ece),[J,de]=v.useState(!1),[me,ue]=v.useState(""),[W,ae]=v.useState(""),[pe,ye]=v.useState(!0),[Te,$]=v.useState(null),[K,D]=v.useState(!1),j=v.useMemo(()=>({filament:n.filament,print:n.process,printer:n.printer})[d]||[],[n,d]),B=v.useMemo(()=>j.filter(Ie=>vS(Ie.setting_id)),[j]),{data:X}=We({queryKey:["cloudFields",d],queryFn:()=>se.getCloudFields(d==="print"?"process":d),staleTime:1e3*60*60}),{data:O}=We({queryKey:["allPresetDetails",d,B.map(Ie=>Ie.setting_id).join(",")],queryFn:async()=>{const Ie={};for(let rt=0;rt{try{const Ce=await se.getCloudSettingDetail(tt.setting_id);return{id:tt.setting_id,detail:Ce}}catch{return null}}))).forEach(tt=>{tt&&(Ie[tt.id]=tt.detail)})}return Ie},enabled:B.length>0,staleTime:1e3*60*10}),{data:ie,isLoading:U}=We({queryKey:["cloudSettingDetail",f],queryFn:()=>se.getCloudSettingDetail(f),enabled:!!f});v.useEffect(()=>{l!=="json"&&C(JSON.stringify(x,null,2))},[x,l]);const G=v.useMemo(()=>({filament:n.filament,print:n.process,printer:n.printer}[d]||[]).filter(Ke=>!vS(Ke.setting_id)).sort((Ke,rt)=>Ke.name.localeCompare(rt.name)),[n,d]);v.useEffect(()=>{if(!f)return;const Ie=G.find(Ke=>Ke.setting_id===f);Ie&&(g(Ie.name),o||(_({inherits:Ie.name}),C(JSON.stringify({inherits:Ie.name},null,2))))},[f,G,o]);const Y=v.useMemo(()=>{const Ie=X?.fields||[],Ke=new Set(Ie.map(tt=>tt.key)),rt=new Set,st=new Set(["inherits","updated_time","compatible_printers","compatible_prints"]);O&&Object.values(O).forEach(tt=>{tt?.setting&&Object.keys(tt.setting).forEach(Ce=>{!Ke.has(Ce)&&!st.has(Ce)&&rt.add(Ce)})}),Object.keys(x).forEach(tt=>{!Ke.has(tt)&&!st.has(tt)&&rt.add(tt)});const Le=Array.from(rt).sort().map(tt=>({key:tt,label:tt.replace(/_/g," ").replace(/\b\w/g,Ce=>Ce.toUpperCase()),type:"text",category:"discovered",description:a("profiles.presets.discoveredFromPresets")}));return[...Ie,...Le]},[X,O,x,a]),Q=Y.filter(Ie=>Ie.label.toLowerCase().includes(A.toLowerCase())||Ie.key.toLowerCase().includes(A.toLowerCase())),oe=()=>{if(z.trim()){const Ie=z.trim().toLowerCase().replace(/\s+/g,"_");ee(Ie,""),I(""),R(!1),i(a("profiles.presets.toast.fieldAdded",{key:Ie}))}},ee=(Ie,Ke)=>{_(rt=>{const st={...rt};return Ke===""||Ke===void 0?delete st[Ie]:st[Ie]=Ke,st})},ge=Ie=>{_(Ke=>({...Ke,...Ie.settings})),$(Ie.name),i(a("profiles.templates.toast.applied"))},ce=()=>{if(!me.trim())return;const Ie={...x};if(delete Ie.inherits,Object.keys(Ie).length===0){i(a("profiles.presets.noOverridesToSave"),"error");return}const Ke={id:Date.now().toString(),name:me.trim(),description:W.trim()||a("profiles.presets.customTemplate"),type:d,settings:Ie,showInModal:pe},rt=[...Z,Ke];re(rt),Dce(rt),de(!1),ue(""),ae(""),ye(!0),i(a("profiles.templates.toast.created"))},le=v.useMemo(()=>Z.filter(Ie=>Ie.type===d&&Ie.showInModal),[d,Z]),q=Ie=>{C(Ie);try{const Ke=JSON.parse(Ie);_(Ke),T(null)}catch(Ke){T(Ke.message)}},L=Ie=>{Ie.preventDefault(),M(!1);const Ke=Ie.dataTransfer.files[0];if(Ke&&Ke.name.endsWith(".json")){const rt=new FileReader;rt.onload=st=>{try{const Le=st.target?.result,tt=JSON.parse(Le),Ce=tt.setting||tt;_(Xe=>({...Xe,...Ce})),C(JSON.stringify({...x,...Ce},null,2)),i(a("profiles.presets.fileImported"))}catch{i(a("profiles.presets.invalidJsonFile"),"error")}},rt.readAsText(Ke)}},ne=it({mutationFn:()=>{const Ie={...x},Ke=d==="filament"?"filament_settings_id":d==="print"?"print_settings_id":"printer_settings_id";Ie[Ke]=`"${m}"`;const rt={type:d,name:m,base_id:f,setting:Ie};return se.createCloudSetting(rt)},onSuccess:async()=>{i(a("profiles.presets.toast.created")),await s.refetchQueries({queryKey:["cloudSettings"]}),t()},onError:Ie=>i(Ie.message,"error")}),xe=it({mutationFn:()=>{if(!e?.setting_id)throw new Error(a("profiles.presets.noSettingId"));return se.updateCloudSetting(e.setting_id,{name:m,setting:x})},onSuccess:async()=>{i(a("profiles.presets.toast.updated")),s.removeQueries({queryKey:["cloudSettingDetail"]}),await s.refetchQueries({queryKey:["cloudSettings"]}),t()},onError:Ie=>i(Ie.message,"error")}),we=o?xe:ne,Ne=ie?.setting?.inherits,ve=Ne?G.find(Ie=>Ie.name===Ne):void 0,{data:be}=We({queryKey:["cloudSettingDetail",ve?.setting_id],queryFn:()=>se.getCloudSettingDetail(ve.setting_id),enabled:!!ve?.setting_id}),Ee=v.useMemo(()=>{const Ie=be?.setting||{},Ke=ie?.setting||{},rt=f&&O?.[f]?.setting?O[f].setting:{};return{...Ie,...Ke,...rt}},[f,ie,be,O]),ze=Ie=>{if(Ie==null)return"";if(Array.isArray(Ie)){const Ke=[...new Set(Ie.map(rt=>String(rt)))];return Ke.length===1?Ke[0]:Ie.join(", ")}return String(Ie)},_e=Ie=>{const Ke=x[Ie.key],rt=Ee[Ie.key],st=ze(rt),Le=U?a("common.loading"):st||"",tt="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(Ie.type==="boolean"){const Ce=Ke==="1"||Ke===void 0&&rt==="1";return r.jsx("button",{type:"button",onClick:()=>ee(Ie.key,Ke==="1"?"0":"1"),className:`w-8 h-5 rounded-full transition-colors ${Ce?"bg-bambu-green":"bg-bambu-dark-tertiary"}`,children:r.jsx("div",{className:`w-4 h-4 rounded-full bg-white shadow transition-transform ${Ce?"translate-x-3.5":"translate-x-0.5"}`})})}return Ie.type==="select"?r.jsxs("select",{value:Ke||"",onChange:Ce=>ee(Ie.key,Ce.target.value),className:tt,children:[r.jsx("option",{value:"",children:Le}),Ie.options?.map(Ce=>r.jsx("option",{value:Ce.value,children:Ce.label},Ce.value))]}):r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("input",{type:Ie.type==="number"?"number":"text",value:Ke!==void 0?String(Ke):"",onChange:Ce=>ee(Ie.key,Ce.target.value),step:Ie.step,min:Ie.min,max:Ie.max,placeholder:Le,className:tt}),Ie.unit&&r.jsx("span",{className:"text-xs text-bambu-gray whitespace-nowrap",children:Ie.unit})]})},Oe=v.useMemo(()=>ie?.setting?ie.setting:{},[ie]);return r.jsxs("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",onDragOver:Ie=>{Ie.preventDefault(),M(!0)},onDragLeave:()=>M(!1),onDrop:L,children:[K&&f&&r.jsx(Fce,{onClose:()=>D(!1),leftPreset:Oe,rightPreset:x,leftLabel:a("profiles.presets.baseLabel",{name:w||f}),rightLabel:a("profiles.presets.currentLabel",{name:m||a("profiles.presets.newPreset")}),t:a}),r.jsx(Ct,{className:"w-full max-w-6xl max-h-[90vh] flex flex-col overflow-y-auto",children:r.jsxs(At,{className:"p-0 flex flex-col h-full",children:[r.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[r.jsxs("div",{children:[r.jsx("h2",{className:"text-xl font-semibold text-white",children:a(o?"profiles.presets.editPreset":e?"profiles.presets.duplicatePreset":"profiles.presets.createNewPreset")}),r.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:a("profiles.presets.customizeSettings")})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[f&&r.jsxs("button",{onClick:()=>D(!0),className:"flex items-center gap-2 px-3 py-2 text-sm text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary rounded-lg transition-colors",title:a("profiles.presets.compareWithBase"),children:[r.jsx(Zx,{className:"w-4 h-4"}),a("profiles.presets.compare")]}),r.jsx("button",{onClick:t,className:"p-2 text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary rounded-lg transition-colors",children:r.jsx(Bt,{className:"w-5 h-5"})})]})]}),S&&r.jsx("div",{className:"absolute inset-0 bg-bambu-green/10 border-2 border-dashed border-bambu-green rounded-lg flex items-center justify-center z-10",children:r.jsxs("div",{className:"text-center",children:[r.jsx(ka,{className:"w-12 h-12 text-bambu-green mx-auto mb-2"}),r.jsx("p",{className:"text-bambu-green font-medium",children:a("profiles.presets.dropJsonToImport")})]})}),r.jsxs("div",{className:"p-4 border-b border-bambu-dark-tertiary space-y-3",children:[r.jsxs("div",{className:"grid grid-cols-3 gap-4 max-[640px]:grid-cols-1",children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("common.type")}),r.jsxs("select",{value:d,onChange:Ie=>{u(Ie.target.value),b("")},className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[r.jsx("option",{value:"filament",children:a("profiles.presets.types.filament")}),r.jsx("option",{value:"print",children:a("profiles.presets.types.process")}),r.jsx("option",{value:"printer",children:a("profiles.presets.types.printer")})]})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("profiles.presets.basePreset")}),r.jsxs("select",{value:f,onChange:Ie=>b(Ie.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",children:[r.jsx("option",{value:"",children:a("profiles.presets.selectBasePreset")}),G.map(Ie=>r.jsx("option",{value:Ie.setting_id,children:Ie.name},Ie.setting_id))]})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("profiles.presets.presetName")}),r.jsx("input",{type:"text",value:m,onChange:Ie=>p(Ie.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",placeholder:a("profiles.presets.myCustomPreset")})]})]}),w&&r.jsx("div",{className:"text-xs text-bambu-gray",children:r.jsxs("p",{className:"flex items-center gap-1",children:[r.jsx(_r,{className:"w-3 h-3 text-bambu-green"}),a("profiles.presets.inheritsFrom")," ",r.jsx("span",{className:"text-white",children:w}),U&&r.jsx(ut,{className:"w-3 h-3 animate-spin ml-1"})]})})]}),r.jsxs("div",{className:"flex border-b border-bambu-dark-tertiary max-[640px]:flex-wrap max-[640px]:items-center",children:[r.jsxs("button",{onClick:()=>c("common"),className:`flex items-center gap-2 px-4 py-3 text-sm font-medium transition-colors border-b-2 -mb-px ${l==="common"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-white border-transparent"}`,children:[r.jsx(c6,{className:"w-4 h-4"}),a("profiles.presets.tabs.common")]}),r.jsxs("button",{onClick:()=>c("fields"),className:`flex items-center gap-2 px-4 py-3 text-sm font-medium transition-colors border-b-2 -mb-px ${l==="fields"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-white border-transparent"}`,children:[r.jsx(AS,{className:"w-4 h-4"}),a("profiles.presets.tabs.allFields")]}),r.jsxs("button",{onClick:()=>c("json"),className:`flex items-center gap-2 px-4 py-3 text-sm font-medium transition-colors border-b-2 -mb-px ${l==="json"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-white border-transparent"}`,children:[r.jsx(Gy,{className:"w-4 h-4"}),"JSON",P&&r.jsx($a,{className:"w-3 h-3 text-red-400"})]}),r.jsx("div",{className:"flex-1 max-[640px]:hidden"}),r.jsxs("button",{onClick:()=>{const Ie={name:m,type:d,base_id:f,setting:x},Ke=new Blob([JSON.stringify(Ie,null,2)],{type:"application/json"}),rt=URL.createObjectURL(Ke),st=document.createElement("a");st.href=rt,st.download=`${m||"preset"}.json`,document.body.appendChild(st),st.click(),document.body.removeChild(st),URL.revokeObjectURL(rt),i(a("profiles.presets.toast.exported"))},className:"flex items-center gap-2 px-4 py-3 text-sm text-bambu-gray hover:text-white transition-colors",title:a("profiles.presets.exportToJson"),children:[r.jsx(Yr,{className:"w-4 h-4"}),a("common.download")]}),r.jsxs("button",{onClick:()=>document.getElementById("file-import")?.click(),className:"flex items-center gap-2 px-4 py-3 text-sm text-bambu-gray hover:text-white transition-colors",title:a("profiles.presets.importFromJson"),children:[r.jsx(ka,{className:"w-4 h-4"}),a("common.upload")]}),r.jsx("input",{id:"file-import",type:"file",accept:".json",className:"hidden",onChange:Ie=>{const Ke=Ie.target.files?.[0];if(Ke){const rt=new FileReader;rt.onload=st=>{try{const Le=JSON.parse(st.target?.result),tt=Le.setting||Le;_(Ce=>({...Ce,...tt})),i(a("profiles.presets.fileImported"))}catch{i(a("profiles.presets.invalidJson"),"error")}},rt.readAsText(Ke)}}})]}),r.jsxs("div",{className:"flex-1 p-4",children:[l==="common"&&r.jsxs("div",{className:"space-y-6",children:[r.jsxs("div",{children:[r.jsxs("div",{className:"flex items-center justify-between mb-3",children:[r.jsxs("h3",{className:"text-sm font-medium text-white flex items-center gap-2",children:[r.jsx(Dg,{className:"w-4 h-4 text-amber-400"}),a("profiles.templates.title")]}),Object.keys(x).filter(Ie=>Ie!=="inherits").length>0&&r.jsxs("button",{onClick:()=>de(!J),className:"text-xs text-bambu-gray hover:text-white flex items-center gap-1 transition-colors",children:[r.jsx(us,{className:"w-3 h-3"}),a("profiles.presets.saveAsTemplate")]})]}),J&&r.jsxs("div",{className:"mb-3 p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"grid grid-cols-2 gap-2 mb-2",children:[r.jsx("input",{type:"text",value:me,onChange:Ie=>ue(Ie.target.value),placeholder:a("profiles.templates.namePlaceholder"),className:"px-3 py-1.5 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none",autoFocus:!0}),r.jsx("input",{type:"text",value:W,onChange:Ie=>ae(Ie.target.value),placeholder:a("profiles.templates.descriptionPlaceholder"),className:"px-3 py-1.5 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none"})]}),r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("div",{className:"flex gap-2",children:[r.jsxs(Me,{size:"sm",onClick:ce,disabled:!me.trim(),children:[r.jsx(us,{className:"w-3 h-3"}),a("common.save")]}),r.jsx(Me,{size:"sm",variant:"secondary",onClick:()=>de(!1),children:a("common.cancel")})]}),r.jsxs("button",{onClick:()=>ye(!pe),className:`flex items-center gap-1.5 text-xs transition-colors ${pe?"text-bambu-green":"text-bambu-gray hover:text-white"}`,children:[pe?r.jsx(Dl,{className:"w-3.5 h-3.5"}):r.jsx(sb,{className:"w-3.5 h-3.5"}),a(pe?"profiles.templates.shownInModals":"profiles.templates.hiddenInModals")]})]})]}),Te&&r.jsxs("div",{className:"mb-3 px-3 py-2 bg-bambu-green/10 border border-bambu-green/30 rounded-lg flex items-center gap-2",children:[r.jsx(_r,{className:"w-4 h-4 text-bambu-green"}),r.jsxs("span",{className:"text-sm text-bambu-green",children:[a("profiles.presets.templateApplied")," ",r.jsx("span",{className:"font-medium",children:Te})]}),r.jsx("button",{onClick:()=>$(null),className:"ml-auto text-bambu-green/70 hover:text-bambu-green",children:r.jsx(Bt,{className:"w-4 h-4"})})]}),r.jsxs("div",{className:"grid grid-cols-3 gap-2",children:[le.map(Ie=>r.jsxs("button",{onClick:()=>ge(Ie),className:"p-3 text-left bg-bambu-dark border border-bambu-dark-tertiary rounded-lg hover:border-bambu-gray-dark transition-colors",children:[r.jsx("p",{className:"text-sm font-medium text-white",children:Ie.name}),r.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:Ie.description})]},Ie.id)),le.length===0&&r.jsx("p",{className:"col-span-3 text-center text-bambu-gray text-sm py-4",children:a("profiles.presets.noTemplatesSelected")})]}),r.jsx("p",{className:"text-xs text-bambu-gray-dark mt-2 text-center",children:a("profiles.presets.manageTemplatesHint")})]}),r.jsxs("div",{children:[r.jsx("h3",{className:"text-sm font-medium text-white mb-3",children:a("profiles.presets.commonSettings")}),r.jsx("div",{className:"grid grid-cols-2 gap-x-6 gap-y-3",children:Y.slice(0,10).map(Ie=>r.jsxs("div",{className:"flex items-center justify-between gap-4 max-[640px]:flex-col max-[640px]:items-start",children:[r.jsx("label",{className:"text-sm text-bambu-gray flex-shrink-0",children:Ie.label}),r.jsx("div",{className:"w-48 max-[640px]:w-full",children:_e(Ie)})]},Ie.key))})]}),Object.keys(x).length>1&&r.jsxs("div",{children:[r.jsx("h3",{className:"text-sm font-medium text-white mb-3",children:a("profiles.presets.currentOverrides")}),r.jsx("div",{className:"flex flex-wrap gap-2",children:Object.entries(x).filter(([Ie])=>Ie!=="inherits").map(([Ie,Ke])=>r.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-1 bg-bambu-green/10 text-bambu-green text-xs rounded",children:[Ie,": ",String(Ke).slice(0,20),r.jsx("button",{onClick:()=>ee(Ie,void 0),className:"hover:text-white",children:r.jsx(Bt,{className:"w-3 h-3"})})]},Ie))})]})]}),l==="fields"&&r.jsxs("div",{className:"grid grid-cols-2 gap-6",style:{height:"400px"},children:[r.jsxs("div",{className:"flex flex-col h-full overflow-hidden",children:[r.jsxs("div",{className:"flex items-center justify-between mb-3 flex-shrink-0",children:[r.jsx("h3",{className:"text-sm font-medium text-white",children:a("profiles.presets.availableFields")}),r.jsx("span",{className:"text-xs text-bambu-gray",children:O?a("profiles.templates.fieldsCount",{count:Y.length}):a("common.loading")})]}),r.jsxs("div",{className:"relative mb-3 flex-shrink-0",children:[r.jsx(Sr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),r.jsx("input",{type:"text",value:A,onChange:Ie=>F(Ie.target.value),placeholder:a("profiles.presets.searchFieldsPlaceholder"),className:"w-full pl-10 pr-4 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder-bambu-gray-dark focus:border-bambu-green focus:outline-none"})]}),r.jsxs("div",{className:"flex-1 overflow-y-auto space-y-1 pr-2 min-h-0",children:[Q.filter(Ie=>!(Ie.key in x)).map(Ie=>{const Ke=Ee[Ie.key],rt=ze(Ke);return r.jsxs("div",{onClick:()=>{_(st=>({...st,[Ie.key]:rt||""}))},className:"flex items-center justify-between gap-2 p-2 rounded-lg hover:bg-bambu-dark-tertiary transition-colors cursor-pointer group",children:[r.jsxs("div",{className:"min-w-0 flex-1",children:[r.jsx("p",{className:"text-sm text-white truncate",children:Ie.label}),r.jsx("p",{className:"text-xs text-bambu-gray-dark truncate",children:Ie.key})]}),r.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[rt&&r.jsxs("span",{className:"text-xs text-bambu-gray bg-bambu-dark px-2 py-0.5 rounded max-w-32 truncate",title:rt,children:[rt.slice(0,20),rt.length>20?"...":""]}),r.jsx("div",{className:"w-6 h-6 flex items-center justify-center rounded bg-bambu-dark-tertiary group-hover:bg-bambu-green/20 transition-colors",children:r.jsx(ar,{className:"w-4 h-4 text-bambu-gray group-hover:text-bambu-green transition-colors"})})]})]},Ie.key)}),Q.filter(Ie=>!(Ie.key in x)).length===0&&r.jsx("p",{className:"text-center text-bambu-gray py-4 text-sm",children:a(A?"profiles.presets.noMatchingFields":"profiles.presets.allFieldsAdded")})]}),r.jsx("div",{className:"pt-3 mt-3 border-t border-bambu-dark-tertiary flex-shrink-0",children:H?r.jsxs("div",{className:"flex gap-2",children:[r.jsx("input",{type:"text",value:z,onChange:Ie=>I(Ie.target.value),onKeyDown:Ie=>Ie.key==="Enter"&&oe(),placeholder:"custom_field_name",className:"flex-1 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white font-mono text-sm placeholder-bambu-gray-dark focus:border-bambu-green focus:outline-none",autoFocus:!0}),r.jsx(Me,{size:"sm",onClick:oe,disabled:!z.trim(),children:r.jsx(ar,{className:"w-4 h-4"})}),r.jsx(Me,{size:"sm",variant:"secondary",onClick:()=>{R(!1),I("")},children:r.jsx(Bt,{className:"w-4 h-4"})})]}):r.jsxs("button",{onClick:()=>R(!0),className:"w-full flex items-center justify-center gap-2 p-2 text-sm text-bambu-gray hover:text-white border border-dashed border-bambu-dark-tertiary hover:border-bambu-gray-dark rounded-lg transition-colors",children:[r.jsx(ar,{className:"w-4 h-4"}),a("profiles.presets.addCustomField")]})})]}),r.jsxs("div",{className:"flex flex-col h-full overflow-hidden",children:[r.jsxs("div",{className:"flex items-center justify-between mb-3 flex-shrink-0",children:[r.jsx("h3",{className:"text-sm font-medium text-white",children:a("profiles.presets.yourOverrides")}),r.jsx("span",{className:"text-xs text-bambu-gray",children:a("profiles.templates.fieldsCount",{count:Object.keys(x).filter(Ie=>Ie!=="inherits").length})})]}),r.jsxs("div",{className:"flex-1 overflow-y-auto space-y-2 pr-2 min-h-0",children:[Object.entries(x).filter(([Ie])=>Ie!=="inherits").map(([Ie,Ke])=>{const rt=Y.find(st=>st.key===Ie);return r.jsxs("div",{className:"p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"flex items-center justify-between mb-2",children:[r.jsxs("div",{children:[r.jsx("p",{className:"text-sm font-medium text-white",children:rt?.label||Ie}),r.jsx("p",{className:"text-xs text-bambu-gray-dark",children:Ie})]}),r.jsx("button",{onClick:()=>ee(Ie,void 0),className:"p-1 text-bambu-gray hover:text-red-400 transition-colors",children:r.jsx(Bt,{className:"w-4 h-4"})})]}),rt?_e(rt):r.jsx("input",{type:"text",value:String(Ke),onChange:st=>ee(Ie,st.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"})]},Ie)}),Object.keys(x).filter(Ie=>Ie!=="inherits").length===0&&r.jsxs("div",{className:"text-center py-8 text-bambu-gray",children:[r.jsx(c6,{className:"w-8 h-8 mx-auto mb-2 opacity-50"}),r.jsx("p",{className:"text-sm",children:a("profiles.presets.noOverridesYet")}),r.jsx("p",{className:"text-xs mt-1",children:a("profiles.presets.clickFieldsToAdd")})]})]}),Object.keys(x).filter(Ie=>Ie!=="inherits").length>0&&r.jsx("div",{className:"pt-3 mt-3 border-t border-bambu-dark-tertiary flex-shrink-0",children:r.jsxs("button",{onClick:()=>{de(!0),c("common")},className:"w-full flex items-center justify-center gap-2 p-2 text-sm text-bambu-gray hover:text-white border border-dashed border-bambu-dark-tertiary hover:border-bambu-gray-dark rounded-lg transition-colors",children:[r.jsx(us,{className:"w-4 h-4"}),a("profiles.presets.saveAsTemplate")]})})]})]}),l==="json"&&r.jsxs("div",{className:"space-y-2",children:[P&&r.jsxs("div",{className:"flex items-center gap-2 text-red-400 text-sm",children:[r.jsx($a,{className:"w-4 h-4"}),P]}),r.jsx("textarea",{value:N,onChange:Ie=>q(Ie.target.value),className:`w-full h-80 px-3 py-2 bg-bambu-dark border rounded-lg text-white text-xs font-mono focus:outline-none resize-none ${P?"border-red-500 focus:border-red-500":"border-bambu-dark-tertiary focus:border-bambu-green"}`,spellCheck:!1}),r.jsx("p",{className:"text-xs text-bambu-gray",children:a("profiles.presets.jsonTip")})]})]}),r.jsxs("div",{className:"p-4 border-t border-bambu-dark-tertiary flex gap-2",children:[r.jsx(Me,{variant:"secondary",onClick:t,className:"flex-1",children:a("common.cancel")}),r.jsxs(Me,{onClick:()=>we.mutate(),disabled:we.isPending||!m.trim()||!o&&!f||!!P,className:"flex-1",children:[we.isPending?r.jsx(ut,{className:"w-4 h-4 animate-spin"}):o?r.jsx(us,{className:"w-4 h-4"}):r.jsx(ar,{className:"w-4 h-4"}),a(o?"common.save":e?"common.duplicate":"common.create")]})]})]})})]})}function Fat({settings:t,lastSyncTime:e,onRefresh:n,isRefreshing:a,printers:i,hasPermission:s,t:o}){const[l,c]=v.useState(""),[d,u]=v.useState("all"),[m,p]=v.useState("all"),[f,b]=v.useState("all"),[w,g]=v.useState("all"),[x,_]=v.useState("all"),[N,C]=v.useState("all"),[P,T]=v.useState(null),[A,F]=v.useState(!1),[S,M]=v.useState(!1),[z,I]=v.useState(null),[H,R]=v.useState(null),[Z,re]=v.useState(null),[J,de]=v.useState(!1),[me,ue]=v.useState([null,null]),[W,ae]=v.useState(!1),[pe,ye]=v.useState(null),Te=en(),$=v.useMemo(()=>[...t.filament.map(oe=>({...oe,type:"filament"})),...t.printer.map(oe=>({...oe,type:"printer"})),...t.process.map(oe=>({...oe,type:"process"}))].map(oe=>({...oe,meta:aU(oe.name)})),[t]),K=v.useMemo(()=>{const Q=new Set,oe=new Set,ee=new Set;return $.forEach(ge=>{ge.meta.nozzle&&Q.add(ge.meta.nozzle),ge.meta.filamentType&&oe.add(ge.meta.filamentType),ge.meta.layerHeight&&ee.add(ge.meta.layerHeight)}),{printers:i.map(ge=>({id:ge.id.toString(),name:ge.name})),nozzles:Array.from(Q).sort((ge,ce)=>parseFloat(ge)-parseFloat(ce)),filaments:Array.from(oe).sort(),layerHeights:Array.from(ee).sort((ge,ce)=>parseFloat(ge)-parseFloat(ce))}},[$,i]),D=v.useMemo(()=>f==="all"?null:i.find(oe=>oe.id.toString()===f)?.model||null,[f,i]),j=v.useMemo(()=>$.filter(Q=>d==="all"||Q.type===d).filter(Q=>{if(m==="all")return!0;const oe=vS(Q.setting_id);return m==="custom"?oe:!oe}).filter(Q=>{if(f==="all"||!D)return!0;const oe=Q.meta.printer?.toLowerCase()||"",ee=D.toLowerCase();return oe.includes(ee)||ee.includes(oe)}).filter(Q=>w==="all"||Q.meta.nozzle===w).filter(Q=>x==="all"||Q.meta.filamentType===x).filter(Q=>N==="all"||Q.meta.layerHeight===N).filter(Q=>l===""||Q.name.toLowerCase().includes(l.toLowerCase())).sort((Q,oe)=>Q.name.localeCompare(oe.name)),[$,d,m,f,D,w,x,N,l]),B=Q=>{if(J){const oe=me[0]?.setting_id===Q.setting_id,ee=me[1]?.setting_id===Q.setting_id;if(oe)ue([me[1],null]);else if(ee)ue([me[0],null]);else if(!me[0])ue([Q,null]);else if(me[1]){if(me[0].type!==Q.type)return;ue([me[0],Q])}else{if(me[0].type!==Q.type)return;ue([me[0],Q])}}else T(Q)},X=Q=>{if(me[0]?.setting_id===Q.setting_id)return 0;if(me[1]?.setting_id===Q.setting_id)return 1},O=async Q=>{try{const oe=await se.getCloudSettingDetail(Q.setting_id),ee=Q.type==="process"?"print":Q.type;I({type:ee,name:Q.name,base_id:oe.base_id||"GFSA00",setting:oe.setting||{}}),T(null)}catch(oe){console.error("Failed to fetch preset details for duplication:",oe)}},ie=async Q=>{try{Te.removeQueries({queryKey:["cloudSettingDetail",Q.setting_id]});const oe=await se.getCloudSettingDetail(Q.setting_id),ee=Q.type==="process"?"print":Q.type;R({type:ee,name:Q.name,base_id:oe.base_id||"GFSA00",setting:oe.setting||{},setting_id:Q.setting_id}),T(null)}catch(oe){console.error("Failed to fetch preset details for editing:",oe)}},U=()=>{u("all"),p("all"),b("all"),g("all"),_("all"),C("all"),c("")},G=d!=="all"||m!=="all"||f!=="all"||w!=="all"||x!=="all"||N!=="all"||l!=="",Y=t.filament.length+t.printer.length+t.process.length;return r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"space-y-4 mb-6",children:[r.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[r.jsxs("div",{className:"relative flex-1",children:[r.jsx(Sr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),r.jsx("input",{type:"text",value:l,onChange:Q=>c(Q.target.value),placeholder:o("profiles.cloudView.searchPlaceholder"),className:"w-full pl-10 pr-4 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray-dark focus:border-bambu-green focus:outline-none"})]}),r.jsxs("div",{className:"flex gap-2 max-[550px]:flex-wrap max-[550px]:items-center",children:[r.jsxs(Me,{variant:J?"primary":"secondary",onClick:()=>{J?(de(!1),ue([null,null])):de(!0)},children:[r.jsx(Zx,{className:"w-4 h-4"}),o(J?"common.cancel":"profiles.presets.compare")]}),r.jsxs(Me,{variant:"secondary",onClick:()=>M(!0),disabled:!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.cloudView.noTemplatesPermission"),children:[r.jsx(Dg,{className:"w-4 h-4"}),o("profiles.cloudView.templates")]}),r.jsxs(Me,{variant:"secondary",onClick:n,disabled:a||!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.cloudView.noRefreshPermission"),children:[r.jsx(sr,{className:`w-4 h-4 ${a?"animate-spin":""}`}),o("profiles.cloudView.refresh")]}),r.jsxs(Me,{onClick:()=>F(!0),disabled:!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.cloudView.noCreatePermission"),children:[r.jsx(ar,{className:"w-4 h-4"}),o("profiles.cloudView.newPreset")]})]})]}),r.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[r.jsx(NS,{className:"w-4 h-4 text-bambu-gray"}),r.jsx(Lx,{label:o("profiles.cloudView.filters.type"),value:d,options:[{value:"all",label:o("profiles.cloudView.filters.all"),count:Y},{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:Q=>u(Q)}),r.jsx(Lx,{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:Q=>p(Q)}),K.printers.length>0&&r.jsx(Lx,{label:o("profiles.cloudView.filters.printer"),value:f,options:[{value:"all",label:o("profiles.cloudView.filters.all")},...K.printers.map(Q=>({value:Q.id,label:Q.name}))],onChange:b}),K.nozzles.length>0&&r.jsx(Lx,{label:o("profiles.cloudView.filters.nozzle"),value:w,options:[{value:"all",label:o("profiles.cloudView.filters.all")},...K.nozzles.map(Q=>({value:Q,label:Q}))],onChange:g}),K.filaments.length>0&&(d==="all"||d==="filament")&&r.jsx(Lx,{label:o("profiles.cloudView.filters.filament"),value:x,options:[{value:"all",label:o("profiles.cloudView.filters.all")},...K.filaments.map(Q=>({value:Q,label:Q}))],onChange:_}),K.layerHeights.length>0&&(d==="all"||d==="process")&&r.jsx(Lx,{label:o("profiles.cloudView.filters.layer"),value:N,options:[{value:"all",label:o("profiles.cloudView.filters.all")},...K.layerHeights.map(Q=>({value:Q,label:Q}))],onChange:C}),G&&r.jsx("button",{onClick:U,className:"px-3 py-2 text-sm text-bambu-gray hover:text-white transition-colors",children:o("profiles.cloudView.clearFilters")})]})]}),J&&r.jsx("div",{className:"mb-4 p-3 bg-blue-500/10 border border-blue-500/30 rounded-lg",children:r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("div",{className:"flex items-center gap-4",children:[r.jsx(Zx,{className:"w-5 h-5 text-blue-400"}),r.jsx("span",{className:"text-white font-medium",children:o("profiles.cloudView.compareMode")}),r.jsx("span",{className:"text-bambu-gray",children:me[0]?o("profiles.cloudView.selectAnotherPreset",{type:me[0].type}):o("profiles.cloudView.clickTwoPresets")})]}),r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("span",{className:`px-2 py-1 text-sm rounded truncate max-w-[200px] ${me[0]?"bg-blue-500/30 text-blue-700 dark:text-blue-300":"bg-bambu-dark text-bambu-gray"}`,children:me[0]?me[0].name:o("profiles.cloudView.selectFirst")}),r.jsx(XN,{className:"w-4 h-4 text-bambu-gray"}),r.jsx("span",{className:`px-2 py-1 text-sm rounded truncate max-w-[200px] ${me[1]?"bg-blue-500/30 text-blue-700 dark:text-blue-300":"bg-bambu-dark text-bambu-gray"}`,children:me[1]?me[1].name:o("profiles.cloudView.selectSecond")})]}),me[0]&&me[1]&&r.jsxs(Me,{size:"sm",onClick:async()=>{try{const[Q,oe]=await Promise.all([se.getCloudSettingDetail(me[0].setting_id),se.getCloudSettingDetail(me[1].setting_id)]);ye([Q.setting||{},oe.setting||{}]),ae(!0)}catch{}},children:[r.jsx(Zx,{className:"w-4 h-4"}),o("profiles.cloudView.compareNow")]})]})]})}),r.jsxs("div",{className:"flex flex-wrap items-center gap-4 mb-4 text-sm text-bambu-gray",children:[e&&r.jsxs("div",{className:"flex items-center gap-1",children:[r.jsx(Zn,{className:"w-3 h-3"}),o("profiles.cloudView.lastSynced")," ",jh(e.toISOString(),"system",o)]}),r.jsx("span",{children:o("profiles.cloudView.showingCount",{showing:j.length,total:Y})}),r.jsxs("div",{className:"flex items-center gap-1",children:[r.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-bambu-green"}),r.jsxs("span",{children:["= ",o("profiles.presets.myPreset")]})]})]}),j.length===0?r.jsxs("div",{className:"text-center py-16",children:[r.jsx(oa,{className:"w-12 h-12 text-bambu-gray-dark mx-auto mb-4"}),r.jsx("p",{className:"text-bambu-gray",children:o("profiles.cloudView.noPresetsFound")}),G&&r.jsx("button",{onClick:U,className:"mt-2 text-sm text-bambu-green hover:text-bambu-green-light",children:o("profiles.cloudView.clearFilters")})]}):r.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-6",children:[r.jsxs("div",{children:[r.jsxs("div",{className:"flex items-center gap-2 mb-3 px-1",children:[r.jsx(ST,{className:"w-4 h-4 text-amber-400"}),r.jsx("h3",{className:"text-sm font-medium text-bambu-gray",children:o("profiles.cloudView.columns.filament")}),r.jsxs("span",{className:"text-xs text-bambu-gray-dark",children:["(",j.filter(Q=>Q.type==="filament").length,")"]})]}),r.jsxs("div",{className:"space-y-1 max-h-[calc(100vh-320px)] overflow-y-auto pr-1",children:[j.filter(Q=>Q.type==="filament").map(Q=>r.jsx(uF,{setting:Q,onClick:()=>B(Q),onDuplicate:()=>O(Q),compareMode:J,isCompareSelected:X(Q)!==void 0,compareIndex:X(Q),compareDisabled:J&&!!me[0]&&me[0].type!==Q.type,t:o},Q.setting_id)),j.filter(Q=>Q.type==="filament").length===0&&r.jsx("p",{className:"text-xs text-bambu-gray-dark px-3 py-2",children:o("profiles.cloudView.noFilamentPresets")})]})]}),r.jsxs("div",{children:[r.jsxs("div",{className:"flex items-center gap-2 mb-3 px-1",children:[r.jsx(uu,{className:"w-4 h-4 text-blue-400"}),r.jsx("h3",{className:"text-sm font-medium text-bambu-gray",children:o("profiles.cloudView.columns.process")}),r.jsxs("span",{className:"text-xs text-bambu-gray-dark",children:["(",j.filter(Q=>Q.type==="process").length,")"]})]}),r.jsxs("div",{className:"space-y-1 max-h-[calc(100vh-320px)] overflow-y-auto pr-1",children:[j.filter(Q=>Q.type==="process").map(Q=>r.jsx(uF,{setting:Q,onClick:()=>B(Q),onDuplicate:()=>O(Q),compareMode:J,isCompareSelected:X(Q)!==void 0,compareIndex:X(Q),compareDisabled:J&&!!me[0]&&me[0].type!==Q.type,t:o},Q.setting_id)),j.filter(Q=>Q.type==="process").length===0&&r.jsx("p",{className:"text-xs text-bambu-gray-dark px-3 py-2",children:o("profiles.cloudView.noProcessPresets")})]})]}),r.jsxs("div",{children:[r.jsxs("div",{className:"flex items-center gap-2 mb-3 px-1",children:[r.jsx(pr,{className:"w-4 h-4 text-purple-400"}),r.jsx("h3",{className:"text-sm font-medium text-bambu-gray",children:o("profiles.cloudView.columns.printer")}),r.jsxs("span",{className:"text-xs text-bambu-gray-dark",children:["(",j.filter(Q=>Q.type==="printer").length,")"]})]}),r.jsxs("div",{className:"space-y-1 max-h-[calc(100vh-320px)] overflow-y-auto pr-1",children:[j.filter(Q=>Q.type==="printer").map(Q=>r.jsx(uF,{setting:Q,onClick:()=>B(Q),onDuplicate:()=>O(Q),compareMode:J,isCompareSelected:X(Q)!==void 0,compareIndex:X(Q),compareDisabled:J&&!!me[0]&&me[0].type!==Q.type,t:o},Q.setting_id)),j.filter(Q=>Q.type==="printer").length===0&&r.jsx("p",{className:"text-xs text-bambu-gray-dark px-3 py-2",children:o("profiles.cloudView.noPrinterPresets")})]})]})]}),P&&r.jsx(Mat,{setting:P,onClose:()=>T(null),onDeleted:()=>T(null),onDuplicate:()=>O(P),onEdit:()=>ie(P),hasPermission:s,t:o}),(A||z||H||Z)&&r.jsx(Dat,{onClose:()=>{F(!1),I(null),R(null),re(null)},initialData:H||z||(Z?{type:Z.type,name:"",base_id:"",setting:Z.setting}:void 0),allPresets:t,t:o}),S&&r.jsx(Eat,{onClose:()=>M(!1),onApply:Q=>{re({type:Q.type,setting:Q.settings}),M(!1)},t:o}),W&&pe&&me[0]&&me[1]&&r.jsx(Fce,{onClose:()=>{ae(!1),ye(null)},leftPreset:pe[0],rightPreset:pe[1],leftLabel:me[0].name,rightLabel:me[1].name,t:o})]})}function Lat(){const{t}=kt(),e=en(),{showToast:n}=rn(),{hasPermission:a}=cr(),[i,s]=v.useState("cloud"),[o,l]=v.useState(),{data:c,isLoading:d}=We({queryKey:["cloudStatus"],queryFn:se.getCloudStatus}),{data:u=[]}=We({queryKey:["printers"],queryFn:se.getPrinters}),{data:m,isLoading:p,refetch:f,dataUpdatedAt:b}=We({queryKey:["cloudSettings"],queryFn:()=>se.getCloudSettings(),enabled:!!c?.is_authenticated,retry:!1,staleTime:1e3*60*5});v.useEffect(()=>{b&&l(new Date(b))},[b]);const w=it({mutationFn:se.cloudLogout,onSuccess:()=>{e.invalidateQueries({queryKey:["cloudStatus"]}),e.removeQueries({queryKey:["cloudSettings"]}),n(t("profiles.toast.loggedOut"))}}),g=()=>{e.invalidateQueries({queryKey:["cloudStatus"]})};return d?r.jsx("div",{className:"p-4 md:p-8 flex items-center justify-center min-h-[400px]",children:r.jsx(ut,{className:"w-8 h-8 text-bambu-green animate-spin"})}):r.jsxs("div",{className:"p-4 md:p-8",children:[r.jsxs("div",{className:"mb-6",children:[r.jsxs("h1",{className:"text-2xl font-bold text-white flex items-center gap-3",children:[r.jsx(Hh,{className:"w-7 h-7 text-bambu-green"}),t("profiles.title")]}),r.jsx("p",{className:"text-bambu-gray mt-1",children:t("profiles.subtitle")})]}),r.jsxs("div",{className:"flex border-b border-bambu-dark-tertiary mb-6",children:[r.jsxs("button",{onClick:()=>s("cloud"),className:`flex items-center gap-2 px-4 py-3 text-sm font-medium transition-colors border-b-2 -mb-px ${i==="cloud"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-white border-transparent"}`,children:[r.jsx(Hh,{className:"w-4 h-4"}),t("profiles.tabs.cloud")]}),r.jsxs("button",{onClick:()=>s("local"),className:`flex items-center gap-2 px-4 py-3 text-sm font-medium transition-colors border-b-2 -mb-px ${i==="local"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-white border-transparent"}`,children:[r.jsx(ob,{className:"w-4 h-4"}),t("profiles.tabs.local")]}),r.jsxs("button",{onClick:()=>s("kprofiles"),className:`flex items-center gap-2 px-4 py-3 text-sm font-medium transition-colors border-b-2 -mb-px ${i==="kprofiles"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-white border-transparent"}`,children:[r.jsx(CS,{className:"w-4 h-4"}),t("profiles.tabs.kprofiles")]})]}),i==="cloud"&&r.jsxs(r.Fragment,{children:[c?.is_authenticated&&r.jsxs("div",{className:"flex items-center justify-between p-3 mb-6 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("div",{className:"w-2 h-2 rounded-full bg-bambu-green animate-pulse"}),r.jsxs("span",{className:"text-sm text-bambu-gray",children:[t("profiles.connectedAs")," ",r.jsx("span",{className:"text-white",children:c.email}),c.region&&r.jsx("span",{className:"ml-2 px-2 py-0.5 text-xs rounded bg-bambu-dark-tertiary text-bambu-gray",children:c.region==="china"?t("profiles.login.regionChina"):t("profiles.login.regionGlobal")})]})]}),r.jsxs(Me,{variant:"secondary",size:"sm",onClick:()=>w.mutate(),disabled:w.isPending||!a("cloud:auth"),title:a("cloud:auth")?void 0:t("profiles.noLogoutPermission"),children:[r.jsx(Jx,{className:"w-4 h-4"}),t("profiles.logout")]})]}),c?.is_authenticated?p?r.jsx("div",{className:"flex items-center justify-center py-16",children:r.jsx(ut,{className:"w-8 h-8 text-bambu-green animate-spin"})}):m?r.jsx(Fat,{settings:m,lastSyncTime:o,onRefresh:()=>f(),isRefreshing:p,printers:u,hasPermission:a,t}):r.jsxs("div",{className:"text-center py-16",children:[r.jsx("p",{className:"text-bambu-gray mb-4",children:t("profiles.failedToLoad")}),r.jsx(Me,{onClick:()=>f(),children:t("profiles.retry")})]}):r.jsx(Aat,{onSuccess:g,t})]}),i==="local"&&r.jsx(Tat,{}),i==="kprofiles"&&r.jsx(kat,{}),r.jsx(jat,{})]})}function Rat(t,e){const n=(e||"").toUpperCase().replace(/[- ]/g,""),a=n.includes("X1"),i=n.includes("P1"),s=n.includes("A1MINI"),o=n.includes("A1")&&!s,l=n.includes("H2D"),c=n.includes("H2C"),d=n.includes("H2S"),u=l||c||d,m=n.includes("P2S"),p=n.includes("X2D"),f=m||p;switch(t){case"Lubricate Steel Rods":return f?"https://wiki.bambulab.com/en/p2s/maintenance/lubricate-x-y-z-axis":null;case"Clean Steel Rods":return f?"https://wiki.bambulab.com/en/p2s/maintenance/lubricate-x-y-z-axis":null;case"Lubricate Linear Rails":return s?"https://wiki.bambulab.com/en/a1-mini/maintenance/lubricate-y-axis":o?"https://wiki.bambulab.com/en/a1/maintenance/lubricate-y-axis":u?"https://wiki.bambulab.com/en/h2/maintenance/x-axis-lubrication":null;case"Clean Nozzle/Hotend":return a||i?"https://wiki.bambulab.com/en/x1/troubleshooting/nozzle-clog":s||o?"https://wiki.bambulab.com/en/a1-mini/troubleshooting/nozzle-clog":u?"https://wiki.bambulab.com/en/h2/maintenance/nozzl-cold-pull-maintenance-and-cleaning":f?"https://wiki.bambulab.com/en/p2s/maintenance/cold-pull-maintenance-hotend":"https://wiki.bambulab.com/en/x1/troubleshooting/nozzle-clog";case"Check Belt Tension":return a?"https://wiki.bambulab.com/en/x1/maintenance/belt-tension":i?"https://wiki.bambulab.com/en/p1/maintenance/p1p-maintenance":s?"https://wiki.bambulab.com/en/a1-mini/maintenance/belt_tension":o?"https://wiki.bambulab.com/en/a1/maintenance/belt_tension":l?"https://wiki.bambulab.com/en/h2/maintenance/belt-tension":c?"https://wiki.bambulab.com/en/h2c/maintenance/belt-tension":d?"https://wiki.bambulab.com/en/h2s/maintenance/belt-tension":f?"https://wiki.bambulab.com/en/p2s/maintenance/belt-tension":"https://wiki.bambulab.com/en/x1/maintenance/belt-tension";case"Clean Carbon Rods":return a||i?"https://wiki.bambulab.com/en/general/carbon-rods-clearance":null;case"Clean Linear Rails":return s?"https://wiki.bambulab.com/en/a1-mini/maintenance/lubricate-y-axis":o?"https://wiki.bambulab.com/en/a1/maintenance/lubricate-y-axis":u?"https://wiki.bambulab.com/en/h2/maintenance/x-axis-lubrication":null;case"Clean Build Plate":return"https://wiki.bambulab.com/en/filament-acc/acc/pei-plate-clean-guide";case"Check PTFE Tube":return a||i?"https://wiki.bambulab.com/en/x1/maintenance/replace-ptfe-tube":s||o?"https://wiki.bambulab.com/en/a1-mini/maintenance/ptfe-tube":l?"https://wiki.bambulab.com/en/h2/maintenance/replace-ptfe-tube-on-h2d-printer":d?"https://wiki.bambulab.com/en/h2s/maintenance/replace-ptfe-tube-on-h2s-printer":c?"https://wiki.bambulab.com/en/h2/maintenance/replace-ptfe-tube-on-h2d-printer":"https://wiki.bambulab.com/en/x1/maintenance/replace-ptfe-tube";case"Replace HEPA Filter":case"HEPA Filter":case"Replace Carbon Filter":case"Carbon Filter":return u?"https://wiki.bambulab.com/en/h2/maintenance/replace-smoke-purifier-air-filte":"https://wiki.bambulab.com/en/x1/maintenance/replace-carbon-filter";case"Lubricate Left Nozzle Rail":case"Left Nozzle Rail":return u?"https://wiki.bambulab.com/en/h2/maintenance/x-axis-lubrication":null;default:return null}}const V0={Droplet:ST,Flame:mm,Ruler:Xxe,Sparkles:Dg,Square:so,Cable:hO,Wrench:qh,Calendar:Sa,Timer:Xd,Cog:cu,Fan:TZ,Zap:Nc,Wind:HZ,Thermometer:FS,Layers:oa,Box:Ni,Target:OZ,RefreshCw:sr,Settings:gy,Filter:NS,CircleDot:rge};function yw(t){return t&&V0[t]||qh}function Rx(t,e,n){if(e==="days"){if(t<1)return n?n("common.today"):"Today";if(t===1)return n?n("maintenance.day"):"1 day";if(t<7){const i=Math.round(t);return n?n("maintenance.days",{count:i}):`${i} days`}if(t<180){const i=Math.round(t/7);return i===1?n?n("maintenance.week"):"1 week":n?n("maintenance.weeks",{count:i}):`${i} weeks`}const a=Math.round(t/30);return a===1?n?n("maintenance.month"):"1 month":n?n("maintenance.months",{count:a}):`${a} months`}else{if(t<1)return`${Math.round(t*60)}m`;if(t<24)return`${t<10?t.toFixed(1):Math.round(t)}h`;const a=t/24;if(a<7)return`${a<2?a.toFixed(1):Math.round(a)}d`;const i=a/7;return i<12?`${i<2?i.toFixed(1):Math.round(i)}w`:`${Math.round(i/4)}mo`}}function mF(t,e,n){return e==="days"?t===1?n?n("maintenance.day"):"1 day":t===7?n?n("maintenance.week"):"1 week":t===14?n?n("maintenance.weeks",{count:2}):"2 weeks":t===30?n?n("maintenance.month"):"1 month":t===60?n?n("maintenance.months",{count:2}):"2 months":t===90?n?n("maintenance.months",{count:3}):"3 months":t===180?n?n("maintenance.months",{count:6}):"6 months":t===365?n?n("maintenance.year"):"1 year":n?n("maintenance.days",{count:t}):`${t} days`:`${t}h`}function Iat({item:t,onPerform:e,onToggle:n,hasPermission:a,t:i}){const s=yw(t.maintenance_type_icon),o=t.interval_type||"hours",c=(()=>{if(o==="days"){const f=t.days_since_maintenance??0;return Math.max(0,Math.min(100,f/t.interval_hours*100))}return Math.max(0,Math.min(100,(t.interval_hours-t.hours_until_due)/t.interval_hours*100))})(),d=()=>t.enabled?t.is_due?"text-red-400":t.is_warning?"text-amber-400":"text-bambu-green":"text-bambu-gray",u=()=>t.enabled?t.is_due?"bg-red-500":t.is_warning?"bg-amber-500":"bg-bambu-green":"bg-bambu-gray/30",m=()=>t.enabled?t.is_due?"bg-red-500/5 border-red-500/20":t.is_warning?"bg-amber-500/5 border-amber-500/20":"bg-bambu-dark-secondary border-bambu-dark-tertiary":"bg-bambu-dark-secondary/50",p=()=>{if(!t.enabled)return i("common.disabled");if(o==="days"){const f=t.days_until_due??0;return t.is_due?i("maintenance.overdueBy",{duration:Rx(Math.abs(f),"days",i)}):t.is_warning?i("maintenance.dueIn",{duration:Rx(f,"days",i)}):i("maintenance.timeLeft",{duration:Rx(f,"days",i)})}else return t.is_due?i("maintenance.overdueBy",{duration:Rx(Math.abs(t.hours_until_due),"hours",i)}):t.is_warning?i("maintenance.dueIn",{duration:Rx(t.hours_until_due,"hours",i)}):i("maintenance.timeLeft",{duration:Rx(t.hours_until_due,"hours",i)})};return r.jsx("div",{className:`rounded-xl border p-4 transition-all ${m()}`,children:r.jsxs("div",{className:"flex items-start gap-3 max-[550px]:flex-wrap",children:[r.jsxs("div",{className:`relative p-2.5 rounded-lg shrink-0 ${t.is_due?"bg-red-500/20":t.is_warning?"bg-amber-500/20":t.enabled?"bg-bambu-dark":"bg-bambu-dark/50"}`,children:[r.jsx(s,{className:`w-5 h-5 ${d()}`}),t.enabled&&(t.is_due||t.is_warning)&&r.jsx("span",{className:`absolute -top-1 -right-1 w-2.5 h-2.5 rounded-full ${t.is_due?"bg-red-500":"bg-amber-500"} animate-pulse`})]}),r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("h3",{className:`font-medium truncate ${t.enabled?"text-white":"text-bambu-gray"}`,children:t.maintenance_type_name}),o==="days"&&r.jsx("span",{title:i("maintenance.timeBasedInterval"),children:r.jsx(Sa,{className:"w-3.5 h-3.5 text-bambu-gray shrink-0"})}),(()=>{const f=t.maintenance_type_wiki_url||Rat(t.maintenance_type_name,t.printer_model);return f?r.jsx("a",{href:f,target:"_blank",rel:"noopener noreferrer",className:"text-bambu-gray hover:text-bambu-green transition-colors shrink-0",title:i("maintenance.viewDocumentation"),onClick:b=>b.stopPropagation(),children:r.jsx(Rr,{className:"w-3.5 h-3.5"})}):null})()]}),r.jsx("div",{className:"mt-2 mb-1.5",children:r.jsx("div",{className:"w-full h-1.5 bg-bambu-dark rounded-full overflow-hidden",children:r.jsx("div",{className:`h-full rounded-full transition-all duration-500 ${u()}`,style:{width:`${c}%`}})})}),r.jsxs("div",{className:`text-xs flex items-center gap-1 ${d()}`,children:[t.is_due&&r.jsx(Nn,{className:"w-3 h-3"}),t.is_warning&&!t.is_due&&r.jsx(Zn,{className:"w-3 h-3"}),!t.is_due&&!t.is_warning&&t.enabled&&r.jsx(_r,{className:"w-3 h-3"}),p()]})]}),r.jsxs("div",{className:"flex items-center gap-2 shrink-0 max-[550px]:w-full max-[550px]:justify-end max-[550px]:mt-1",children:[r.jsx("span",{title:a("maintenance:update")?void 0:i("maintenance.noPermissionUpdate"),children:r.jsx(En,{checked:t.enabled,onChange:f=>n(t.id,f),disabled:!a("maintenance:update")})}),r.jsxs(Me,{size:"sm",variant:t.is_due?"primary":"secondary",onClick:()=>e(t.id),disabled:!t.enabled||!a("maintenance:update"),title:a("maintenance:update")?void 0:i("maintenance.noPermissionPerform"),className:"!px-3",children:[r.jsx(gs,{className:"w-3.5 h-3.5"}),i("common.reset")]})]})]})})}function Oat({overview:t,onPerform:e,onToggle:n,onSetHours:a,hasPermission:i,t:s}){const[o,l]=v.useState(!1),[c,d]=v.useState(!1),[u,m]=v.useState(t.total_print_hours.toFixed(1)),p=[...t.maintenance_items].sort((w,g)=>w.is_due&&!g.is_due?-1:!w.is_due&&g.is_due?1:w.is_warning&&!g.is_warning?-1:!w.is_warning&&g.is_warning?1:w.maintenance_type_id-g.maintenance_type_id),f=p.find(w=>w.enabled&&(w.is_due||w.is_warning)),b=()=>{const w=parseFloat(u);!isNaN(w)&&w>=0&&(a(t.printer_id,w),d(!1))};return r.jsxs(Ct,{className:"overflow-hidden",children:[r.jsxs("div",{className:"p-5",children:[r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("div",{className:"flex items-center gap-4",children:[r.jsx("h2",{className:"text-xl font-semibold text-white",children:t.printer_name}),r.jsxs("div",{className:"flex items-center gap-2",children:[t.due_count>0&&r.jsxs("span",{className:"px-2.5 py-1 bg-red-500/20 text-red-400 text-xs font-medium rounded-full flex items-center gap-1.5",children:[r.jsx(Nn,{className:"w-3 h-3"}),s("maintenance.overdueCount",{count:t.due_count})]}),t.warning_count>0&&r.jsxs("span",{className:"px-2.5 py-1 bg-amber-500/20 text-amber-400 text-xs font-medium rounded-full flex items-center gap-1.5",children:[r.jsx(Zn,{className:"w-3 h-3"}),s("maintenance.dueSoonCount",{count:t.warning_count})]}),t.due_count===0&&t.warning_count===0&&r.jsxs("span",{className:"px-2.5 py-1 bg-bambu-green/20 text-bambu-green text-xs font-medium rounded-full flex items-center gap-1.5",children:[r.jsx(_r,{className:"w-3 h-3"}),s("maintenance.allGood")]})]})]}),r.jsxs("button",{onClick:()=>l(!o),className:"flex items-center gap-1.5 px-3 py-1.5 text-sm text-bambu-gray hover:text-white hover:bg-bambu-dark rounded-lg transition-colors",children:[o?r.jsx(tl,{className:"w-4 h-4"}):r.jsx(Ln,{className:"w-4 h-4"}),s(o?"common.collapse":"common.expand")]})]}),r.jsxs("div",{className:"flex items-center gap-6 mt-4",children:[r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("div",{className:"p-2 bg-bambu-dark/50 rounded-lg",children:r.jsx(Xd,{className:"w-4 h-4 text-bambu-gray"})}),c?r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("input",{type:"number",value:u,onChange:w=>m(w.target.value),onKeyDown:w=>{w.key==="Enter"&&b(),w.key==="Escape"&&d(!1)},className:"w-24 px-2 py-1 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-sm",min:"0",step:"1",autoFocus:!0}),r.jsx("span",{className:"text-xs text-bambu-gray",children:s("common.hours")}),r.jsx(Me,{size:"sm",onClick:b,children:s("common.save")}),r.jsx(Me,{size:"sm",variant:"secondary",onClick:()=>d(!1),children:s("common.cancel")})]}):r.jsxs("button",{onClick:()=>{i("maintenance:update")&&(m(Math.round(t.total_print_hours).toString()),d(!0))},className:`group ${i("maintenance:update")?"":"cursor-not-allowed opacity-60"}`,title:i("maintenance:update")?void 0:s("maintenance.noPermissionEditHours"),children:[r.jsxs("div",{className:`text-sm font-medium text-white ${i("maintenance:update")?"group-hover:text-bambu-green":""} transition-colors flex items-center gap-1`,children:[Math.round(t.total_print_hours)," ",s("common.hours"),r.jsx(Eg,{className:`w-3 h-3 text-bambu-gray ${i("maintenance:update")?"group-hover:text-bambu-green":""}`})]}),r.jsx("div",{className:"text-xs text-bambu-gray",children:s("maintenance.totalPrintTime")})]})]}),r.jsx("div",{className:"w-px h-10 bg-bambu-dark-tertiary"}),f&&r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("div",{className:`p-2 rounded-lg ${f.is_due?"bg-red-500/20":"bg-amber-500/20"}`,children:(()=>{const w=yw(f.maintenance_type_icon);return r.jsx(w,{className:`w-4 h-4 ${f.is_due?"text-red-400":"text-amber-400"}`})})()}),r.jsxs("div",{children:[r.jsx("div",{className:`text-sm font-medium ${f.is_due?"text-red-400":"text-amber-400"}`,children:f.maintenance_type_name}),r.jsx("div",{className:`text-xs ${f.is_due?"text-red-400/70":"text-amber-400/70"}`,children:f.is_due?s("common.overdue"):s("maintenance.dueSoon")})]})]})]})]}),o&&r.jsx(At,{className:"pt-0 border-t border-bambu-dark-tertiary",children:r.jsx("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-3 pt-4",children:p.map(w=>r.jsx(Iat,{item:w,onPerform:e,onToggle:n,hasPermission:i,t:s},w.id))})})]})}function zat({overview:t,types:e,onUpdateInterval:n,onAddType:a,onUpdateType:i,onDeleteType:s,onRestoreDefaults:o,isRestoringDefaults:l,onAssignType:c,onRemoveItem:d,hasPermission:u,t:m}){const[p,f]=v.useState(null),[b,w]=v.useState(""),[g,x]=v.useState("hours"),[_,N]=v.useState(!1),[C,P]=v.useState(""),[T,A]=v.useState("100"),[F,S]=v.useState("hours"),[M,z]=v.useState("Wrench"),[I,H]=v.useState(""),[R,Z]=v.useState(new Set),[re,J]=v.useState(null),[de,me]=v.useState(null),ue=v.useMemo(()=>t?t.map(q=>({id:q.printer_id,name:q.printer_name})):[],[t]),W=q=>t?t.filter(L=>L.maintenance_items.some(ne=>ne.maintenance_type_id===q)).map(L=>({printerId:L.printer_id,printerName:L.printer_name,itemId:L.maintenance_items.find(ne=>ne.maintenance_type_id===q)?.id})):[],ae=q=>{if(!t)return[];const L=new Set(W(q).map(ne=>ne.printerId));return ue.filter(ne=>!L.has(ne.id))},[pe,ye]=v.useState(null),[Te,$]=v.useState(""),[K,D]=v.useState(""),[j,B]=v.useState("hours"),[X,O]=v.useState("Wrench"),[ie,U]=v.useState(""),G=q=>{ye(q),$(q.name),D(q.default_interval_hours.toString()),B(q.interval_type||"hours"),O(q.icon||"Wrench"),U(q.wiki_url||"")},Y=()=>{pe&&Te.trim()&&parseFloat(K)>0&&(i(pe.id,{name:Te.trim(),default_interval_hours:parseFloat(K),interval_type:j,icon:X,wiki_url:ie.trim()||null}),ye(null))},Q=(q,L,ne)=>{const xe=parseFloat(b);if(!isNaN(xe)&&xe>0){const we=Math.abs(xe-L)<.01?null:xe;n(q,{custom_interval_hours:we,custom_interval_type:g!==ne?g:null})}f(null)},oe=q=>{q.preventDefault(),C.trim()&&parseFloat(T)>0&&R.size>0&&(a({name:C.trim(),default_interval_hours:parseFloat(T),interval_type:F,icon:M,wiki_url:I.trim()||null},Array.from(R)),P(""),A("100"),S("hours"),H(""),Z(new Set),N(!1))},ee=q=>{Z(L=>{const ne=new Set(L);return ne.has(q)?ne.delete(q):ne.add(q),ne})},ge=t?.map(q=>({printerId:q.printer_id,printerName:q.printer_name,items:q.maintenance_items.sort((L,ne)=>L.maintenance_type_id-ne.maintenance_type_id)})).sort((q,L)=>q.printerName.localeCompare(L.printerName))||[],ce=e.filter(q=>q.is_system),le=e.filter(q=>!q.is_system);return r.jsxs("div",{className:"space-y-8",children:[r.jsxs("div",{children:[r.jsxs("div",{className:"flex items-center justify-between mb-4",children:[r.jsxs("div",{children:[r.jsx("h2",{className:"text-lg font-semibold text-white",children:m("maintenance.maintenanceTypes")}),r.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:m("maintenance.maintenanceTypesDescription")})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(Me,{variant:"secondary",onClick:o,disabled:!u("maintenance:delete")||l,title:u("maintenance:delete")?void 0:m("maintenance.noPermissionDeleteTypes"),children:m("maintenance.restoreDefaults")}),r.jsxs(Me,{onClick:()=>N(!_),disabled:!u("maintenance:create"),title:u("maintenance:create")?void 0:m("maintenance.noPermissionEditTypes"),children:[r.jsx(ar,{className:"w-4 h-4"}),m("maintenance.addCustomType")]})]})]}),_&&r.jsx(Ct,{className:"mb-6",children:r.jsx(At,{className:"py-4",children:r.jsxs("form",{onSubmit:oe,children:[r.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4",children:[r.jsxs("div",{className:"lg:col-span-2",children:[r.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:m("common.name")}),r.jsx("input",{type:"text",value:C,onChange:q=>P(q.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",placeholder:m("maintenance.exampleName"),autoFocus:!0})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:m("maintenance.intervalType")}),r.jsxs("select",{value:F,onChange:q=>{S(q.target.value),q.target.value==="days"?A("30"):A("100")},className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",children:[r.jsx("option",{value:"hours",children:m("maintenance.printHours")}),r.jsx("option",{value:"days",children:m("maintenance.calendarDays")})]})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:m("maintenance.intervalValue",{type:F==="days"?m("maintenance.calendarDays").toLowerCase():m("common.hours")})}),r.jsx("input",{type:"number",value:T,onChange:q=>A(q.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",min:"1"})]})]}),r.jsx("div",{className:"mt-4 flex items-end justify-between",children:r.jsxs("div",{children:[r.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:m("maintenance.icon")}),r.jsx("div",{className:"flex gap-1",children:Object.keys(V0).map(q=>{const L=V0[q];return r.jsx("button",{type:"button",onClick:()=>z(q),className:`p-2 rounded-lg transition-colors ${M===q?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary"}`,children:r.jsx(L,{className:"w-4 h-4"})},q)})})]})}),r.jsxs("div",{className:"mt-4",children:[r.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:m("maintenance.documentationLink")}),r.jsx("input",{type:"url",value:I,onChange:q=>H(q.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",placeholder:"https://wiki.bambulab.com/..."})]}),r.jsxs("div",{className:"mt-4",children:[r.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:m("maintenance.assignToPrinters")}),r.jsx("div",{className:"flex flex-wrap gap-2",children:ue.map(q=>r.jsx("button",{type:"button",onClick:()=>ee(q.id),className:`px-3 py-1.5 rounded-lg text-sm transition-colors ${R.has(q.id)?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary"}`,children:q.name},q.id))}),R.size===0&&r.jsx("p",{className:"text-xs text-orange-400 mt-1",children:m("maintenance.selectAtLeastOnePrinter")})]}),r.jsxs("div",{className:"mt-4 flex justify-end gap-2",children:[r.jsx(Me,{type:"button",variant:"secondary",onClick:()=>{N(!1),Z(new Set)},children:m("common.cancel")}),r.jsx(Me,{type:"submit",disabled:!C.trim()||R.size===0,children:m("maintenance.addType")})]})]})})}),r.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3",children:[ce.map(q=>{const L=yw(q.icon),ne=q.interval_type||"hours";return r.jsx("div",{className:"bg-bambu-dark-secondary rounded-xl p-4 border border-bambu-dark-tertiary",children:r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("div",{className:"p-2.5 bg-bambu-dark rounded-lg",children:r.jsx(L,{className:"w-5 h-5 text-bambu-gray"})}),r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsx("div",{className:"text-sm font-medium text-white truncate",children:q.name}),r.jsxs("div",{className:"text-xs text-bambu-gray mt-0.5 flex items-center gap-1",children:[ne==="days"?r.jsx(Sa,{className:"w-3 h-3"}):r.jsx(Xd,{className:"w-3 h-3"}),mF(q.default_interval_hours,ne,m)]})]}),r.jsx("button",{onClick:()=>{u("maintenance:delete")&&me(q)},disabled:!u("maintenance:delete"),title:u("maintenance:delete")?void 0:m("maintenance.noPermissionDeleteTypes"),className:`p-2 rounded-lg hover:bg-bambu-dark text-bambu-gray hover:text-red-400 transition-colors ${u("maintenance:delete")?"":"opacity-50 cursor-not-allowed"}`,children:r.jsx(Jt,{className:"w-4 h-4"})})]})},q.id)}),le.map(q=>{const L=yw(q.icon),ne=q.interval_type||"hours";if(pe?.id===q.id)return r.jsx("div",{className:"bg-bambu-dark-secondary rounded-xl p-4 border border-bambu-green",children:r.jsxs("div",{className:"space-y-3",children:[r.jsx("input",{type:"text",value:Te,onChange:be=>$(be.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",placeholder:m("common.name"),autoFocus:!0}),r.jsxs("div",{className:"flex gap-2",children:[r.jsxs("select",{value:j,onChange:be=>B(be.target.value),className:"flex-1 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",children:[r.jsx("option",{value:"hours",children:m("maintenance.printHours")}),r.jsx("option",{value:"days",children:m("maintenance.calendarDays")})]}),r.jsx("input",{type:"number",value:K,onChange:be=>D(be.target.value),className:"w-24 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",min:"1"})]}),r.jsx("div",{className:"flex flex-wrap gap-1",children:Object.keys(V0).map(be=>{const Ee=V0[be];return r.jsx("button",{type:"button",onClick:()=>O(be),className:`p-1.5 rounded transition-colors ${X===be?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:r.jsx(Ee,{className:"w-3.5 h-3.5"})},be)})}),r.jsx("input",{type:"url",value:ie,onChange:be=>U(be.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",placeholder:m("maintenance.documentationLink")}),r.jsxs("div",{className:"flex gap-2",children:[r.jsx(Me,{size:"sm",onClick:Y,disabled:!Te.trim(),children:m("common.save")}),r.jsx(Me,{size:"sm",variant:"secondary",onClick:()=>ye(null),children:m("common.cancel")})]})]})},q.id);const we=W(q.id),Ne=ae(q.id),ve=re===q.id;return r.jsxs("div",{className:"bg-bambu-dark-secondary rounded-xl p-4 border border-bambu-green/30",children:[r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("div",{className:"p-2.5 bg-bambu-green/20 rounded-lg",children:r.jsx(L,{className:"w-5 h-5 text-bambu-green"})}),r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("span",{className:"text-sm font-medium text-white truncate",children:q.name}),r.jsx("span",{className:"px-1.5 py-0.5 bg-bambu-green/20 text-bambu-green text-[10px] font-medium rounded",children:m("maintenance.custom")})]}),r.jsxs("div",{className:"text-xs text-bambu-gray mt-0.5 flex items-center gap-1",children:[ne==="days"?r.jsx(Sa,{className:"w-3 h-3"}):r.jsx(Xd,{className:"w-3 h-3"}),mF(q.default_interval_hours,ne,m)]})]}),r.jsxs("button",{onClick:()=>J(ve?null:q.id),className:`px-2 py-1 rounded-lg border transition-colors flex items-center gap-1 ${we.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:we.length}),children:[r.jsx(pr,{className:"w-3 h-3"}),r.jsx("span",{className:"text-xs font-medium",children:we.length}),r.jsx(Ln,{className:`w-3 h-3 transition-transform ${ve?"rotate-180":""}`})]}),r.jsx("button",{onClick:()=>G(q),disabled:!u("maintenance:update"),title:u("maintenance:update")?void 0:m("maintenance.noPermissionEditTypes"),className:`p-2 rounded-lg hover:bg-bambu-dark text-bambu-gray hover:text-white transition-colors ${u("maintenance:update")?"":"opacity-50 cursor-not-allowed"}`,children:r.jsx(Eg,{className:"w-4 h-4"})}),r.jsx("button",{onClick:()=>{confirm(m("maintenance.deleteTypeConfirm",{name:q.name}))&&s(q.id)},disabled:!u("maintenance:delete"),title:u("maintenance:delete")?void 0:m("maintenance.noPermissionDeleteTypes"),className:`p-2 rounded-lg hover:bg-bambu-dark text-bambu-gray hover:text-red-400 transition-colors ${u("maintenance:delete")?"":"opacity-50 cursor-not-allowed"}`,children:r.jsx(Jt,{className:"w-4 h-4"})})]}),ve&&r.jsxs("div",{className:"mt-3 pt-3 border-t border-bambu-dark-tertiary",children:[r.jsx("p",{className:"text-xs text-bambu-gray mb-2",children:m("maintenance.assignedToPrinters")}),we.length===0?r.jsx("p",{className:"text-xs text-orange-400",children:m("maintenance.noPrintersAssigned")}):r.jsx("div",{className:"flex flex-wrap gap-1 mb-2",children:we.map(be=>r.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-1 bg-bambu-dark rounded text-xs text-white",children:[be.printerName,r.jsx("button",{onClick:()=>be.itemId&&d(be.itemId),disabled:!u("maintenance:delete"),title:u("maintenance:delete")?m("maintenance.removeFromPrinter"):m("maintenance.noPermissionRemovePrinter"),className:`ml-1 ${u("maintenance:delete")?"hover:text-red-400":"opacity-50 cursor-not-allowed"}`,children:"×"})]},be.printerId))}),Ne.length>0&&r.jsxs("div",{className:"flex flex-wrap gap-1",children:[r.jsx("span",{className:"text-xs text-bambu-gray mr-1",children:m("maintenance.addPrinterShort")}),Ne.map(be=>r.jsxs("button",{onClick:()=>c(be.id,q.id),disabled:!u("maintenance:create"),title:u("maintenance:create")?void 0:m("maintenance.noPermissionAssignPrinter"),className:`px-2 py-1 bg-bambu-dark rounded text-xs transition-colors ${u("maintenance:create")?"hover:bg-bambu-green/20 text-bambu-gray hover:text-bambu-green":"opacity-50 cursor-not-allowed text-bambu-gray"}`,children:["+ ",be.name]},be.id))]})]})]},q.id)})]})]}),ge.length>0&&r.jsxs("div",{children:[r.jsxs("div",{className:"mb-4",children:[r.jsx("h2",{className:"text-lg font-semibold text-white",children:m("maintenance.intervalOverrides")}),r.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:m("maintenance.intervalOverridesDescription")})]}),r.jsx("div",{className:"space-y-4",children:ge.map(q=>r.jsx(Ct,{children:r.jsxs(At,{className:"py-4",children:[r.jsx("h3",{className:"text-sm font-medium text-white mb-3",children:q.printerName}),r.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-2",children:q.items.map(L=>{const ne=yw(L.maintenance_type_icon),xe=e.find(Ee=>Ee.id===L.maintenance_type_id),we=xe?.default_interval_hours||L.interval_hours,Ne=xe?.interval_type||"hours",ve=L.interval_type||"hours",be=p===L.id;return r.jsxs("div",{className:"flex items-center gap-2 p-2.5 bg-bambu-dark rounded-lg",children:[r.jsx(ne,{className:"w-4 h-4 text-bambu-gray shrink-0"}),r.jsx("span",{className:"text-xs text-bambu-gray flex-1 truncate",children:L.maintenance_type_name}),be?r.jsxs("div",{className:"flex items-center gap-1",children:[g==="days"?r.jsx(Sa,{className:"w-3.5 h-3.5 text-bambu-gray shrink-0"}):r.jsx(Xd,{className:"w-3.5 h-3.5 text-bambu-gray shrink-0"}),r.jsxs("select",{value:g,onChange:Ee=>x(Ee.target.value),className:"px-1.5 py-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-xs",children:[r.jsx("option",{value:"hours",children:m("maintenance.printHours")}),r.jsx("option",{value:"days",children:m("maintenance.calendarDays")})]}),r.jsx("input",{type:"number",value:b,onChange:Ee=>w(Ee.target.value),onKeyDown:Ee=>{Ee.key==="Enter"&&Q(L.id,we,Ne),Ee.key==="Escape"&&f(null)},className:"w-16 px-2 py-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-xs",min:"1"}),r.jsx(Me,{size:"sm",onClick:()=>Q(L.id,we,Ne),children:"OK"})]}):r.jsxs("button",{onClick:()=>{u("maintenance:update")&&(f(L.id),w(L.interval_hours.toString()),x(ve))},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:[ve==="days"?r.jsx(Sa,{className:"w-3 h-3"}):r.jsx(Xd,{className:"w-3 h-3"}),mF(L.interval_hours,ve,m),r.jsx(Eg,{className:"w-3 h-3 text-bambu-gray"})]})]},L.id)})})]})},q.printerId))})]}),ge.length===0&&r.jsx(Ct,{children:r.jsxs(At,{className:"text-center py-12",children:[r.jsx(Zn,{className:"w-12 h-12 mx-auto mb-4 text-bambu-gray/30"}),r.jsx("p",{className:"text-bambu-gray",children:m("common.noPrinters")}),r.jsx("p",{className:"text-sm text-bambu-gray/70 mt-1",children:m("maintenance.intervalOverridesDescription")})]})}),de&&r.jsx(vn,{title:m("maintenance.deleteSystemTypeTitle"),message:m("maintenance.deleteSystemTypeMessage",{name:de.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(de.id),me(null)},onCancel:()=>me(null)})]})}function Uat(){const{t}=kt(),e=en(),{showToast:n}=rn(),{hasPermission:a}=cr(),[i,s]=v.useState("status"),{data:o,isLoading:l}=We({queryKey:["maintenanceOverview"],queryFn:se.getMaintenanceOverview}),{data:c}=We({queryKey:["maintenanceTypes"],queryFn:se.getMaintenanceTypes}),d=it({mutationFn:({id:T,notes:A})=>se.performMaintenance(T,A),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]}),e.invalidateQueries({queryKey:["maintenanceSummary"]}),n(t("maintenance.maintenanceComplete"))},onError:T=>{n(T.message,"error")}}),u=it({mutationFn:({id:T,data:A})=>se.updateMaintenanceItem(T,A),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]})},onError:T=>{n(T.message,"error")}}),m=it({mutationFn:({id:T,data:A})=>se.updateMaintenanceType(T,A),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceTypes"]}),e.invalidateQueries({queryKey:["maintenanceOverview"]}),n(t("maintenance.typeUpdated"))},onError:T=>{n(T.message,"error")}}),p=it({mutationFn:se.deleteMaintenanceType,onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceTypes"]}),e.invalidateQueries({queryKey:["maintenanceOverview"]}),n(t("maintenance.typeDeleted"))},onError:T=>{n(T.message,"error")}}),f=it({mutationFn:se.restoreDefaultMaintenanceTypes,onSuccess:T=>{e.invalidateQueries({queryKey:["maintenanceTypes"]}),e.invalidateQueries({queryKey:["maintenanceOverview"]}),n(t("maintenance.defaultsRestored",{count:T.restored}))},onError:T=>{n(T.message,"error")}}),b=it({mutationFn:({printerId:T,hours:A})=>se.setPrinterHours(T,A),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]}),e.invalidateQueries({queryKey:["maintenanceSummary"]}),n(t("maintenance.printHoursUpdated"))},onError:T=>{n(T.message,"error")}}),w=it({mutationFn:({printerId:T,typeId:A})=>se.assignMaintenanceType(T,A),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]}),n(t("maintenance.printerAssigned"))},onError:T=>{n(T.message,"error")}}),g=it({mutationFn:se.removeMaintenanceItem,onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]}),n(t("maintenance.printerRemoved"))},onError:T=>{n(T.message,"error")}}),x=T=>{d.mutate({id:T})},_=(T,A)=>{u.mutate({id:T,data:{enabled:A}})},N=(T,A)=>{b.mutate({printerId:T,hours:A})};if(l)return r.jsx("div",{className:"p-4 md:p-8 flex justify-center",children:r.jsx(ut,{className:"w-8 h-8 text-bambu-green animate-spin"})});const C=o?.reduce((T,A)=>T+A.due_count,0)||0,P=o?.reduce((T,A)=>T+A.warning_count,0)||0;return r.jsxs("div",{className:"p-4 md:p-8",children:[r.jsxs("div",{className:"mb-6",children:[r.jsxs("h1",{className:"text-2xl font-bold text-white flex items-center gap-3",children:[r.jsx(qh,{className:"w-7 h-7 text-bambu-green"}),t("maintenance.title")]}),r.jsx("p",{className:"text-bambu-gray mt-1",children:i==="status"?r.jsxs(r.Fragment,{children:[C>0&&r.jsx("span",{className:"text-red-400",children:t("maintenance.dueCount",{count:C})}),C>0&&P>0&&" · ",P>0&&r.jsx("span",{className:"text-amber-400",children:t("maintenance.warningCount",{count:P})}),C===0&&P===0&&r.jsx("span",{className:"text-bambu-green",children:t("maintenance.allOk")})]}):t("maintenance.configureSettings")})]}),r.jsxs("div",{className:"flex gap-1 mb-6 border-b border-bambu-dark-tertiary",children:[r.jsx("button",{onClick:()=>s("status"),className:`px-4 py-2 text-sm font-medium border-b-2 -mb-px transition-colors ${i==="status"?"text-bambu-green border-bambu-green":"text-bambu-gray border-transparent hover:text-white"}`,children:t("maintenance.statusTab")}),r.jsx("button",{onClick:()=>s("settings"),className:`px-4 py-2 text-sm font-medium border-b-2 -mb-px transition-colors ${i==="settings"?"text-bambu-green border-bambu-green":"text-bambu-gray border-transparent hover:text-white"}`,children:t("maintenance.settingsTab")})]}),i==="status"?r.jsx("div",{className:"space-y-6",children:o&&o.length>0?[...o].sort((T,A)=>{const F=T.due_count*10+T.warning_count,S=A.due_count*10+A.warning_count;return F!==S?S-F:T.printer_name.localeCompare(A.printer_name)}).map(T=>r.jsx(Oat,{overview:T,onPerform:x,onToggle:_,onSetHours:N,hasPermission:a,t},T.printer_id)):r.jsx(Ct,{children:r.jsxs(At,{className:"text-center py-16",children:[r.jsx(qh,{className:"w-16 h-16 mx-auto mb-4 text-bambu-gray/30"}),r.jsx("p",{className:"text-lg font-medium text-white mb-2",children:t("common.noPrinters")}),r.jsx("p",{className:"text-bambu-gray",children:t("maintenance.configureSettings")})]})})}):r.jsx(zat,{overview:o,types:c||[],onUpdateInterval:(T,A)=>u.mutate({id:T,data:A}),onAddType:async(T,A)=>{const F=await se.createMaintenanceType(T);for(const S of A)await se.assignMaintenanceType(S,F.id);e.invalidateQueries({queryKey:["maintenanceTypes"]}),e.invalidateQueries({queryKey:["maintenanceOverview"]}),n(t("maintenance.typeUpdated"))},onUpdateType:(T,A)=>m.mutate({id:T,data:A}),onDeleteType:T=>p.mutate(T),onRestoreDefaults:()=>f.mutate(),isRestoringDefaults:f.isPending,onAssignType:(T,A)=>w.mutate({printerId:T,typeId:A}),onRemoveItem:T=>g.mutate(T),hasPermission:a,t})]})}const mQ=["#ef4444","#f97316","#eab308","#22c55e","#06b6d4","#3b82f6","#8b5cf6","#ec4899","#6b7280"];function Lce({project:t,onClose:e,onSave:n,isLoading:a,currencySymbol:i,t:s}){const[o,l]=v.useState(t?.name||""),[c,d]=v.useState(t?.description||""),[u,m]=v.useState(t?.color||mQ[0]),[p,f]=v.useState(t?.target_count?.toString()||""),[b,w]=v.useState(t?.target_parts_count?.toString()||""),[g,x]=v.useState(t?.status||"active"),[_,N]=v.useState(t?.tags||""),[C,P]=v.useState(t?.due_date?.split("T")[0]||""),[T,A]=v.useState(t?.priority||"normal"),[F,S]=v.useState(t?.budget?.toString()||""),[M,z]=v.useState(t?.url||""),[I,H]=v.useState(null),R=en(),[Z,re]=v.useState(t?.cover_image_filename||null),J=v.useRef(null),[de,me]=v.useState(!1),[ue,W]=v.useState(0),ae=async Te=>{const $=Te.target.files?.[0];if(!(!$||!t)){me(!0);try{const K=await se.uploadProjectCoverImage(t.id,$);re(K.filename),W(D=>D+1),R.invalidateQueries({queryKey:["projects"]})}catch{}finally{me(!1),J.current&&(J.current.value="")}}},pe=async()=>{if(t){me(!0);try{await se.deleteProjectCoverImage(t.id),re(null),W(Te=>Te+1),R.invalidateQueries({queryKey:["projects"]})}finally{me(!1)}}},ye=Te=>{Te.preventDefault();const $=M.trim();if($&&!/^https?:\/\//i.test($)){H(s("projects.urlInvalid"));return}H(null),n({name:o.trim(),description:c.trim()||void 0,color:u,target_count:p?parseInt(p,10):void 0,target_parts_count:b?parseInt(b,10):void 0,tags:_.trim()||void 0,due_date:C||void 0,priority:T,budget:F.trim()?parseFloat(F):null,url:t?$||null:$||void 0,...t&&{status:g}})};return r.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:r.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-md border border-bambu-dark-tertiary",children:[r.jsx("div",{className:"p-4 border-b border-bambu-dark-tertiary",children:r.jsx("h2",{className:"text-lg font-semibold text-white",children:s(t?"projects.editProject":"projects.newProject")})}),r.jsxs("form",{onSubmit:ye,className:"p-4 space-y-4",children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("common.name")}),r.jsx("input",{type:"text",value:o,onChange:Te=>l(Te.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:s("projects.namePlaceholder"),required:!0})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("common.description")}),r.jsx("textarea",{value:c,onChange:Te=>d(Te.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green resize-none",placeholder:s("projects.descriptionPlaceholder"),rows:2})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("projects.urlLabel")}),r.jsx("input",{type:"url",value:M,onChange:Te=>{z(Te.target.value),I&&H(null)},className:`w-full bg-bambu-dark border rounded px-3 py-2 text-white placeholder-bambu-gray focus:outline-none ${I?"border-red-500 focus:border-red-500":"border-bambu-dark-tertiary focus:border-bambu-green"}`,placeholder:s("projects.urlPlaceholder"),maxLength:2048}),I&&r.jsx("p",{className:"text-xs text-red-400 mt-1",children:I})]}),t&&r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("projects.coverImageLabel")}),r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("div",{className:"w-20 h-20 rounded bg-bambu-dark border border-bambu-dark-tertiary overflow-hidden flex items-center justify-center flex-shrink-0",children:Z?r.jsx("img",{src:`${se.getProjectCoverImageUrl(t.id)}?v=${ue}`,alt:s("projects.coverImageAlt"),className:"w-full h-full object-cover"}):r.jsx(du,{className:"w-6 h-6 text-bambu-gray"})}),r.jsxs("div",{className:"flex flex-col gap-2",children:[r.jsx("input",{ref:J,type:"file",accept:"image/jpeg,image/png,image/gif,image/webp",onChange:ae,className:"hidden"}),r.jsxs(Me,{type:"button",variant:"secondary",onClick:()=>J.current?.click(),disabled:de,children:[de?r.jsx(ut,{className:"w-4 h-4 animate-spin"}):r.jsx(ka,{className:"w-4 h-4 mr-1"}),s(Z?"projects.coverImageReplace":"projects.coverImageUpload")]}),Z&&r.jsxs(Me,{type:"button",variant:"secondary",onClick:pe,disabled:de,children:[r.jsx(Bt,{className:"w-4 h-4 mr-1"}),s("projects.coverImageRemove")]})]})]})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("projects.color")}),r.jsx("div",{className:"flex gap-2 flex-wrap",children:mQ.map(Te=>r.jsx("button",{type:"button",onClick:()=>m(Te),className:`w-8 h-8 rounded-full transition-transform ${u===Te?"ring-2 ring-white ring-offset-2 ring-offset-bambu-dark-secondary scale-110":""}`,style:{backgroundColor:Te}},Te))})]}),r.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("projects.targetPlates")}),r.jsx("input",{type:"number",value:p,onChange:Te=>f(Te.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:s("projects.targetPlatesPlaceholder"),min:"1"}),r.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:s("projects.targetPlatesHelp")})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("projects.targetParts")}),r.jsx("input",{type:"number",value:b,onChange:Te=>w(Te.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:s("projects.targetPartsPlaceholder"),min:"1"}),r.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:s("projects.targetPartsHelp")})]})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("projects.tagsLabel")}),r.jsx("input",{type:"text",value:_,onChange:Te=>N(Te.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:s("projects.tagsPlaceholder")})]}),r.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("projects.dueDate")}),r.jsx("input",{type:"date",value:C,onChange:Te=>P(Te.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white focus:outline-none focus:border-bambu-green"})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("projects.priority")}),r.jsxs("select",{value:T,onChange:Te=>A(Te.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white focus:outline-none focus:border-bambu-green",children:[r.jsx("option",{value:"low",children:s("projects.priorityLow")}),r.jsx("option",{value:"normal",children:s("projects.priorityNormal")}),r.jsx("option",{value:"high",children:s("projects.priorityHigh")}),r.jsx("option",{value:"urgent",children:s("projects.priorityUrgent")})]})]})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("projectDetail.cost.budget")}),r.jsxs("div",{className:"relative",children:[r.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-bambu-gray pointer-events-none",children:i}),r.jsx("input",{type:"number",step:"0.01",min:"0",value:F,onChange:Te=>S(Te.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded pl-8 pr-3 py-2 text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:"0.00"})]})]}),t&&r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("common.status")}),r.jsxs("select",{value:g,onChange:Te=>x(Te.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white focus:outline-none focus:border-bambu-green",children:[r.jsx("option",{value:"active",children:s("projects.statusActive")}),r.jsx("option",{value:"completed",children:s("projects.statusCompleted")}),r.jsx("option",{value:"archived",children:s("projects.statusArchived")})]})]}),r.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[r.jsx(Me,{type:"button",variant:"secondary",onClick:e,children:s("common.cancel")}),r.jsx(Me,{type:"submit",disabled:!o.trim()||a,children:a?r.jsx(ut,{className:"w-4 h-4 animate-spin"}):s(t?"common.save":"projects.create")})]})]})]})})}function Bat({projectId:t,altText:e}){const n=v.useRef(null),[a,i]=v.useState(!1),[s,o]=v.useState(null),l=()=>{if(!n.current)return;const d=n.current.getBoundingClientRect(),u=384,m=8,p=window.innerWidth,f=window.innerHeight;let b=d.right+m;b+u>p-8&&(b=d.left-u-m);let w=d.top;w+u>f-8&&(w=f-u-8),w<8&&(w=8),o({left:b,top:w}),i(!0)},c=()=>i(!1);return r.jsxs("div",{ref:n,className:"relative flex-shrink-0",onMouseEnter:l,onMouseLeave:c,onClick:d=>d.stopPropagation(),children:[r.jsx("div",{className:"w-10 h-10 rounded-lg overflow-hidden bg-bambu-dark border border-bambu-dark-tertiary",children:r.jsx("img",{src:se.getProjectCoverImageUrl(t),alt:e,className:"w-full h-full object-cover",loading:"lazy"})}),a&&s&&Yd.createPortal(r.jsx("div",{className:"fixed z-[100] w-96 h-96 rounded-lg overflow-hidden border border-bambu-dark-tertiary shadow-2xl bg-bambu-dark pointer-events-none",style:{left:s.left,top:s.top},"aria-hidden":"true",children:r.jsx("img",{src:se.getProjectCoverImageUrl(t),alt:"",className:"w-full h-full object-contain",loading:"lazy"})}),document.body)]})}function Hat({project:t,onClick:e,onEdit:n,onDelete:a,hasPermission:i,t:s}){const o=t.target_count?Math.round(t.archive_count/t.target_count*100):0,l=t.target_parts_count?Math.round(t.completed_count/t.target_parts_count*100):0,c=t.status==="completed",d=t.status==="archived",[u,m]=v.useState(!1),f=c?{icon:rd,color:"text-bambu-green",bg:"bg-bambu-green/10"}:d?{icon:ro,color:"text-bambu-gray",bg:"bg-bambu-gray/10"}:t.queue_count>0?{icon:Zn,color:"text-blue-400",bg:"bg-blue-400/10"}:{icon:ao,color:"text-bambu-gray",bg:"bg-bambu-gray/10"};return r.jsxs("div",{className:"group relative bg-gradient-to-br from-bambu-card to-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary hover:border-bambu-green/50 hover:shadow-lg hover:shadow-bambu-green/5 transition-all duration-300 cursor-pointer overflow-hidden",onClick:e,children:[r.jsx("div",{className:"absolute top-0 left-0 w-1.5 h-full",style:{backgroundColor:t.color||"#6b7280",boxShadow:`0 0 12px ${t.color||"#6b7280"}40`}}),r.jsxs("div",{className:"p-5 pl-6",children:[r.jsxs("div",{className:"flex items-start justify-between mb-4",children:[r.jsxs("div",{className:"flex items-center gap-3 min-w-0 flex-1",children:[t.cover_image_filename?r.jsx(Bat,{projectId:t.id,altText:s("projects.coverImageAlt")}):r.jsx("div",{className:`p-2 rounded-lg ${f.bg} flex-shrink-0`,children:r.jsx(f.icon,{className:`w-5 h-5 ${f.color}`})}),r.jsxs("div",{className:"min-w-0 flex-1",children:[r.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[r.jsx("h3",{className:"font-semibold text-white truncate",children:t.name}),t.url&&r.jsx("a",{href:t.url,target:"_blank",rel:"noopener noreferrer",onClick:b=>b.stopPropagation(),title:t.url,"aria-label":s("projects.openExternalUrl"),className:"inline-flex items-center justify-center w-6 h-6 rounded bg-bambu-dark border border-bambu-dark-tertiary text-bambu-green hover:bg-bambu-green/10 hover:border-bambu-green transition-colors flex-shrink-0",children:r.jsx(Rr,{className:"w-3.5 h-3.5"})}),t.target_parts_count?r.jsxs("span",{className:`text-xs px-2 py-0.5 rounded-full whitespace-nowrap font-medium ${l>=100?"bg-bambu-green/20 text-bambu-green":"bg-bambu-dark text-bambu-gray"}`,children:[t.completed_count,"/",t.target_parts_count," ",s("projects.parts")]}):t.target_count?r.jsxs("span",{className:`text-xs px-2 py-0.5 rounded-full whitespace-nowrap font-medium ${o>=100?"bg-bambu-green/20 text-bambu-green":"bg-bambu-dark text-bambu-gray"}`,children:[t.archive_count,"/",t.target_count," ",s("projects.plates")]}):t.completed_count>0?r.jsxs("span",{className:"text-xs px-2 py-0.5 rounded-full whitespace-nowrap font-medium bg-bambu-dark text-bambu-gray",children:[t.completed_count," ",s("projects.parts")]}):null,c&&r.jsx("span",{className:"text-xs bg-bambu-green/20 text-bambu-green px-2 py-0.5 rounded-full whitespace-nowrap",children:s("projects.done")}),d&&r.jsx("span",{className:"text-xs bg-bambu-gray/20 text-bambu-gray px-2 py-0.5 rounded-full whitespace-nowrap",children:s("projects.statusArchived")})]}),t.description&&r.jsx("p",{className:"text-sm text-bambu-gray/70 mt-1 line-clamp-1",children:t.description}),t.archives&&t.archives.length>0&&(()=>{const b=t.archives.map(_=>_.filament_type).filter(Boolean).flatMap(_=>_.split(",").map(N=>N.trim())).filter(Boolean),w=[...new Set(b)],g=t.archives.map(_=>_.filament_color).filter(Boolean).flatMap(_=>_.split(",").map(N=>N.trim())).filter(_=>_.startsWith("#")||/^[0-9A-Fa-f]{6}$/.test(_)),x=[...new Set(g)];return w.length===0&&x.length===0?null:r.jsxs("div",{className:"flex items-center gap-2 mt-1.5",children:[w.slice(0,3).map(_=>r.jsx("span",{className:"text-[10px] px-1.5 py-0.5 bg-bambu-dark text-bambu-gray rounded",children:_},_)),x.length>0&&r.jsxs("div",{className:"flex items-center gap-0.5",children:[x.slice(0,5).map(_=>r.jsx("div",{className:"w-3 h-3 rounded-full border border-black/20",style:{backgroundColor:_.startsWith("#")?_:`#${_}`},title:_},_)),x.length>5&&r.jsxs("span",{className:"text-[10px] text-bambu-gray ml-0.5",children:["+",x.length-5]})]})]})})()]})]}),r.jsxs("div",{className:"relative",onClick:b=>b.stopPropagation(),children:[r.jsx("button",{className:"p-1.5 rounded-lg hover:bg-bambu-dark text-bambu-gray hover:text-white transition-colors opacity-0 group-hover:opacity-100",onClick:()=>m(!u),children:r.jsx(ym,{className:"w-4 h-4"})}),u&&r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>m(!1)}),r.jsxs("div",{className:"absolute right-0 top-8 z-20 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl py-1 min-w-[120px]",children:[r.jsxs("button",{className:`w-full px-3 py-2 text-left text-sm flex items-center gap-2 ${i("projects:update")?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{i("projects:update")&&(n(),m(!1))},disabled:!i("projects:update"),title:i("projects:update")?void 0:s("projects.noEditPermission"),children:[r.jsx(Eg,{className:"w-4 h-4"}),s("common.edit")]}),r.jsxs("button",{className:`w-full px-3 py-2 text-left text-sm flex items-center gap-2 ${i("projects:delete")?"text-red-400 hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{i("projects:delete")&&(a(),m(!1))},disabled:!i("projects:delete"),title:i("projects:delete")?void 0:s("projects.noDeletePermission"),children:[r.jsx(Jt,{className:"w-4 h-4"}),s("common.delete")]})]})]})]})]}),r.jsx("div",{className:"mb-4",children:t.target_count||t.target_parts_count?r.jsxs("div",{className:"space-y-3",children:[t.target_count&&r.jsxs("div",{children:[r.jsxs("div",{className:"flex items-center justify-between text-xs mb-1",children:[r.jsx("span",{className:"text-bambu-gray",children:s("projects.plates")}),r.jsxs("span",{className:o>=100?"text-bambu-green font-medium":"text-white",children:[t.archive_count," / ",t.target_count]})]}),r.jsx("div",{className:"h-2 bg-bambu-dark/80 rounded-full overflow-hidden backdrop-blur-sm",children:r.jsx("div",{className:"h-full transition-all duration-500 ease-out rounded-full relative",style:{width:`${Math.min(o,100)}%`,background:o>=100?"linear-gradient(90deg, #22c55e, #4ade80)":`linear-gradient(90deg, ${t.color||"#6b7280"}, ${t.color||"#6b7280"}cc)`,boxShadow:`0 0 8px ${o>=100?"#22c55e":t.color||"#6b7280"}60`}})})]}),t.target_parts_count&&r.jsxs("div",{children:[r.jsxs("div",{className:"flex items-center justify-between text-xs mb-1",children:[r.jsx("span",{className:"text-bambu-gray",children:s("projects.parts")}),r.jsxs("span",{className:l>=100?"text-bambu-green font-medium":"text-white",children:[t.completed_count," / ",t.target_parts_count]})]}),r.jsx("div",{className:"h-2 bg-bambu-dark/80 rounded-full overflow-hidden backdrop-blur-sm",children:r.jsx("div",{className:"h-full transition-all duration-500 ease-out rounded-full relative",style:{width:`${Math.min(l,100)}%`,background:l>=100?"linear-gradient(90deg, #22c55e, #4ade80)":`linear-gradient(90deg, ${t.color||"#6b7280"}, ${t.color||"#6b7280"}cc)`,boxShadow:`0 0 8px ${l>=100?"#22c55e":t.color||"#6b7280"}60`}})})]}),t.failed_count>0&&r.jsxs("div",{className:"text-xs text-red-400",children:[t.failed_count," ",s("projects.failed")]})]}):t.completed_count>0||t.failed_count>0?r.jsxs("div",{className:"flex items-center gap-4 text-xs",children:[t.completed_count>0&&r.jsxs("div",{className:"flex items-center gap-1.5 text-bambu-gray",children:[r.jsx(ro,{className:"w-3.5 h-3.5"}),r.jsxs("span",{children:[t.completed_count," ",s("projects.completed")]})]}),t.failed_count>0&&r.jsxs("div",{className:"flex items-center gap-1.5 text-red-400",children:[r.jsx(Nn,{className:"w-3.5 h-3.5"}),r.jsxs("span",{children:[t.failed_count," ",s("projects.failed")]})]}),t.queue_count>0&&r.jsxs("div",{className:"flex items-center gap-1.5 text-blue-400",children:[r.jsx(Zn,{className:"w-3.5 h-3.5"}),r.jsxs("span",{children:[t.queue_count," ",s("projects.inQueue")]})]})]}):r.jsx("div",{className:"text-xs text-bambu-gray/60 italic",children:s("projects.noPrintsYet")})}),t.archives&&t.archives.length>0&&r.jsxs("div",{className:"mb-4",children:[r.jsx("div",{className:"grid grid-cols-4 gap-1.5",children:t.archives.slice(0,4).map(b=>r.jsxs("div",{className:"relative aspect-square rounded-lg bg-bambu-dark overflow-hidden border border-bambu-dark-tertiary",title:b.print_name||"Unknown",children:[b.thumbnail_path?r.jsx("img",{src:se.getArchiveThumbnail(b.id),alt:b.print_name||"",className:"w-full h-full object-cover"}):r.jsx("div",{className:"w-full h-full flex items-center justify-center text-bambu-gray/50",children:r.jsx(Br,{className:"w-6 h-6"})}),b.status==="failed"&&r.jsx("div",{className:"absolute inset-0 bg-red-500/40 flex items-center justify-center",children:r.jsx(Nn,{className:"w-4 h-4 text-white"})})]},b.id))}),t.archive_count>4&&r.jsx("p",{className:"text-xs text-bambu-gray mt-1.5 text-center",children:s("common.more",{count:t.archive_count-4})})]}),r.jsxs("div",{className:"flex items-center justify-between pt-3 border-t border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"flex items-center gap-4 text-xs text-bambu-gray",children:[r.jsxs("div",{className:"flex items-center gap-1.5",title:s("projects.printJobs"),children:[r.jsx(oa,{className:"w-3.5 h-3.5 text-blue-400"}),r.jsxs("span",{children:[t.archive_count," ",s("projects.plates")]})]}),r.jsxs("div",{className:"flex items-center gap-1.5",title:s("projects.partsPrinted"),children:[r.jsx(Br,{className:"w-3.5 h-3.5 text-bambu-green"}),r.jsxs("span",{children:[t.completed_count," ",s("projects.parts")]})]}),t.failed_count>0&&r.jsxs("div",{className:"flex items-center gap-1.5 text-red-400",title:s("projects.failedParts"),children:[r.jsx(Nn,{className:"w-3.5 h-3.5"}),r.jsx("span",{children:t.failed_count})]}),t.queue_count>0&&r.jsxs("div",{className:"flex items-center gap-1.5 text-yellow-400",title:s("projects.inQueue"),children:[r.jsx(qF,{className:"w-3.5 h-3.5"}),r.jsx("span",{children:t.queue_count})]})]}),r.jsx(Va,{className:"w-4 h-4 text-bambu-gray/50 group-hover:text-bambu-gray transition-colors"})]})]})]})}function qat(){const{t}=kt(),e=Di(),n=en(),{showToast:a}=rn(),{hasPermission:i}=cr(),[s,o]=v.useState(!1),[l,c]=v.useState(),[d,u]=v.useState("active"),[m,p]=v.useState(null),{data:f}=We({queryKey:["settings"],queryFn:se.getSettings}),b=Vo(f?.currency||"USD"),{data:w,isLoading:g}=We({queryKey:["projects",d==="all"?void 0:d],queryFn:()=>se.getProjects(d==="all"?void 0:d)}),x=it({mutationFn:Z=>se.createProject(Z),onSuccess:()=>{n.invalidateQueries({queryKey:["projects"]}),o(!1),a(t("projects.toast.created"),"success")},onError:Z=>{a(Z.message,"error")}}),_=it({mutationFn:({id:Z,data:re})=>se.updateProject(Z,re),onSuccess:()=>{n.invalidateQueries({queryKey:["projects"]}),o(!1),c(void 0),a(t("projects.toast.updated"),"success")},onError:Z=>{a(Z.message,"error")}}),N=it({mutationFn:Z=>se.deleteProject(Z),onSuccess:()=>{p(null),a(t("projects.toast.deleted"),"success"),setTimeout(()=>window.location.reload(),100)},onError:Z=>{p(null),a(Z.message,"error")}}),C=it({mutationFn:Z=>se.importProject(Z),onSuccess:()=>{n.invalidateQueries({queryKey:["projects"]}),a(t("projects.toast.imported"),"success")},onError:Z=>{a(Z.message,"error")}}),P=v.useRef(null),T=async()=>{try{const Z=await se.getProjects(),re=await Promise.all(Z.map(async ue=>await se.exportProjectJson(ue.id))),J=new Blob([JSON.stringify(re,null,2)],{type:"application/json"}),de=URL.createObjectURL(J),me=document.createElement("a");me.href=de,me.download=`bambuddy_projects_${new Date().toISOString().split("T")[0]}.json`,me.click(),URL.revokeObjectURL(de),a(t("projects.toast.exported"),"success")}catch(Z){a(Z.message,"error")}},A=()=>{P.current?.click()},F=async Z=>{const re=Z.target.files?.[0];if(re){try{if(re.name.toLowerCase().endsWith(".zip"))await se.importProjectFile(re),n.invalidateQueries({queryKey:["projects"]}),a(t("projects.toast.imported"),"success");else{const de=await re.text(),me=JSON.parse(de),ue=Array.isArray(me)?me:[me];for(const W of ue)await C.mutateAsync(W);ue.length>1&&a(t("projects.toast.multipleImported",{count:ue.length}),"success")}}catch(J){a(`${t("projects.toast.importFailed")}: ${J.message}`,"error")}Z.target.value=""}},S=Z=>{l?_.mutate({id:l.id,data:Z}):x.mutate(Z)},M=Z=>{c(Z),o(!0)},z=Z=>{e(`/projects/${Z.id}`)},I=Z=>{p(Z)},H=()=>{m!==null&&N.mutate(m)},R=w?.reduce((Z,re)=>(Z[re.status]=(Z[re.status]||0)+1,Z.all=(Z.all||0)+1,Z),{})||{};return r.jsxs("div",{className:"p-4 md:p-8 space-y-8",children:[r.jsx("input",{ref:P,type:"file",accept:".json,.zip",onChange:F,className:"hidden"}),r.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4",children:[r.jsxs("div",{children:[r.jsxs("h1",{className:"text-2xl font-bold text-white flex items-center gap-3",children:[r.jsx(ao,{className:"w-7 h-7 text-bambu-green"}),t("projects.title")]}),r.jsx("p",{className:"text-bambu-gray mt-1",children:t("projects.subtitle")})]}),r.jsxs("div",{className:"flex gap-2",children:[r.jsxs(Me,{variant:"secondary",onClick:A,disabled:!i("projects:create"),title:i("projects:create")?t("projects.importProject"):t("projects.noImportPermission"),children:[r.jsx(ka,{className:"w-4 h-4 mr-2"}),t("projects.import")]}),r.jsxs(Me,{variant:"secondary",onClick:T,disabled:!i("projects:read"),title:i("projects:read")?t("projects.exportAll"):t("projects.noExportPermission"),children:[r.jsx(Yr,{className:"w-4 h-4 mr-2"}),t("projects.export")]}),r.jsxs(Me,{onClick:()=>o(!0),className:"sm:w-auto w-full",disabled:!i("projects:create"),title:i("projects:create")?void 0:t("projects.noCreatePermission"),children:[r.jsx(ar,{className:"w-4 h-4 mr-2"}),t("projects.newProject")]})]})]}),r.jsx("div",{className:"flex gap-1 p-1 bg-bambu-dark rounded-xl w-fit",children:[{key:"active",label:t("projects.statusActive"),icon:Zn},{key:"completed",label:t("projects.statusCompleted"),icon:rd},{key:"archived",label:t("projects.statusArchived"),icon:ro},{key:"all",label:t("common.all"),icon:ao}].map(({key:Z,label:re,icon:J})=>r.jsxs("button",{onClick:()=>u(Z),className:`flex items-center gap-2 px-4 py-2 text-sm rounded-lg transition-all ${d===Z?"bg-bambu-card text-white shadow-sm":"text-bambu-gray hover:text-white"}`,children:[r.jsx(J,{className:"w-4 h-4"}),r.jsx("span",{children:re}),R[Z]>0&&r.jsx("span",{className:`text-xs px-1.5 py-0.5 rounded-full ${d===Z?"bg-bambu-green/20 text-bambu-green":"bg-bambu-dark-tertiary"}`,children:R[Z]})]},Z))}),g?r.jsx("div",{className:"flex items-center justify-center py-20",children:r.jsxs("div",{className:"flex flex-col items-center gap-3",children:[r.jsx(ut,{className:"w-8 h-8 animate-spin text-bambu-green"}),r.jsx("p",{className:"text-sm text-bambu-gray",children:t("projects.loading")})]})}):w?.length===0?r.jsxs("div",{className:"flex flex-col items-center justify-center py-20 px-4",children:[r.jsx("div",{className:"p-4 bg-bambu-dark rounded-2xl mb-4",children:r.jsx(ao,{className:"w-12 h-12 text-bambu-gray/50"})}),r.jsx("h3",{className:"text-lg font-medium text-white mb-2",children:d==="all"?t("projects.noProjects"):t("projects.noProjectsFiltered",{status:d})}),r.jsx("p",{className:"text-bambu-gray text-center max-w-md mb-6",children:d==="all"?t("projects.createFirst"):t("projects.noProjectsFilteredHelp",{status:d})}),d==="all"&&r.jsxs(Me,{onClick:()=>o(!0),disabled:!i("projects:create"),title:i("projects:create")?void 0:t("projects.noCreatePermission"),children:[r.jsx(ar,{className:"w-4 h-4 mr-2"}),t("projects.createFirstButton")]})]}):r.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-8",children:w?.map(Z=>r.jsx(Hat,{project:Z,onClick:()=>z(Z),onEdit:()=>M(Z),onDelete:()=>I(Z.id),hasPermission:i,t},Z.id))}),m!==null&&r.jsx(vn,{title:t("projects.deleteProject"),message:t("projects.deleteConfirm"),confirmText:t("projects.deleteProject"),variant:"danger",onConfirm:H,onCancel:()=>p(null)}),s&&r.jsx(Lce,{project:l,onClose:()=>{o(!1),c(void 0)},onSave:S,isLoading:x.isPending||_.isPending,currencySymbol:b,t})]})}function $at(t){const e=t.toLowerCase();return e.endsWith(".gcode")||e.endsWith(".gcode.3mf")}function Vat(t){return t>=1e3?`${(t/1e3).toFixed(2)}kg`:`${Math.round(t)}g`}function Gat({status:t,t:e}){const n={active:"bg-bambu-green/20 text-bambu-green",completed:"bg-blue-500/20 text-blue-400",archived:"bg-bambu-gray/20 text-bambu-gray"},a=n[t]||n.active,i={active:e("projectDetail.status.active"),completed:e("projectDetail.status.completed"),archived:e("projectDetail.status.archived")};return r.jsx("span",{className:`px-2 py-1 rounded text-sm font-medium ${a}`,children:i[t]||t.charAt(0).toUpperCase()+t.slice(1)})}function pQ({icon:t,label:e,value:n,subValue:a,hint:i,color:s="text-bambu-gray"}){return r.jsx(Ct,{children:r.jsx(At,{className:"p-4",children:r.jsxs("div",{className:"flex items-center gap-3",title:i,children:[r.jsx("div",{className:`p-2 rounded-lg bg-bambu-dark ${s}`,children:r.jsx(t,{className:"w-5 h-5"})}),r.jsxs("div",{children:[r.jsx("p",{className:"text-sm text-bambu-gray",children:e}),r.jsx("p",{className:"text-xl font-semibold text-white",children:n}),a&&r.jsx("p",{className:"text-xs text-bambu-gray/70",children:a})]})]})})})}function Wat({archives:t,t:e}){return t.length===0?r.jsxs("div",{className:"text-center py-8 text-bambu-gray",children:[r.jsx(Br,{className:"w-12 h-12 mx-auto mb-2 opacity-50"}),r.jsx("p",{children:e("projectDetail.noPrints")})]}):r.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6 gap-3",children:t.map(n=>r.jsxs(Is,{to:`/archives?search=${encodeURIComponent(n.print_name||"")}`,className:"group relative aspect-square rounded-lg bg-bambu-dark border border-bambu-dark-tertiary overflow-hidden hover:border-bambu-green transition-colors",children:[n.thumbnail_path?r.jsx("img",{src:se.getArchiveThumbnail(n.id),alt:n.print_name||"Print",className:"w-full h-full object-cover"}):r.jsx("div",{className:"w-full h-full flex items-center justify-center text-bambu-gray",children:r.jsx(Br,{className:"w-8 h-8"})}),n.status==="failed"&&r.jsx("div",{className:"absolute inset-0 bg-red-500/30 flex items-center justify-center",children:r.jsx(Da,{className:"w-8 h-8 text-white"})}),n.status==="completed"&&r.jsx("div",{className:"absolute top-1 right-1",children:r.jsx(wr,{className:"w-4 h-4 text-bambu-green"})}),r.jsx("div",{className:"absolute inset-x-0 bottom-0 bg-gradient-to-t from-black/80 to-transparent p-2 opacity-0 group-hover:opacity-100 transition-opacity",children:r.jsx("p",{className:"text-xs text-white truncate",children:n.print_name||"Unknown"})})]},n.id))})}function Kat({priority:t,t:e}){const n={low:{color:"bg-gray-500/20 text-gray-400",label:e("projectDetail.priority.low")},normal:{color:"bg-blue-500/20 text-blue-400",label:e("projectDetail.priority.normal")},high:{color:"bg-orange-500/20 text-orange-400",label:e("projectDetail.priority.high")},urgent:{color:"bg-red-500/20 text-red-400",label:e("projectDetail.priority.urgent")}},{color:a,label:i}=n[t]||n.normal;return r.jsxs("span",{className:`px-2 py-1 rounded text-xs font-medium flex items-center gap-1 ${a}`,children:[t==="urgent"&&r.jsx(Nn,{className:"w-3 h-3"}),i]})}function pF(t,e){if(!t)return null;const n=Xn(t);if(!n)return null;const a=new Date,i=Math.ceil((n.getTime()-a.getTime())/(1e3*60*60*24));return i<0?{color:"text-red-400",label:e("projectDetail.dueDate.overdue")}:i===0?{color:"text-orange-400",label:e("projectDetail.dueDate.today")}:i<=3?{color:"text-yellow-400",label:e("projectDetail.dueDate.daysLeft",{count:i})}:{color:"text-bambu-gray",label:e("projectDetail.dueDate.daysLeft",{count:i})}}function Yat(){const{id:t}=_S(),e=Di(),{t:n}=kt(),a=en(),{showToast:i}=rn(),{hasPermission:s}=cr(),[o,l]=v.useState(!1),[c,d]=v.useState(!1),[u,m]=v.useState(""),[p,f]=v.useState(null),[b,w]=v.useState(null),g=parseInt(t||"0",10),{data:x,isLoading:_,error:N}=We({queryKey:["project",g],queryFn:()=>se.getProject(g),enabled:g>0}),{data:C,isLoading:P}=We({queryKey:["project-archives",g],queryFn:()=>se.getProjectArchives(g),enabled:g>0}),{data:T,isLoading:A}=We({queryKey:["project-bom",g],queryFn:()=>se.getProjectBOM(g),enabled:g>0}),{data:F,isLoading:S}=We({queryKey:["project-timeline",g],queryFn:()=>se.getProjectTimeline(g,20),enabled:g>0}),{data:M}=We({queryKey:["settings"],queryFn:se.getSettings}),{data:z}=We({queryKey:["project-folders",g],queryFn:()=>se.getLibraryFoldersByProject(g),enabled:g>0}),{data:I,isLoading:H}=We({queryKey:["project-files",g],queryFn:()=>se.getLibraryFiles(null,!1,g),enabled:g>0}),R=v.useMemo(()=>{const fe=new Map;for(const Ae of I??[])if(Ae.folder_id!=null){const $e=fe.get(Ae.folder_id)??[];$e.push(Ae),fe.set(Ae.folder_id,$e)}return fe},[I]),Z=Vo(M?.currency||"USD"),re=M?.time_format||"system",J=it({mutationFn:fe=>se.updateProject(g,fe),onSuccess:()=>{a.invalidateQueries({queryKey:["project",g]}),a.invalidateQueries({queryKey:["projects"]}),l(!1),d(!1),i(n("projectDetail.toast.projectUpdated"),"success")},onError:fe=>{i(fe.message,"error")}}),de=()=>{m(x?.notes||""),d(!0)},me=()=>{J.mutate({notes:u})},ue=()=>{d(!1),m("")},[W,ae]=v.useState(""),[pe,ye]=v.useState(1),[Te,$]=v.useState(""),[K,D]=v.useState(""),[j,B]=v.useState(""),[X,O]=v.useState(!1),[ie,U]=v.useState(!1),[G,Y]=v.useState(null),[Q,oe]=v.useState(""),[ee,ge]=v.useState(1),[ce,le]=v.useState(""),[q,L]=v.useState(""),[ne,xe]=v.useState(""),[we,Ne]=v.useState({isOpen:!1,title:"",message:"",onConfirm:()=>{}}),ve=it({mutationFn:fe=>se.createBOMItem(g,fe),onSuccess:()=>{a.invalidateQueries({queryKey:["project-bom",g]}),a.invalidateQueries({queryKey:["project",g]}),ae(""),ye(1),$(""),D(""),B(""),O(!1),i(n("projectDetail.toast.partAdded"),"success")},onError:fe=>i(fe.message,"error")}),be=it({mutationFn:({itemId:fe,data:Ae})=>se.updateBOMItem(g,fe,Ae),onSuccess:()=>{a.invalidateQueries({queryKey:["project-bom",g]}),a.invalidateQueries({queryKey:["project",g]}),Y(null)},onError:fe=>i(fe.message,"error")}),Ee=it({mutationFn:fe=>se.deleteBOMItem(g,fe),onSuccess:()=>{a.invalidateQueries({queryKey:["project-bom",g]}),a.invalidateQueries({queryKey:["project",g]}),i(n("projectDetail.toast.partRemoved"),"success")},onError:fe=>i(fe.message,"error")}),ze=fe=>{fe.preventDefault(),W.trim()&&ve.mutate({name:W.trim(),quantity_needed:pe,unit_price:Te?parseFloat(Te):void 0,sourcing_url:K.trim()||void 0,remarks:j.trim()||void 0})},_e=fe=>{const Ae=fe.is_complete?0:fe.quantity_needed;be.mutate({itemId:fe.id,data:{quantity_acquired:Ae}})},Oe=(fe,Ae)=>{Ne({isOpen:!0,title:n("projectDetail.bom.deletePart"),message:n("projectDetail.bom.deleteConfirm",{name:Ae}),onConfirm:()=>{Ne($e=>({...$e,isOpen:!1})),Ee.mutate(fe)}})},Ie=fe=>{Y(fe),oe(fe.name),ge(fe.quantity_needed),le(fe.unit_price?.toString()||""),L(fe.sourcing_url||""),xe(fe.remarks||"")},Ke=fe=>{fe.preventDefault(),!(!G||!Q.trim())&&be.mutate({itemId:G.id,data:{name:Q.trim(),quantity_needed:ee,unit_price:ce?parseFloat(ce):void 0,sourcing_url:q.trim()||void 0,remarks:ne.trim()||void 0}})},rt=()=>{Y(null)},st=async()=>{try{const{blob:fe,filename:Ae}=await se.exportProjectZip(Number(g)),$e=URL.createObjectURL(fe),Be=document.createElement("a");Be.href=$e,Be.download=Ae||`${x?.name||"project"}_${new Date().toISOString().split("T")[0]}.zip`,Be.click(),URL.revokeObjectURL($e),i(n("projectDetail.toast.projectExported"),"success")}catch(fe){i(fe.message,"error")}},Le=it({mutationFn:()=>se.createTemplateFromProject(g),onSuccess:()=>{a.invalidateQueries({queryKey:["projects"]}),i(n("projectDetail.toast.templateCreated"),"success")},onError:fe=>i(fe.message,"error")}),tt=fe=>Rg(fe,re,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"});if(_)return r.jsx("div",{className:"flex items-center justify-center py-24",children:r.jsx(ut,{className:"w-8 h-8 animate-spin text-bambu-green"})});if(N||!x)return r.jsxs("div",{className:"text-center py-24",children:[r.jsx("p",{className:"text-bambu-gray",children:N?`${n("common.error")}: ${N.message}`:n("projectDetail.notFound")}),r.jsx(Me,{variant:"secondary",className:"mt-4",onClick:()=>e("/projects"),children:n("projectDetail.backToProjects")})]});const Ce=x.stats,Xe=Ce?.progress_percent??0,Ue=Ce?.parts_progress_percent??0;return r.jsxs("div",{className:"p-4 md:p-8 space-y-8",children:[r.jsxs("div",{className:"flex items-center gap-2 text-sm text-bambu-gray",children:[r.jsx(Is,{to:"/projects",className:"hover:text-white transition-colors",children:n("nav.projects")}),r.jsx(Va,{className:"w-4 h-4"}),r.jsx("span",{className:"text-white",children:x.name})]}),r.jsxs("div",{className:"flex items-start justify-between",children:[r.jsxs("div",{className:"flex items-center gap-4",children:[r.jsx("button",{onClick:()=>e("/projects"),className:"p-2 rounded-lg bg-bambu-card hover:bg-bambu-dark-tertiary transition-colors",children:r.jsx(vT,{className:"w-5 h-5 text-bambu-gray"})}),r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("div",{className:"w-4 h-4 rounded-full shrink-0",style:{backgroundColor:x.color||"#6b7280"}}),r.jsxs("div",{children:[r.jsx("h1",{className:"text-2xl font-bold text-white",children:x.name}),x.description&&r.jsx("p",{className:"text-bambu-gray mt-1",children:x.description})]})]}),r.jsx(Gat,{status:x.status,t:n})]}),r.jsxs("div",{className:"flex gap-2",children:[r.jsxs(Me,{variant:"secondary",onClick:st,disabled:!s("projects:read"),title:s("projects:read")?n("projectDetail.exportProject"):n("projectDetail.noExportPermission"),children:[r.jsx(Yr,{className:"w-4 h-4 mr-2"}),n("projectDetail.export")]}),r.jsxs(Me,{onClick:()=>l(!0),disabled:!s("projects:update"),title:s("projects:update")?void 0:n("projectDetail.noEditPermission"),children:[r.jsx(Eg,{className:"w-4 h-4 mr-2"}),n("common.edit")]})]})]}),(x.target_count||x.target_parts_count)&&r.jsx(Ct,{children:r.jsxs(At,{className:"p-4 space-y-4",children:[x.target_count&&r.jsxs("div",{children:[r.jsxs("div",{className:"flex items-center justify-between mb-2",children:[r.jsx("span",{className:"text-sm text-bambu-gray",children:n("projectDetail.progress.platesProgress")}),r.jsxs("span",{className:"text-sm font-medium text-white",children:[Ce?.total_archives||0," / ",x.target_count," ",n("projectDetail.progress.printJobs")]})]}),r.jsx("div",{className:"h-3 bg-bambu-dark rounded-full overflow-hidden",children:r.jsx("div",{className:"h-full transition-all duration-500",style:{width:`${Math.min(Xe,100)}%`,backgroundColor:Xe>=100?"#22c55e":x.color||"#6b7280"}})}),r.jsxs("div",{className:"flex justify-between mt-1",children:[r.jsx("span",{className:"text-xs text-bambu-gray/70",children:n("projectDetail.progress.percentComplete",{percent:Xe.toFixed(0)})}),Ce?.remaining_prints!=null&&Ce.remaining_prints>0&&r.jsx("span",{className:"text-xs text-bambu-gray/70",children:n("projectDetail.progress.remaining",{count:Ce.remaining_prints})})]})]}),x.target_parts_count&&r.jsxs("div",{children:[r.jsxs("div",{className:"flex items-center justify-between mb-2",children:[r.jsx("span",{className:"text-sm text-bambu-gray",children:n("projectDetail.progress.partsProgress")}),r.jsxs("span",{className:"text-sm font-medium text-white",children:[Ce?.completed_prints||0," / ",x.target_parts_count," ",n("projectDetail.progress.parts")]})]}),r.jsx("div",{className:"h-3 bg-bambu-dark rounded-full overflow-hidden",children:r.jsx("div",{className:"h-full transition-all duration-500",style:{width:`${Math.min(Ue,100)}%`,backgroundColor:Ue>=100?"#22c55e":x.color||"#6b7280"}})}),r.jsxs("div",{className:"flex justify-between mt-1",children:[r.jsx("span",{className:"text-xs text-bambu-gray/70",children:n("projectDetail.progress.percentComplete",{percent:Ue.toFixed(0)})}),Ce?.remaining_parts!=null&&Ce.remaining_parts>0&&r.jsx("span",{className:"text-xs text-bambu-gray/70",children:n("projectDetail.progress.remaining",{count:Ce.remaining_parts})})]})]})]})}),Ce&&r.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[r.jsx(Ct,{children:r.jsx(At,{className:"p-4",children:r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("div",{className:"p-2 rounded-lg bg-bambu-dark text-bambu-green",children:r.jsx(Br,{className:"w-5 h-5"})}),r.jsxs("div",{children:[r.jsx("p",{className:"text-sm text-bambu-gray",children:n("projectDetail.stats.printJobs")}),r.jsxs("p",{className:"text-xl font-semibold text-white",children:[Ce.total_archives," ",r.jsx("span",{className:"text-sm font-normal text-bambu-gray",children:n("projectDetail.stats.total")})]}),Ce.failed_prints>0&&r.jsx("p",{className:"text-sm text-status-error",children:n("projectDetail.stats.failed",{count:Ce.failed_prints})}),r.jsx("p",{className:"text-sm text-bambu-gray",children:n("projectDetail.stats.partsPrinted",{count:Ce.completed_prints})})]})]})})}),r.jsx(pQ,{icon:Zn,label:n("projectDetail.stats.printTime"),value:Fve(Ce.total_print_time_hours),color:"text-yellow-400"}),r.jsx(pQ,{icon:pr,label:n("projectDetail.stats.filamentUsed"),value:Vat(Ce.total_filament_grams),color:"text-purple-400"})]}),Ce&&(()=>{const fe=Ce.estimated_cost+Ce.total_energy_cost+Ce.bom_cost;return Ce.estimated_cost>0||fe>0||x.budget!==null})()&&r.jsx(Ct,{children:r.jsxs(At,{className:"p-4",children:[r.jsx("h2",{className:"text-lg font-semibold text-white mb-3",children:n("projectDetail.cost.title")}),r.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[r.jsxs("div",{children:[r.jsx("p",{className:"text-xs text-bambu-gray uppercase",children:n("projectDetail.cost.filamentCost")}),r.jsxs("p",{className:"text-lg font-semibold text-white",children:[Z,Ce.estimated_cost.toFixed(2)]})]}),Ce.total_energy_kwh>0&&r.jsxs("div",{children:[r.jsx("p",{className:"text-xs text-bambu-gray uppercase",children:n("projectDetail.cost.energy")}),r.jsxs("p",{className:"text-lg font-semibold text-white",children:[Ce.total_energy_kwh.toFixed(3)," kWh",Ce.total_energy_cost>0&&r.jsxs("span",{className:"text-sm text-bambu-gray ml-1",children:["(",Z,Ce.total_energy_cost.toFixed(2),")"]})]})]}),(()=>{const fe=Ce.estimated_cost+Ce.total_energy_cost+Ce.bom_cost;return fe<=0?null:r.jsxs("div",{children:[r.jsx("p",{className:"text-xs text-bambu-gray uppercase",children:n("projectDetail.cost.totalCost")}),r.jsxs("p",{className:"text-lg font-semibold text-bambu-green",children:[Z,fe.toFixed(2)]}),Ce.bom_cost>0&&r.jsx("p",{className:"text-xs text-bambu-gray/70",children:n("projectDetail.cost.includesBom")})]})})(),x.budget!==null&&(()=>{const fe=Ce.estimated_cost+Ce.total_energy_cost+Ce.bom_cost,Ae=x.budget-fe;return r.jsxs("div",{children:[r.jsx("p",{className:"text-xs text-bambu-gray uppercase",children:n("projectDetail.cost.budget")}),r.jsxs("p",{className:"text-sm text-bambu-gray",children:[n("projectDetail.cost.total"),": ",r.jsxs("span",{className:"text-white font-semibold",children:[Z,x.budget.toFixed(2)]})]}),r.jsxs("p",{className:`text-sm ${Ae>=0?"text-bambu-green":"text-red-400"}`,children:[n("projectDetail.cost.remaining"),": ",r.jsxs("span",{className:"font-semibold",children:[Z,Ae.toFixed(2)]})]})]})})()]})]})}),x.children&&x.children.length>0&&r.jsx(Ct,{children:r.jsxs(At,{className:"p-4",children:[r.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2 mb-3",children:[r.jsx(fbe,{className:"w-5 h-5"}),n("projectDetail.subProjects.title",{count:x.children.length})]}),r.jsx("div",{className:"space-y-2",children:x.children.map(fe=>r.jsxs(Is,{to:`/projects/${fe.id}`,className:"flex items-center justify-between p-3 bg-bambu-dark rounded-lg hover:bg-bambu-dark-tertiary transition-colors",children:[r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("div",{className:"w-3 h-3 rounded-full",style:{backgroundColor:fe.color||"#6b7280"}}),r.jsx("span",{className:"text-white",children:fe.name}),r.jsx("span",{className:`text-xs px-2 py-0.5 rounded ${fe.status==="completed"?"bg-status-ok/20 text-status-ok":fe.status==="archived"?"bg-bambu-gray/20 text-bambu-gray":"bg-blue-500/20 text-blue-400"}`,children:fe.status})]}),fe.progress_percent!==null&&r.jsxs("span",{className:"text-sm text-bambu-gray",children:[fe.progress_percent.toFixed(0),"%"]})]},fe.id))})]})}),x.parent_id&&x.parent_name&&r.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[r.jsx(oa,{className:"w-4 h-4 text-bambu-gray"}),r.jsx("span",{className:"text-bambu-gray",children:n("projectDetail.partOf")}),r.jsx(Is,{to:`/projects/${x.parent_id}`,className:"text-bambu-green hover:underline",children:x.parent_name})]}),(x.tags||x.due_date||x.priority!=="normal")&&r.jsxs("div",{className:"flex flex-wrap items-center gap-4",children:[x.priority&&x.priority!=="normal"&&r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("span",{className:"text-xs text-bambu-gray uppercase",children:n("projectDetail.priorityLabel")}),r.jsx(Kat,{priority:x.priority,t:n})]}),x.due_date&&r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(Sa,{className:"w-4 h-4 text-bambu-gray"}),r.jsx("span",{className:"text-sm text-white",children:Lg(x.due_date,{year:"numeric",month:"short",day:"numeric"})}),pF(x.due_date,n)&&r.jsxs("span",{className:`text-xs ${pF(x.due_date,n).color}`,children:["(",pF(x.due_date,n).label,")"]})]}),x.tags&&r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx($m,{className:"w-4 h-4 text-bambu-gray"}),r.jsx("div",{className:"flex flex-wrap gap-1",children:x.tags.split(",").map((fe,Ae)=>r.jsx("span",{className:"px-2 py-0.5 bg-bambu-dark-tertiary text-bambu-gray text-xs rounded",children:fe.trim()},Ae))})]})]}),r.jsx(Ct,{children:r.jsxs(At,{className:"p-4",children:[r.jsxs("div",{className:"flex items-center justify-between mb-3",children:[r.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[r.jsx(Bs,{className:"w-5 h-5"}),n("projectDetail.notes.title")]}),c?r.jsxs("div",{className:"flex gap-2",children:[r.jsxs(Me,{variant:"secondary",size:"sm",onClick:ue,disabled:J.isPending,children:[r.jsx(Bt,{className:"w-4 h-4 mr-1"}),n("common.cancel")]}),r.jsxs(Me,{size:"sm",onClick:me,disabled:J.isPending,children:[J.isPending?r.jsx(ut,{className:"w-4 h-4 animate-spin mr-1"}):r.jsx(us,{className:"w-4 h-4 mr-1"}),n("common.save")]})]}):r.jsxs(Me,{variant:"secondary",size:"sm",onClick:de,disabled:!s("projects:update"),title:s("projects:update")?void 0:n("projectDetail.notes.noEditPermission"),children:[r.jsx(Eg,{className:"w-4 h-4 mr-1"}),n("common.edit")]})]}),c?r.jsx(UI,{content:u,onChange:m,placeholder:n("projectDetail.notes.placeholder")}):x.notes?r.jsx("div",{className:"prose prose-invert prose-sm max-w-none",dangerouslySetInnerHTML:{__html:c5.sanitize(x.notes)}}):r.jsx("p",{className:"text-bambu-gray/70 text-sm italic",children:n("projectDetail.notes.empty")})]})}),r.jsx(Ct,{children:r.jsxs(At,{className:"p-4",children:[r.jsx("div",{className:"flex items-center justify-between mb-3",children:r.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[r.jsx(Fl,{className:"w-5 h-5"}),n("projectDetail.files.title")]})}),r.jsxs("p",{className:"text-xs text-bambu-gray mb-3",children:[r.jsx(Is,{to:"/files",className:"text-bambu-green hover:underline",children:n("projectDetail.files.linkFolders")})," ",n("projectDetail.files.forQuickAccess")]}),z&&z.length>0?r.jsx("div",{className:"space-y-4",children:z.map(fe=>{const Ae=R.get(fe.id)??[],$e=H;return r.jsxs("div",{children:[r.jsxs(Is,{to:`/files?folder=${fe.id}`,className:"flex items-center justify-between p-3 bg-bambu-dark rounded-lg hover:bg-bambu-dark-tertiary transition-colors mb-2",children:[r.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[r.jsx(Fl,{className:"w-5 h-5 text-bambu-green shrink-0"}),r.jsxs("div",{className:"min-w-0",children:[r.jsx("p",{className:"text-sm text-white truncate",children:fe.name}),r.jsx("p",{className:"text-xs text-bambu-gray",children:n("projectDetail.files.fileCount",{count:fe.file_count})})]})]}),r.jsx(Va,{className:"w-4 h-4 text-bambu-gray shrink-0"})]}),$e?r.jsx("div",{className:"flex items-center gap-2 px-3 py-2 text-bambu-gray text-sm",children:r.jsx(ut,{className:"w-4 h-4 animate-spin"})}):Ae.length===0?r.jsx("p",{className:"text-bambu-gray/60 text-xs italic px-3",children:n("projectDetail.files.noFiles")}):r.jsx("div",{className:"space-y-1 pl-3",children:Ae.map(Be=>{const nt=$at(Be.filename);return r.jsxs("div",{className:"flex items-center gap-3 p-2 rounded-lg hover:bg-bambu-dark-tertiary transition-colors",children:[r.jsx("div",{className:"w-10 h-10 shrink-0 rounded bg-bambu-dark overflow-hidden flex items-center justify-center",children:Be.thumbnail_path?r.jsx("img",{src:se.getLibraryFileThumbnailUrl(Be.id),alt:Be.print_name||Be.filename,className:"w-full h-full object-cover"}):r.jsx(Nh,{className:"w-5 h-5 text-bambu-gray/40"})}),r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsx("p",{className:"text-sm text-white truncate",title:Be.print_name||Be.filename,children:Be.print_name||Be.filename}),r.jsx("span",{className:`text-xs px-1.5 py-0.5 rounded font-medium ${Be.file_type==="3mf"?"bg-bambu-green/20 text-bambu-green":Be.file_type==="gcode"?"bg-blue-500/20 text-blue-400":"bg-bambu-gray/20 text-bambu-gray"}`,children:Be.file_type.toUpperCase()})]}),nt&&r.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[r.jsx("button",{onClick:()=>f(Be),title:n("projectDetail.files.print"),className:"p-1.5 rounded hover:bg-bambu-green/20 text-bambu-green transition-colors",children:r.jsx(fs,{className:"w-4 h-4"})}),r.jsx("button",{onClick:()=>w(Be),title:n("projectDetail.files.addToQueue"),className:"p-1.5 rounded hover:bg-blue-500/20 text-blue-400 transition-colors",children:r.jsx(Ife,{className:"w-4 h-4"})})]})]},Be.id)})})]},fe.id)})}):r.jsx("p",{className:"text-bambu-gray/70 text-sm italic",children:n("projectDetail.files.empty")})]})}),r.jsx(Ct,{children:r.jsxs(At,{className:"p-4",children:[r.jsxs("div",{className:"flex items-center justify-between mb-4",children:[r.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[r.jsx(lb,{className:"w-5 h-5"}),n("projectDetail.bom.title"),Ce&&Ce.bom_total_items>0&&r.jsxs("span",{className:"text-sm font-normal text-bambu-gray",children:["(",n("projectDetail.bom.acquired",{completed:Ce.bom_completed_items,total:Ce.bom_total_items}),")"]})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[T&&T.some(fe=>fe.is_complete)&&r.jsx("button",{onClick:()=>U(!ie),className:`text-xs px-2 py-1 rounded transition-colors ${ie?"bg-bambu-green/20 text-bambu-green":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:n(ie?"projectDetail.bom.showAll":"projectDetail.bom.hideDone")}),!X&&r.jsxs(Me,{variant:"secondary",size:"sm",onClick:()=>O(!0),disabled:!s("projects:update"),title:s("projects:update")?void 0:n("projectDetail.bom.noAddPermission"),children:[r.jsx(ar,{className:"w-4 h-4 mr-1"}),n("projectDetail.bom.addPart")]})]})]}),X&&r.jsxs("form",{onSubmit:ze,className:"bg-bambu-dark rounded-lg p-4 mb-4 space-y-3",children:[r.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[r.jsx("input",{type:"text",value:W,onChange:fe=>ae(fe.target.value),className:"bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:n("projectDetail.bom.partNamePlaceholder"),autoFocus:!0}),r.jsxs("div",{className:"flex gap-2",children:[r.jsx("input",{type:"number",value:pe,onChange:fe=>ye(parseInt(fe.target.value)||1),className:"w-20 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white focus:outline-none focus:border-bambu-green",min:"1",placeholder:n("projectDetail.bom.qty")}),r.jsx("input",{type:"number",step:"0.01",value:Te,onChange:fe=>$(fe.target.value),className:"flex-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:n("projectDetail.bom.price",{currency:Z})})]})]}),r.jsx("input",{type:"url",value:K,onChange:fe=>D(fe.target.value),className:"w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:n("projectDetail.bom.sourcingUrlPlaceholder")}),r.jsx("input",{type:"text",value:j,onChange:fe=>B(fe.target.value),className:"w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:n("projectDetail.bom.remarksPlaceholder")}),r.jsxs("div",{className:"flex justify-end gap-2",children:[r.jsx(Me,{type:"button",variant:"secondary",size:"sm",onClick:()=>O(!1),children:n("common.cancel")}),r.jsx(Me,{type:"submit",size:"sm",disabled:!W.trim()||ve.isPending,children:ve.isPending?r.jsx(ut,{className:"w-4 h-4 animate-spin"}):n("projectDetail.bom.addPart")})]})]}),A?r.jsx("div",{className:"flex items-center justify-center py-4",children:r.jsx(ut,{className:"w-6 h-6 animate-spin text-bambu-green"})}):T&&T.length>0?r.jsxs("div",{className:"space-y-2",children:[T.filter(fe=>!ie||!fe.is_complete).map(fe=>r.jsx("div",{className:`p-3 rounded-lg transition-colors ${fe.is_complete?"bg-status-ok/10":"bg-bambu-dark"}`,children:G?.id===fe.id?r.jsxs("form",{onSubmit:Ke,className:"space-y-3",children:[r.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[r.jsx("input",{type:"text",value:Q,onChange:Ae=>oe(Ae.target.value),className:"bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:n("projectDetail.bom.partName"),autoFocus:!0}),r.jsxs("div",{className:"flex gap-2",children:[r.jsx("input",{type:"number",value:ee,onChange:Ae=>ge(parseInt(Ae.target.value)||1),className:"w-20 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white focus:outline-none focus:border-bambu-green",min:"1",placeholder:n("projectDetail.bom.qty")}),r.jsx("input",{type:"number",step:"0.01",value:ce,onChange:Ae=>le(Ae.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:Z})})]})]}),r.jsx("input",{type:"url",value:q,onChange:Ae=>L(Ae.target.value),className:"w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:n("projectDetail.bom.sourcingUrlPlaceholder")}),r.jsx("input",{type:"text",value:ne,onChange:Ae=>xe(Ae.target.value),className:"w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:n("projectDetail.bom.remarksPlaceholder")}),r.jsxs("div",{className:"flex justify-end gap-2",children:[r.jsx(Me,{type:"button",variant:"secondary",size:"sm",onClick:rt,children:n("common.cancel")}),r.jsx(Me,{type:"submit",size:"sm",disabled:!Q.trim()||be.isPending,children:be.isPending?r.jsx(ut,{className:"w-4 h-4 animate-spin"}):n("common.save")})]})]}):r.jsxs("div",{className:"flex items-start gap-3",children:[r.jsx("button",{onClick:()=>s("projects:update")&&_e(fe),disabled:be.isPending||!s("projects:update"),title:s("projects:update")?void 0:n("projectDetail.bom.noUpdatePermission"),className:`w-5 h-5 mt-0.5 rounded border-2 flex items-center justify-center transition-colors shrink-0 ${fe.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:fe.is_complete&&r.jsx(wr,{className:"w-3 h-3"})}),r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsxs("div",{className:"flex items-center justify-between gap-2",children:[r.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[r.jsxs("p",{className:`text-sm font-medium ${fe.is_complete?"text-bambu-gray line-through":"text-white"}`,children:[fe.name,r.jsxs("span",{className:"text-bambu-gray font-normal ml-2",children:["x",fe.quantity_needed]})]}),fe.unit_price!==null&&r.jsxs("span",{className:"text-xs text-bambu-green whitespace-nowrap",children:[Z,(fe.unit_price*fe.quantity_needed).toFixed(2)]})]}),r.jsxs("div",{className:"flex items-center gap-1",children:[r.jsx("button",{onClick:()=>s("projects:update")&&Ie(fe),disabled:!s("projects:update"),className:`p-1 rounded transition-colors shrink-0 ${s("projects:update")?"hover:bg-bambu-dark-tertiary text-bambu-gray hover:text-white":"text-bambu-gray/50 cursor-not-allowed"}`,title:s("projects:update")?n("common.edit"):n("projectDetail.bom.noEditPermission"),children:r.jsx(oi,{className:"w-4 h-4"})}),r.jsx("button",{onClick:()=>s("projects:update")&&Oe(fe.id,fe.name),disabled:!s("projects:update"),className:`p-1 rounded transition-colors shrink-0 ${s("projects:update")?"hover:bg-bambu-dark-tertiary text-bambu-gray hover:text-red-400":"text-bambu-gray/50 cursor-not-allowed"}`,title:s("projects:update")?n("common.delete"):n("projectDetail.bom.noDeletePermission"),children:r.jsx(Jt,{className:"w-4 h-4"})})]})]}),fe.sourcing_url&&r.jsxs("a",{href:fe.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:Ae=>Ae.stopPropagation(),children:[r.jsx(Rr,{className:"w-3 h-3 shrink-0"}),r.jsx("span",{className:"truncate",children:(()=>{try{return new URL(fe.sourcing_url).hostname.replace("www.","")}catch{return fe.sourcing_url}})()})]}),fe.remarks&&r.jsx("p",{className:"mt-1 text-xs text-bambu-gray/80 italic",children:fe.remarks})]})]})},fe.id)),Ce&&Ce.bom_cost>0&&r.jsxs("div",{className:"pt-2 mt-2 border-t border-bambu-dark-tertiary flex justify-between text-sm",children:[r.jsx("span",{className:"text-bambu-gray",children:n("projectDetail.bom.totalCost")}),r.jsxs("span",{className:"text-white font-medium",children:[Z,Ce.bom_cost.toFixed(2)]})]})]}):r.jsx("p",{className:"text-bambu-gray/70 text-sm italic",children:n("projectDetail.bom.empty")})]})}),r.jsx(Ct,{children:r.jsxs(At,{className:"p-4",children:[r.jsx("div",{className:"flex items-center justify-between mb-3",children:r.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[r.jsx(Aw,{className:"w-5 h-5"}),n("projectDetail.timeline.title")]})}),S?r.jsx("div",{className:"flex items-center justify-center py-4",children:r.jsx(ut,{className:"w-6 h-6 animate-spin text-bambu-green"})}):F&&F.length>0?r.jsx("div",{className:"space-y-3",children:F.slice(0,10).map((fe,Ae)=>r.jsxs("div",{className:"flex gap-3",children:[r.jsxs("div",{className:`w-8 h-8 rounded-full flex items-center justify-center shrink-0 ${fe.event_type==="print_completed"?"bg-status-ok/20 text-status-ok":fe.event_type==="print_failed"?"bg-status-error/20 text-status-error":fe.event_type==="print_started"?"bg-yellow-500/20 text-yellow-400":"bg-bambu-dark-tertiary text-bambu-gray"}`,children:[fe.event_type==="print_completed"&&r.jsx(wr,{className:"w-4 h-4"}),fe.event_type==="print_failed"&&r.jsx(Da,{className:"w-4 h-4"}),fe.event_type==="print_started"&&r.jsx(pr,{className:"w-4 h-4"}),fe.event_type==="queued"&&r.jsx(qF,{className:"w-4 h-4"}),fe.event_type==="project_created"&&r.jsx(ar,{className:"w-4 h-4"})]}),r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsx("p",{className:"text-sm text-white",children:fe.title}),fe.description&&r.jsx("p",{className:"text-xs text-bambu-gray truncate",children:fe.description}),r.jsx("p",{className:"text-xs text-bambu-gray/70",children:tt(fe.timestamp)})]})]},Ae))}):r.jsx("p",{className:"text-bambu-gray/70 text-sm italic",children:n("projectDetail.timeline.empty")})]})}),!x.is_template&&r.jsx("div",{className:"flex justify-end",children:r.jsxs(Me,{variant:"secondary",size:"sm",onClick:()=>Le.mutate(),disabled:Le.isPending||!s("projects:create"),title:s("projects:create")?void 0:n("projectDetail.template.noCreatePermission"),children:[Le.isPending?r.jsx(ut,{className:"w-4 h-4 animate-spin mr-2"}):r.jsx(Mi,{className:"w-4 h-4 mr-2"}),n("projectDetail.template.saveAsTemplate")]})}),Ce&&(Ce.queued_prints>0||Ce.in_progress_prints>0)&&r.jsx(Ct,{children:r.jsxs(At,{className:"p-4",children:[r.jsxs("div",{className:"flex items-center justify-between mb-3",children:[r.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[r.jsx(qF,{className:"w-5 h-5"}),n("projectDetail.queue.title")]}),r.jsx(Is,{to:`/queue?project=${g}`,className:"text-sm text-bambu-green hover:underline",children:n("projectDetail.queue.viewAll")})]}),r.jsxs("div",{className:"flex items-center gap-4 text-sm",children:[Ce.in_progress_prints>0&&r.jsx("span",{className:"text-yellow-400",children:n("projectDetail.queue.printing",{count:Ce.in_progress_prints})}),Ce.queued_prints>0&&r.jsx("span",{className:"text-bambu-gray",children:n("projectDetail.queue.queued",{count:Ce.queued_prints})})]})]})}),r.jsxs("div",{children:[r.jsx("div",{className:"flex items-center justify-between mb-4",children:r.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[r.jsx(Br,{className:"w-5 h-5"}),n("projectDetail.prints.title",{count:C?.length||0})]})}),P?r.jsx("div",{className:"flex items-center justify-center py-8",children:r.jsx(ut,{className:"w-6 h-6 animate-spin text-bambu-green"})}):r.jsx(Wat,{archives:C||[],t:n})]}),o&&r.jsx(Lce,{t:n,currencySymbol:Z,project:{...x,archive_count:Ce?.total_archives||0,total_items:Ce?.total_items||0,completed_count:Ce?.completed_prints||0,failed_count:Ce?.failed_prints||0,queue_count:Ce?.queued_prints||0,progress_percent:Ce?.progress_percent||null,archives:[]},onClose:()=>l(!1),onSave:fe=>J.mutate(fe),isLoading:J.isPending}),we.isOpen&&r.jsx(vn,{title:we.title,message:we.message,confirmText:n("common.delete"),variant:"danger",onConfirm:we.onConfirm,onCancel:()=>Ne(fe=>({...fe,isOpen:!1}))}),p&&r.jsx(wc,{mode:"reprint",libraryFileId:p.id,archiveName:p.print_name||p.filename,projectId:g,onClose:()=>f(null),onSuccess:()=>{f(null),a.invalidateQueries({queryKey:["archives"]})}}),b&&r.jsx(wc,{mode:"add-to-queue",libraryFileId:b.id,archiveName:b.print_name||b.filename,projectId:g,onClose:()=>w(null),onSuccess:()=>{w(null),a.invalidateQueries({queryKey:["queue"]})}})]})}function Xat({archiveId:t,libraryFileId:e,title:n,fileType:a,onClose:i}){const{t:s}=kt(),{data:o}=We({queryKey:["settings"],queryFn:se.getSettings}),l=o?.preferred_slicer||"bambu_studio",c=e!=null,[d,u]=v.useState(null),[m,p]=v.useState(null),[f,b]=v.useState(!0),[w,g]=v.useState(null),[x,_]=v.useState(!1),[N,C]=v.useState(null),[P,T]=v.useState(0),[A,F]=v.useState(!1),[S,M]=v.useState(null),[z,I]=v.useState(!1),[H,R]=v.useState(!1),Z=v.useRef(null),re=v.useRef(null),J=10,de=160,me=240,ue=.35;v.useEffect(()=>{const ce=le=>{le.key==="Escape"&&i()};return window.addEventListener("keydown",ce),()=>window.removeEventListener("keydown",ce)},[i]),v.useEffect(()=>{if(b(!0),c){const ce=(a||"").toLowerCase(),le=ce==="3mf"||ce==="stl",q=ce==="gcode"||ce==="3mf";p({has_model:le,has_gcode:q,has_source:!1,build_volume:{x:256,y:256,z:256},filament_colors:[]}),u(le?"3d":q?"gcode":null),b(!1);return}if(!t){p(null),u(null),b(!1);return}se.getArchiveCapabilities(t).then(ce=>{p(ce),ce.has_model?u("3d"):ce.has_gcode&&u("gcode"),b(!1)}).catch(()=>{p({has_model:!0,has_gcode:!1,has_source:!1,build_volume:{x:256,y:256,z:256},filament_colors:[]}),u("3d"),b(!1)})},[t,a,c]),v.useEffect(()=>{if(_(!0),C(null),T(0),c){const ce=(a||"").toLowerCase();if(!e||ce!=="3mf"){g(null),_(!1);return}se.getLibraryFilePlates(e).then(le=>g(le)).catch(()=>g(null)).finally(()=>_(!1));return}if(!t){g(null),_(!1);return}se.getArchivePlates(t).then(ce=>g(ce)).catch(()=>g(null)).finally(()=>_(!1))},[t,a,c,e]);const W=v.useMemo(()=>w?.plates??[],[w]),ae=(w?.is_multi_plate??!1)&&W.length>1,pe=A&&ae,ye=N==null?null:W.find(ce=>ce.index===N)??null,Te=ce=>ce.object_count??ce.objects?.length??0,$=W.reduce((ce,le)=>ce+Te(le),0),K=ye?Te(ye):$,D=ye?s("modelViewer.plateNumber",{number:ye.index}):s("modelViewer.allPlates"),j=W.length>0,B=v.useRef(null),X=v.useRef(null),[O,ie]=v.useState(10),[U,G]=v.useState(3),Y=W.length>O,Q=Math.max(1,Math.ceil(W.length/O)),oe=Y?W.slice(P*O,(P+1)*O):W;v.useEffect(()=>{if(!pe){ie(10),G(3);return}const ce=B.current,le=X.current;if(!ce||!le)return;let q=0;const L=()=>{const we=le.clientWidth,ve=Math.floor(we/210),be=Math.max(3,Math.min(5,ve||3));G(Le=>Le===be?Le:be);const Ee=window.getComputedStyle(ce),ze=Number.parseFloat(Ee.rowGap||"0"),Oe=ce.querySelector("button")?.getBoundingClientRect().height??44,Ie=le.clientHeight,rt=Math.max(1,Math.floor((Ie+ze)/(Oe+ze)))*be,st=Math.max(1,rt-1);ie(Le=>Le===st?Le:st)},ne=()=>{q&&cancelAnimationFrame(q),q=requestAnimationFrame(L)};ne();const xe=new ResizeObserver(ne);return xe.observe(le),xe.observe(ce),()=>{q&&cancelAnimationFrame(q),xe.disconnect()}},[pe,W.length]),v.useEffect(()=>{if(!Y){T(0);return}T(ce=>Math.min(ce,Q-1))},[W.length,Y,Q]),v.useEffect(()=>{if(!Y||N==null)return;const ce=W.findIndex(q=>q.index===N);if(ce<0)return;const le=Math.floor(ce/O);T(q=>q===le?q:le)},[W,O,N,Y]),v.useEffect(()=>{if(!pe){M(null),R(!1);return}if(H)return;const ce=Z.current,le=re.current;if(!ce||!le)return;const q=ce.clientHeight;if(!q)return;const L=Math.max(me,q*ue),ne=Math.max(de,q-J-L),xe=Math.min(le.scrollHeight,ne);M(Math.max(de,xe))},[pe,H,W.length,P,J,de,me,ue]),v.useEffect(()=>{if(!z)return;const ce=q=>{const L=Z.current;if(!L)return;const ne=L.getBoundingClientRect(),xe=ne.height;if(!xe)return;const we=Math.max(me,xe*ue),Ne=Math.max(de,xe-J-we),ve=Math.min(Ne,Math.max(de,q.clientY-ne.top));M(ve)},le=()=>{I(!1),R(!0)};return document.addEventListener("mousemove",ce),document.addEventListener("mouseup",le),document.body.style.cursor="row-resize",document.body.style.userSelect="none",()=>{document.removeEventListener("mousemove",ce),document.removeEventListener("mouseup",le),document.body.style.cursor="",document.body.style.userSelect=""}},[z,J,de,me,ue]);const ee=c?(a||"").toLowerCase()==="3mf":!0,ge=async()=>{if(!ee)return;const ce=n||"model";try{if(c){const{token:le}=await se.createLibrarySlicerToken(e),q=se.getLibrarySlicerDownloadUrl(e,le,ce);Am(`${window.location.origin}${q}`,l)}else{const{token:le}=await se.createArchiveSlicerToken(t),q=se.getArchiveSlicerDownloadUrl(t,le,ce);Am(`${window.location.origin}${q}`,l)}}catch{if(c){const le=`${window.location.origin}${se.getLibraryFileDownloadUrl(e)}`;Am(le,l)}else{const le=`${window.location.origin}${se.getArchiveForSlicer(t,ce)}`;Am(le,l)}}};return r.jsx("div",{className:`fixed inset-0 bg-black/70 flex items-center justify-center z-50 ${A?"p-0":"p-8"}`,onClick:i,children:r.jsxs("div",{className:`bg-bambu-dark-secondary border border-bambu-dark-tertiary w-full flex flex-col ${A?"h-full max-w-none rounded-none":"h-[80vh] max-w-4xl rounded-xl"}`,onClick:ce=>ce.stopPropagation(),children:[r.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"flex items-center gap-3 min-w-0 flex-1 mr-4",children:[r.jsx("h2",{className:"text-lg font-semibold text-white truncate",children:n}),j&&r.jsxs("span",{className:"text-xs text-bambu-gray bg-bambu-dark-tertiary/70 px-2 py-1 rounded whitespace-nowrap",children:[D,": ",s("modelViewer.objectCount",{count:K})]})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsxs(Me,{variant:"secondary",size:"sm",onClick:ge,disabled:!ee,children:[r.jsx(Rr,{className:"w-4 h-4"}),s("modelViewer.openInSlicer")]}),r.jsx(Me,{variant:"secondary",size:"sm",onClick:()=>F(ce=>!ce),title:A?"Exit fullscreen":"Enter fullscreen",children:A?r.jsx(xO,{className:"w-4 h-4"}):r.jsx(kT,{className:"w-4 h-4"})}),r.jsx(Me,{variant:"ghost",size:"sm",onClick:i,children:r.jsx(Bt,{className:"w-5 h-5"})})]})]}),m&&r.jsxs("div",{className:"flex border-b border-bambu-dark-tertiary",children:[r.jsxs("button",{onClick:()=>m.has_model&&u("3d"),disabled:!m.has_model,className:`flex items-center gap-2 px-6 py-3 text-sm font-medium transition-colors ${d==="3d"?"text-bambu-green border-b-2 border-bambu-green":m.has_model?"text-bambu-gray hover:text-white":"text-bambu-gray/30 cursor-not-allowed"}`,children:[r.jsx(Ni,{className:"w-4 h-4"}),s("modelViewer.tabs.model"),!m.has_model&&r.jsxs("span",{className:"text-xs",children:["(",s("modelViewer.notAvailable"),")"]})]}),r.jsxs("button",{onClick:()=>m.has_gcode&&u("gcode"),disabled:!m.has_gcode,className:`flex items-center gap-2 px-6 py-3 text-sm font-medium transition-colors ${d==="gcode"?"text-bambu-green border-b-2 border-bambu-green":m.has_gcode?"text-bambu-gray hover:text-white":"text-bambu-gray/30 cursor-not-allowed"}`,children:[r.jsx(hge,{className:"w-4 h-4"}),s("modelViewer.tabs.gcode"),!m.has_gcode&&r.jsxs("span",{className:"text-xs",children:["(",s("modelViewer.notSliced"),")"]})]})]}),r.jsx("div",{className:"flex-1 overflow-hidden p-4",children:f?r.jsx("div",{className:"w-full h-full flex items-center justify-center",children:r.jsx(ut,{className:"w-8 h-8 animate-spin text-bambu-green"})}):d==="3d"&&m?r.jsxs("div",{ref:Z,className:`w-full h-full flex flex-col ${pe?"gap-0 min-h-0":"gap-3"}`,children:[ae&&r.jsxs("div",{ref:re,style:pe&&S!=null?{height:S}:void 0,className:`rounded-lg border border-bambu-dark-tertiary bg-bambu-dark p-3 ${pe?"flex flex-col shrink-0":""}`,children:[r.jsxs("div",{className:"flex items-center gap-2 text-sm text-bambu-gray mb-2",children:[r.jsx(oa,{className:"w-4 h-4"}),s("modelViewer.plates"),x&&r.jsx(ut,{className:"w-3 h-3 animate-spin"})]}),r.jsxs("div",{className:pe?"flex flex-col min-h-0 flex-1":void 0,children:[r.jsx("div",{ref:X,className:pe?"min-h-0 overflow-hidden pr-1 flex-1":void 0,children:r.jsxs("div",{ref:B,className:pe?"grid gap-2":"grid grid-cols-2 md:grid-cols-3 gap-2",style:pe?{gridTemplateColumns:`repeat(${U}, minmax(0, 1fr))`}:void 0,children:[r.jsxs("button",{type:"button",onClick:()=>C(null),className:`flex items-center rounded-lg border text-left transition-colors ${pe?"gap-1.5 p-1.5 w-full":"gap-2 p-2"} ${N==null?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary bg-bambu-dark-secondary hover:border-bambu-gray"}`,children:[r.jsx("div",{className:`rounded bg-bambu-dark-tertiary flex items-center justify-center ${pe?"w-8 h-8":"w-10 h-10"}`,children:r.jsx(oa,{className:`${pe?"w-4 h-4":"w-5 h-5"} text-bambu-gray`})}),r.jsxs("div",{className:"min-w-0 flex-1",children:[r.jsx("p",{className:`${pe?"text-xs":"text-sm"} text-white font-medium truncate`,children:s("modelViewer.allPlates")}),r.jsx("p",{className:`${pe?"text-[10px]":"text-xs"} text-bambu-gray truncate`,children:s("modelViewer.plateCount",{count:W.length})})]}),N==null&&r.jsx(_r,{className:`${pe?"w-3.5 h-3.5":"w-4 h-4"} text-bambu-green flex-shrink-0`})]}),oe.map(ce=>r.jsxs("button",{type:"button",onClick:()=>C(ce.index),className:`flex items-center rounded-lg border text-left transition-colors ${pe?"gap-1.5 p-1.5 w-full":"gap-2 p-2"} ${N===ce.index?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary bg-bambu-dark-secondary hover:border-bambu-gray"}`,children:[ce.has_thumbnail&&ce.thumbnail_url?r.jsx("img",{src:ce.thumbnail_url,alt:`Plate ${ce.index}`,className:`${pe?"w-8 h-8":"w-10 h-10"} rounded object-cover bg-bambu-dark-tertiary`}):r.jsx("div",{className:`rounded bg-bambu-dark-tertiary flex items-center justify-center ${pe?"w-8 h-8":"w-10 h-10"}`,children:r.jsx(oa,{className:`${pe?"w-4 h-4":"w-5 h-5"} text-bambu-gray`})}),r.jsxs("div",{className:"min-w-0 flex-1",children:[r.jsx("p",{className:`${pe?"text-xs":"text-sm"} text-white font-medium truncate`,children:ce.name||s("modelViewer.plateNumber",{number:ce.index})}),r.jsx("p",{className:`${pe?"text-[10px]":"text-xs"} text-bambu-gray truncate`,children:s("modelViewer.objectCount",{count:ce.object_count??ce.objects?.length??0})})]}),N===ce.index&&r.jsx(_r,{className:`${pe?"w-3.5 h-3.5":"w-4 h-4"} text-bambu-green flex-shrink-0`})]},ce.index))]})}),(ye||Y)&&r.jsxs("div",{className:"mt-auto pt-3 flex items-center gap-4 text-xs text-bambu-gray overflow-x-auto",children:[ye&&r.jsxs("div",{className:"flex items-center gap-3 whitespace-nowrap",children:[r.jsx("span",{children:s("modelViewer.plateNumber",{number:ye.index})}),ye.print_time_seconds!=null&&r.jsx("span",{children:s("modelViewer.eta",{minutes:Math.round(ye.print_time_seconds/60)})}),ye.filament_used_grams!=null&&r.jsxs("span",{children:[ye.filament_used_grams.toFixed(1)," g"]}),ye.filaments.length>0&&r.jsx("span",{children:s("modelViewer.filamentCount",{count:ye.filaments.length})})]}),Y&&r.jsxs("div",{className:`flex items-center gap-2 whitespace-nowrap ${ye?"ml-auto":""}`,children:[r.jsx("span",{children:s("modelViewer.pagination.pageOf",{current:P+1,total:Q})}),r.jsxs("div",{className:"flex items-center gap-1",children:[r.jsx("button",{type:"button",onClick:()=>T(ce=>Math.max(ce-1,0)),disabled:P===0,className:`px-2 py-1 rounded border text-xs ${P===0?"border-bambu-dark-tertiary text-bambu-gray/40 cursor-not-allowed":"border-bambu-dark-tertiary text-bambu-gray hover:text-white hover:border-bambu-gray"}`,children:s("modelViewer.pagination.prev")}),(()=>{let le=Math.max(0,P-Math.floor(2.5));const q=Math.min(Q,le+5);q-le<5&&(le=Math.max(0,q-5));const L=Array.from({length:q-le},(ne,xe)=>le+xe);return r.jsxs(r.Fragment,{children:[le>0&&r.jsx("button",{type:"button",onClick:()=>T(0),className:`px-2 py-1 rounded border text-xs ${P===0?"border-bambu-green text-bambu-green":"border-bambu-dark-tertiary text-bambu-gray hover:text-white hover:border-bambu-gray"}`,children:"1"}),le>1&&r.jsx("span",{className:"px-1",children:"…"}),L.map(ne=>r.jsx("button",{type:"button",onClick:()=>T(ne),className:`px-2 py-1 rounded border text-xs ${P===ne?"border-bambu-green text-bambu-green":"border-bambu-dark-tertiary text-bambu-gray hover:text-white hover:border-bambu-gray"}`,children:ne+1},ne)),qT(Q-1),className:`px-2 py-1 rounded border text-xs ${P===Q-1?"border-bambu-green text-bambu-green":"border-bambu-dark-tertiary text-bambu-gray hover:text-white hover:border-bambu-gray"}`,children:Q})]})})(),r.jsx("button",{type:"button",onClick:()=>T(ce=>Math.min(ce+1,Q-1)),disabled:P>=Q-1,className:`px-2 py-1 rounded border text-xs ${P>=Q-1?"border-bambu-dark-tertiary text-bambu-gray/40 cursor-not-allowed":"border-bambu-dark-tertiary text-bambu-gray hover:text-white hover:border-bambu-gray"}`,children:s("modelViewer.pagination.next")})]})]})]})]})]}),pe&&r.jsx("div",{role:"separator","aria-orientation":"horizontal",onMouseDown:ce=>{ce.preventDefault(),I(!0),R(!0)},className:`h-2 cursor-row-resize flex items-center justify-center ${z?"bg-bambu-dark-tertiary":"bg-bambu-dark-secondary/60 hover:bg-bambu-dark-tertiary"}`,children:r.jsx("div",{className:"w-12 h-1 rounded-full bg-bambu-gray/50"})}),r.jsx("div",{className:`flex-1 ${pe?"min-h-0":""}`,children:r.jsx(UJ,{url:c?se.getLibraryFileDownloadUrl(e):m.has_source?se.getSource3mfDownloadUrl(t):se.getArchiveDownload(t),fileType:a,buildVolume:m.build_volume,filamentColors:m.filament_colors,selectedPlateId:N,className:"w-full h-full"})})]}):d==="gcode"&&m?r.jsx(See,{gcodeUrl:c?se.getLibraryFileGcodeUrl(e):se.getArchiveGcode(t),filamentColors:m.filament_colors,className:"w-full h-full"}):r.jsx("div",{className:"w-full h-full flex items-center justify-center text-bambu-gray",children:s("modelViewer.noPreview")})})]})})}const Qat=90;function Zat({onClose:t}){const{t:e}=kt(),n=en(),{showToast:a}=rn(),[i,s]=v.useState(Qat),[o,l]=v.useState(!0),[c,d]=v.useState(i);v.useEffect(()=>{const g=window.setTimeout(()=>d(i),300);return()=>window.clearTimeout(g)},[i]);const u=We({queryKey:["library-purge-preview",c,o],queryFn:()=>se.previewLibraryPurge(c,o),enabled:c>=1}),m=it({mutationFn:()=>se.executeLibraryPurge(i,o),onSuccess:g=>{a(e("libraryPurge.toast.success",{count:g.moved_to_trash}),"success"),n.invalidateQueries({queryKey:["library-files"]}),n.invalidateQueries({queryKey:["library-folders"]}),n.invalidateQueries({queryKey:["library-trash"]}),n.invalidateQueries({queryKey:["library-trash-count"]}),t()},onError:g=>a(g.message||e("libraryPurge.toast.failed"),"error")});v.useEffect(()=>{const g=x=>{x.key==="Escape"&&!m.isPending&&t()};return window.addEventListener("keydown",g),()=>window.removeEventListener("keydown",g)},[t,m.isPending]);const p=u.data,f=p?.count??0,b=p?.total_bytes??0,w=f>0&&!m.isPending;return r.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4",children:r.jsxs("div",{className:"bg-white dark:bg-gray-900 rounded-lg shadow-xl max-w-lg w-full",children:[r.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-gray-200 dark:border-gray-700",children:[r.jsxs("h2",{className:"text-lg font-semibold text-gray-900 dark:text-gray-100 flex items-center gap-2",children:[r.jsx(Jt,{className:"w-5 h-5"}),e("libraryPurge.title")]}),r.jsx("button",{onClick:t,className:"text-gray-400 hover:text-gray-600 dark:hover:text-gray-200","aria-label":e("common.close"),disabled:m.isPending,children:r.jsx(Bt,{className:"w-5 h-5"})})]}),r.jsxs("div",{className:"p-4 space-y-4",children:[r.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-400",children:e("libraryPurge.description")}),r.jsxs("div",{children:[r.jsx("label",{htmlFor:"purge-days",className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1",children:e("libraryPurge.ageLabel")}),r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("input",{id:"purge-days",type:"number",min:1,max:3650,value:i,onChange:g=>s(Math.max(1,Math.min(3650,parseInt(g.target.value||"0",10)||0))),className:"w-24 rounded border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-sm px-2 py-1 text-gray-900 dark:text-gray-100"}),r.jsx("span",{className:"text-sm text-gray-600 dark:text-gray-400",children:e("libraryPurge.days")})]})]}),r.jsxs("label",{className:"flex items-center gap-2 text-sm text-gray-700 dark:text-gray-300",children:[r.jsx("input",{type:"checkbox",checked:o,onChange:g=>l(g.target.checked),className:"rounded border-gray-300"}),e("libraryPurge.includeNeverPrinted")]}),r.jsxs("div",{className:"rounded border border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-800/30 p-3",children:[r.jsx("div",{className:"text-xs font-semibold uppercase tracking-wide text-gray-600 dark:text-gray-300 mb-2",children:e("libraryPurge.effectsTitle")}),r.jsxs("ul",{className:"text-xs text-gray-700 dark:text-gray-300 space-y-1 list-disc pl-4",children:[r.jsx("li",{children:e("libraryPurge.effect1")}),r.jsx("li",{children:e("libraryPurge.effect2")}),r.jsx("li",{children:e("libraryPurge.effect3")}),r.jsx("li",{children:e("libraryPurge.effect4")})]})]}),r.jsx("div",{className:"rounded border border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-800/50 p-3",children:u.isLoading||u.isFetching?r.jsxs("div",{className:"flex items-center gap-2 text-sm text-gray-500 dark:text-gray-400",children:[r.jsx(ut,{className:"w-4 h-4 animate-spin"})," ",e("libraryPurge.previewLoading")]}):u.isError?r.jsx("div",{className:"text-sm text-red-600 dark:text-red-400",children:u.error?.message??e("libraryPurge.previewFailed")}):r.jsxs("div",{className:"text-sm text-gray-900 dark:text-gray-100",children:[r.jsx("div",{className:"font-medium",children:e("libraryPurge.previewSummary",{count:f,size:cs(b)})}),p?.sample_filenames&&p.sample_filenames.length>0&&r.jsxs("ul",{className:"mt-2 text-xs text-gray-600 dark:text-gray-400 space-y-0.5 list-disc pl-4",children:[p.sample_filenames.map(g=>r.jsx("li",{className:"truncate",children:g},g)),f>p.sample_filenames.length&&r.jsx("li",{className:"list-none italic text-gray-500",children:e("libraryPurge.andMore",{count:f-p.sample_filenames.length})})]})]})}),r.jsxs("div",{className:"flex gap-2 items-start text-xs text-amber-700 dark:text-amber-400 bg-amber-50 dark:bg-amber-900/20 rounded px-3 py-2",children:[r.jsx(Nn,{className:"w-4 h-4 mt-0.5 shrink-0"}),r.jsx("span",{children:e("libraryPurge.warning")})]})]}),r.jsxs("div",{className:"flex justify-end gap-2 p-4 border-t border-gray-200 dark:border-gray-700",children:[r.jsx(Me,{variant:"secondary",onClick:t,disabled:m.isPending,children:e("common.cancel")}),r.jsx(Me,{variant:"danger",disabled:!w,onClick:()=>m.mutate(),children:m.isPending?r.jsxs(r.Fragment,{children:[r.jsx(ut,{className:"w-4 h-4 animate-spin mr-1"}),e("libraryPurge.purging")]}):e("libraryPurge.confirmCta",{count:f})})]})]})})}function Jat({parentId:t,onClose:e,onSave:n,isLoading:a,t:i}){const[s,o]=v.useState(""),l=c=>{c.preventDefault(),n({name:s.trim(),parent_id:t})};return r.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:r.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-sm border border-bambu-dark-tertiary",children:[r.jsx("div",{className:"p-4 border-b border-bambu-dark-tertiary",children:r.jsx("h2",{className:"text-lg font-semibold text-white",children:i("fileManager.newFolder")})}),r.jsxs("form",{onSubmit:l,className:"p-4 space-y-4",children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:i("fileManager.folderName")}),r.jsx("input",{type:"text",value:s,onChange:c=>o(c.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:i("fileManager.folderNamePlaceholder"),autoFocus:!0,required:!0})]}),r.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[r.jsx(Me,{type:"button",variant:"secondary",onClick:e,children:i("common.cancel")}),r.jsx(Me,{type:"submit",disabled:!s.trim()||a,children:a?r.jsx(ut,{className:"w-4 h-4 animate-spin"}):i("common.create")})]})]})]})})}function eit({onClose:t,onSave:e,isLoading:n,t:a}){const[i,s]=v.useState(""),[o,l]=v.useState(""),[c,d]=v.useState(!0),[u,m]=v.useState(!1),p=f=>{f.preventDefault(),e({name:i.trim(),external_path:o.trim(),readonly:c,show_hidden:u})};return r.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:r.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-md border border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"p-4 border-b border-bambu-dark-tertiary",children:[r.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[r.jsx(eC,{className:"w-5 h-5 text-bambu-green"}),a("fileManager.linkExternalFolder")]}),r.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:a("fileManager.linkExternalFolderDescription")})]}),r.jsxs("form",{onSubmit:p,className:"p-4 space-y-4",children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:a("fileManager.folderName")}),r.jsx("input",{type:"text",value:i,onChange:f=>s(f.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:a("fileManager.externalFolderNamePlaceholder"),autoFocus:!0,required:!0})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:a("fileManager.externalPath")}),r.jsx("input",{type:"text",value:o,onChange:f=>l(f.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green font-mono text-sm",placeholder:"/mnt/nas/3d-prints",required:!0}),r.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:a("fileManager.externalPathHelp")})]}),r.jsxs("div",{className:"space-y-2",children:[r.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[r.jsx("input",{type:"checkbox",checked:c,onChange:f=>d(f.target.checked),className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),r.jsx("span",{className:"text-sm text-white",children:a("fileManager.readOnly")}),r.jsxs("span",{className:"text-xs text-bambu-gray",children:["(",a("fileManager.readOnlyHelp"),")"]})]}),r.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[r.jsx("input",{type:"checkbox",checked:u,onChange:f=>m(f.target.checked),className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),r.jsx("span",{className:"text-sm text-white",children:a("fileManager.showHiddenFiles")})]})]}),r.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[r.jsx(Me,{type:"button",variant:"secondary",onClick:t,children:a("common.cancel")}),r.jsx(Me,{type:"submit",disabled:!i.trim()||!o.trim()||n,children:n?r.jsx(ut,{className:"w-4 h-4 animate-spin"}):a("fileManager.linkFolder")})]})]})]})})}function tit({type:t,currentName:e,onClose:n,onSave:a,isLoading:i,t:s}){const o=t==="file"?e.match(/(\.gcode\.3mf|\.3mf|\.gcode)$/i)?.[1]??"":"",l=t==="file"&&o?e.slice(0,-o.length):e,[c,d]=v.useState(l),u=m=>{m.preventDefault();const p=t==="file"?c.trim()+o:c.trim();c.trim()&&p!==e&&a(p)};return r.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:r.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-sm border border-bambu-dark-tertiary",children:[r.jsx("div",{className:"p-4 border-b border-bambu-dark-tertiary",children:r.jsx("h2",{className:"text-lg font-semibold text-white",children:s(t==="file"?"fileManager.renameFile":"fileManager.renameFolder")})}),r.jsxs("form",{onSubmit:u,className:"p-4 space-y-4",children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("common.name")}),r.jsxs("div",{className:"flex items-center bg-bambu-dark border border-bambu-dark-tertiary rounded focus-within:border-bambu-green",children:[r.jsx("input",{type:"text",value:c,onChange:m=>d(m.target.value),className:"flex-1 bg-transparent px-3 py-2 text-white placeholder-bambu-gray focus:outline-none min-w-0",autoFocus:!0,required:!0}),o&&r.jsx("span",{className:"pr-3 text-bambu-gray text-sm select-none whitespace-nowrap",children:o})]})]}),r.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[r.jsx(Me,{type:"button",variant:"secondary",onClick:n,children:s("common.cancel")}),r.jsx(Me,{type:"submit",disabled:!c.trim()||c.trim()===l||i,children:i?r.jsx(ut,{className:"w-4 h-4 animate-spin"}):s("common.rename")})]})]})]})})}function nit({folders:t,selectedFiles:e,currentFolderId:n,onClose:a,onMove:i,isLoading:s,t:o}){const[l,c]=v.useState(null),d=(m,p=0)=>{const f=[];for(const b of m)f.push({id:b.id,name:b.name,depth:p}),b.children.length>0&&f.push(...d(b.children,p+1));return f},u=[{id:null,name:o("fileManager.rootNoFolder"),depth:0},...d(t)];return r.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:r.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-sm border border-bambu-dark-tertiary",children:[r.jsx("div",{className:"p-4 border-b border-bambu-dark-tertiary",children:r.jsx("h2",{className:"text-lg font-semibold text-white",children:o("fileManager.moveFiles",{count:e.length})})}),r.jsxs("div",{className:"p-4 space-y-4",children:[r.jsx("div",{className:"max-h-64 overflow-y-auto space-y-1",children:u.map(m=>r.jsxs("button",{onClick:()=>c(m.id),disabled:m.id===n,className:`w-full text-left px-3 py-2 rounded transition-colors flex items-center gap-2 ${l===m.id?"bg-bambu-green/20 text-bambu-green":m.id===n?"opacity-50 cursor-not-allowed text-bambu-gray":"hover:bg-bambu-dark text-white"}`,style:{paddingLeft:`${12+m.depth*16}px`},children:[r.jsx(Fl,{className:"w-4 h-4"}),m.name,m.id===n&&r.jsxs("span",{className:"text-xs text-bambu-gray ml-auto",children:["(",o("fileManager.current"),")"]})]},m.id??"root"))}),r.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[r.jsx(Me,{type:"button",variant:"secondary",onClick:a,children:o("common.cancel")}),r.jsx(Me,{onClick:()=>i(l),disabled:s,children:s?r.jsx(ut,{className:"w-4 h-4 animate-spin"}):o("common.move")})]})]})]})})}function rit({folder:t,onClose:e,onLink:n,isLoading:a,t:i}){const[s,o]=v.useState("project"),[l,c]=v.useState(t.project_id||t.archive_id||null);v.useState(()=>{t.archive_id&&o("archive")});const{data:d}=We({queryKey:["projects"],queryFn:()=>se.getProjects(),select:b=>[...b].sort((w,g)=>w.name.localeCompare(g.name))}),{data:u}=We({queryKey:["archives-for-link"],queryFn:()=>se.getArchives(void 0,void 0,100)}),m=()=>{n(s==="project"?{project_id:l,archive_id:0}:{project_id:0,archive_id:l})},p=()=>{n({project_id:0,archive_id:0})},f=t.project_id||t.archive_id;return r.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:r.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-md border border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"p-4 border-b border-bambu-dark-tertiary flex items-center justify-between",children:[r.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[r.jsx(Th,{className:"w-5 h-5 text-bambu-green"}),i("fileManager.linkFolder")]}),r.jsx("button",{onClick:e,className:"p-1 hover:bg-bambu-dark rounded",children:r.jsx(Bt,{className:"w-5 h-5 text-bambu-gray"})})]}),r.jsxs("div",{className:"p-4 space-y-4",children:[r.jsx("p",{className:"text-sm text-bambu-gray",children:i("fileManager.linkFolderDescription",{name:t.name})}),r.jsxs("div",{className:"flex gap-2",children:[r.jsxs("button",{onClick:()=>{o("project"),c(null)},className:`flex-1 flex items-center justify-center gap-2 px-3 py-2 rounded-lg border transition-colors ${s==="project"?"border-bambu-green bg-bambu-green/10 text-bambu-green":"border-bambu-dark-tertiary text-bambu-gray hover:text-white"}`,children:[r.jsx(CZ,{className:"w-4 h-4"}),i("fileManager.project")]}),r.jsxs("button",{onClick:()=>{o("archive"),c(null)},className:`flex-1 flex items-center justify-center gap-2 px-3 py-2 rounded-lg border transition-colors ${s==="archive"?"border-bambu-green bg-bambu-green/10 text-bambu-green":"border-bambu-dark-tertiary text-bambu-gray hover:text-white"}`,children:[r.jsx(ro,{className:"w-4 h-4"}),i("fileManager.archive")]})]}),r.jsx("div",{className:"max-h-64 overflow-y-auto space-y-1 bg-bambu-dark rounded-lg p-2",children:s==="project"?d&&d.length>0?d.map(b=>r.jsxs("button",{onClick:()=>c(b.id),className:`w-full text-left px-3 py-2 rounded transition-colors flex items-center gap-2 ${l===b.id?"bg-bambu-green/20 text-bambu-green":"hover:bg-bambu-dark-tertiary text-white"}`,children:[r.jsx("div",{className:"w-3 h-3 rounded-full flex-shrink-0",style:{backgroundColor:b.color||"#00ae42"}}),r.jsx("span",{className:"truncate",children:b.name})]},b.id)):r.jsx("p",{className:"text-sm text-bambu-gray text-center py-4",children:i("fileManager.noProjectsFound")}):u&&u.length>0?u.map(b=>r.jsxs("button",{onClick:()=>c(b.id),className:`w-full text-left px-3 py-2 rounded transition-colors flex items-center gap-2 ${l===b.id?"bg-bambu-green/20 text-bambu-green":"hover:bg-bambu-dark-tertiary text-white"}`,children:[r.jsx(Nh,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"}),r.jsx("span",{className:"truncate",children:b.print_name||b.filename})]},b.id)):r.jsx("p",{className:"text-sm text-bambu-gray text-center py-4",children:i("fileManager.noArchivesFound")})})]}),r.jsxs("div",{className:"p-4 border-t border-bambu-dark-tertiary flex justify-between",children:[f&&r.jsxs(Me,{variant:"danger",onClick:p,disabled:a,children:[r.jsx(iu,{className:"w-4 h-4 mr-2"}),i("fileManager.unlink")]}),r.jsxs("div",{className:`flex gap-2 ${f?"":"ml-auto"}`,children:[r.jsx(Me,{variant:"secondary",onClick:e,children:i("common.cancel")}),r.jsx(Me,{onClick:m,disabled:!l||a,children:a?r.jsx(ut,{className:"w-4 h-4 animate-spin"}):i("fileManager.link")})]})]})]})})}function Rce({folder:t,selectedFolderId:e,onSelect:n,onDelete:a,onLink:i,onRename:s,depth:o=0,wrapNames:l=!1,defaultExpanded:c=!0,hasPermission:d,t:u}){const[m,p]=v.useState(c),[f,b]=v.useState(!1),w=t.children.length>0,g=t.project_id||t.archive_id,x=t.is_external;return r.jsxs("div",{children:[r.jsxs("div",{className:`group flex items-center gap-1 px-2 py-1.5 rounded cursor-pointer transition-colors ${e===t.id?"bg-bambu-green/20 text-bambu-green":"hover:bg-bambu-dark text-white"}`,style:{paddingLeft:`${8+o*12}px`},onClick:()=>n(t.id),children:[w?r.jsx("button",{onClick:_=>{_.stopPropagation(),p(!m)},className:"p-0.5 hover:bg-bambu-dark-tertiary rounded",children:r.jsx(Va,{className:`w-3.5 h-3.5 transition-transform ${m?"rotate-90":""}`})}):r.jsx("div",{className:"w-4.5"}),x?r.jsx(eC,{className:"w-4 h-4 text-purple-400 flex-shrink-0"}):r.jsx(Fl,{className:"w-4 h-4 text-bambu-green flex-shrink-0"}),r.jsx("span",{className:`text-sm flex-1 min-w-0 ${l?"break-all":"truncate"}`,title:t.name,children:t.name}),g&&r.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:[r.jsx(Th,{className:"w-3 h-3"}),t.project_name?r.jsx(CZ,{className:"w-3 h-3"}):r.jsx(ro,{className:"w-3 h-3"})]}),x&&t.external_readonly&&r.jsx("span",{title:u("fileManager.readOnly"),children:r.jsx(lc,{className:"w-3 h-3 text-amber-400 flex-shrink-0"})}),t.file_count>0&&r.jsx("span",{className:"flex-shrink-0 text-xs text-bambu-gray",children:t.file_count}),!g&&!x&&r.jsx("button",{onClick:_=>{_.stopPropagation(),i(t)},className:"flex-shrink-0 p-1 rounded hover:bg-bambu-dark-tertiary",title:u("fileManager.linkToProjectOrArchive"),children:r.jsx(Th,{className:"w-3.5 h-3.5 text-bambu-gray hover:text-bambu-green"})}),r.jsx("div",{className:`flex-shrink-0 flex items-center gap-0.5 transition-opacity ${l?"":"opacity-0 group-hover:opacity-100"}`,onClick:_=>_.stopPropagation(),children:r.jsxs("div",{className:"relative",children:[r.jsx("button",{onClick:()=>b(!f),className:"p-1 rounded hover:bg-bambu-dark-tertiary",children:r.jsx(ym,{className:"w-3.5 h-3.5 text-bambu-gray"})}),f&&r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>b(!1)}),r.jsxs("div",{className:"absolute right-0 top-full mt-1 z-20 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl py-1 min-w-[120px]",children:[r.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${d("library:update_all")?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{d("library:update_all")&&(s(t),b(!1))},disabled:!d("library:update_all"),title:d("library:update_all")?void 0:u("fileManager.noPermissionRenameFolder"),children:[r.jsx(oi,{className:"w-3.5 h-3.5"}),u("common.rename")]}),r.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${d("library:update_all")?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{d("library:update_all")&&(i(t),b(!1))},disabled:!d("library:update_all"),title:d("library:update_all")?void 0:u("fileManager.noPermissionLinkFolder"),children:[r.jsx(Th,{className:"w-3.5 h-3.5"}),u(g?"fileManager.changeLink":"fileManager.linkTo")]}),r.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${d("library:delete_all")?"text-red-400 hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{d("library:delete_all")&&(a(t.id),b(!1))},disabled:!d("library:delete_all"),title:d("library:delete_all")?void 0:u("fileManager.noPermissionDeleteFolder"),children:[r.jsx(Jt,{className:"w-3.5 h-3.5"}),u("common.delete")]})]})]})]})})]}),w&&m&&r.jsx("div",{children:t.children.map(_=>r.jsx(Rce,{folder:_,selectedFolderId:e,onSelect:n,onDelete:a,onLink:i,onRename:s,depth:o+1,wrapNames:l,defaultExpanded:c,hasPermission:d,t:u},_.id))})]})}function vw(t){const e=t.toLowerCase();return e.endsWith(".gcode")||e.endsWith(".gcode.3mf")}function Ice(t){const e=t.toLowerCase();return e.endsWith(".gcode")||e.endsWith(".gcode.3mf")?!1:e.endsWith(".stl")||e.endsWith(".3mf")||e.endsWith(".step")||e.endsWith(".stp")}function ait({file:t,isSelected:e,isMobile:n,onSelect:a,onDelete:i,onDownload:s,onAddToQueue:o,onPrint:l,onSlice:c,useSlicerApi:d,onPreview3d:u,onRename:m,onGenerateThumbnail:p,thumbnailVersion:f,hasPermission:b,canModify:w,authEnabled:g,t:x}){const[_,N]=v.useState(!1);return r.jsxs("div",{className:`group relative bg-bambu-dark-secondary rounded-lg border transition-all cursor-pointer overflow-hidden ${e?"border-bambu-green ring-1 ring-bambu-green":"border-bambu-dark-tertiary hover:border-bambu-green/50"}`,onClick:()=>a(t.id),children:[r.jsxs("div",{className:"aspect-square bg-bambu-dark flex items-center justify-center overflow-hidden",children:[t.thumbnail_path?r.jsx("img",{src:`${se.getLibraryFileThumbnailUrl(t.id)}${f?(se.getLibraryFileThumbnailUrl(t.id).includes("?")?"&":"?")+`v=${f}`:""}`,alt:t.filename,className:"w-full h-full object-cover"}):r.jsx(Nh,{className:"w-12 h-12 text-bambu-gray/30"}),r.jsx("div",{className:`absolute top-2 right-2 text-xs px-1.5 py-0.5 rounded font-medium ${t.file_type==="3mf"?"bg-bambu-green/90 text-white":t.file_type==="gcode"?"bg-blue-500/90 text-white":t.file_type==="stl"?"bg-purple-500/90 text-white":"bg-bambu-gray/90 text-white"}`,children:t.file_type.toUpperCase()})]}),r.jsxs("div",{className:"p-3",children:[r.jsx("h3",{className:"text-sm font-medium text-white truncate",title:t.print_name||t.filename,children:t.print_name||t.filename}),r.jsxs("div",{className:"flex items-center gap-3 mt-1 text-xs text-bambu-gray",children:[r.jsx("span",{children:cs(t.file_size)}),t.print_time_seconds&&r.jsxs("span",{className:"flex items-center gap-1",children:[r.jsx(Zn,{className:"w-3 h-3"}),ds(t.print_time_seconds)]})]}),t.sliced_for_model&&r.jsxs("div",{className:"mt-1 text-xs text-bambu-gray flex items-center gap-1",children:[r.jsx(pr,{className:"w-3 h-3"}),t.sliced_for_model]}),t.print_count>0&&r.jsx("div",{className:"mt-1 text-xs text-bambu-green",children:x("fileManager.printedCount",{count:t.print_count})}),g&&t.created_by_username&&r.jsxs("div",{className:"mt-1 text-xs text-bambu-gray flex items-center gap-1",children:[r.jsx(Vm,{className:"w-3 h-3"}),t.created_by_username]})]}),r.jsxs("div",{className:`absolute bottom-2 right-2 transition-opacity ${n?"opacity-100":"opacity-0 group-hover:opacity-100"}`,onClick:C=>C.stopPropagation(),children:[r.jsx("button",{onClick:()=>N(!_),className:"p-1.5 rounded bg-bambu-dark-secondary/90 hover:bg-bambu-dark-tertiary",children:r.jsx(ym,{className:"w-4 h-4 text-bambu-gray"})}),_&&r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>N(!1)}),r.jsxs("div",{className:"absolute right-0 bottom-8 z-20 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl py-1 min-w-[140px]",children:[l&&vw(t.filename)&&r.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${b("printers:control")?"text-bambu-green hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{b("printers:control")&&(l(t),N(!1))},disabled:!b("printers:control"),title:b("printers:control")?void 0:x("fileManager.noPermissionPrint"),children:[r.jsx(pr,{className:"w-3.5 h-3.5"}),x("common.print")]}),o&&vw(t.filename)&&r.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${b("queue:create")?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{b("queue:create")&&(o(t.id),N(!1))},disabled:!b("queue:create"),title:b("queue:create")?void 0:x("fileManager.noPermissionAddToQueue"),children:[r.jsx(Zn,{className:"w-3.5 h-3.5"}),x("fileManager.schedulePrint")]}),c&&d&&Ice(t.filename)&&r.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${b("library:upload")?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{b("library:upload")&&(c(t),N(!1))},disabled:!b("library:upload"),title:b("library:upload")?void 0:x("fileManager.noPermissionSlice"),children:[r.jsx(cu,{className:"w-3.5 h-3.5"}),x("slice.action")]}),u&&(t.file_type==="3mf"||t.file_type==="gcode"||t.file_type==="stl")&&r.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${b("library:read")?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{b("library:read")&&(u(t),N(!1))},disabled:!b("library:read"),title:b("library:read")?void 0:"You do not have permission to preview files",children:[r.jsx(Ni,{className:"w-3.5 h-3.5"}),"3D Preview"]}),r.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${b("library:read")?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{b("library:read")&&(s(t.id),N(!1))},disabled:!b("library:read"),title:b("library:read")?void 0:x("fileManager.noPermissionDownload"),children:[r.jsx(Yr,{className:"w-3.5 h-3.5"}),x("common.download")]}),m&&r.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${w("library","update",t.created_by_id)?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{w("library","update",t.created_by_id)&&(m(t),N(!1))},disabled:!w("library","update",t.created_by_id),title:w("library","update",t.created_by_id)?void 0:x("fileManager.noPermissionRenameFile"),children:[r.jsx(oi,{className:"w-3.5 h-3.5"}),x("common.rename")]}),p&&t.file_type==="stl"&&r.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${w("library","update",t.created_by_id)?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{w("library","update",t.created_by_id)&&(p(t),N(!1))},disabled:!w("library","update",t.created_by_id),title:w("library","update",t.created_by_id)?void 0:x("fileManager.noPermissionGenerateThumbnail"),children:[r.jsx(du,{className:"w-3.5 h-3.5"}),x("fileManager.generateThumbnail")]}),r.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${w("library","delete",t.created_by_id)?"text-red-400 hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{w("library","delete",t.created_by_id)&&(i(t.id),N(!1))},disabled:!w("library","delete",t.created_by_id),title:w("library","delete",t.created_by_id)?void 0:x("fileManager.noPermissionDeleteFile"),children:[r.jsx(Jt,{className:"w-3.5 h-3.5"}),x("common.delete")]})]})]})]}),r.jsx("div",{className:`absolute top-2 left-2 w-5 h-5 rounded border-2 flex items-center justify-center transition-all ${e?"bg-bambu-green border-bambu-green":`border-white/30 bg-black/30 ${n?"opacity-100":"opacity-0 group-hover:opacity-100"}`}`,children:e&&r.jsx("div",{className:"w-2 h-2 bg-white rounded-sm"})})]})}function iit(){const{t}=kt(),e=en(),{showToast:n}=rn(),{hasPermission:a,hasAnyPermission:i,canModify:s,authEnabled:o}=cr(),[l]=ab(),c=Di(),d=l.get("folder"),u=d?parseInt(d,10):null,[m,p]=v.useState(u),[f,b]=v.useState([]),[w,g]=v.useState(!1),[x,_]=v.useState(!1),[N,C]=v.useState(!1),[P,T]=v.useState(!1),[A,F]=v.useState(!1),[S,M]=v.useState(null),[z,I]=v.useState(null),[H,R]=v.useState(null),[Z,re]=v.useState(null),[J,de]=v.useState(null),[me,ue]=v.useState(null),[W,ae]=v.useState(null),[pe,ye]=v.useState({}),[Te,$]=v.useState(null),[K,D]=v.useState(()=>localStorage.getItem("library-view-mode")||"grid"),[j,B]=v.useState(()=>localStorage.getItem("library-wrap-folders")==="true"),[X,O]=v.useState(()=>localStorage.getItem("library-collapse-folders")==="true"),[ie,U]=v.useState(()=>{const je=localStorage.getItem("library-sidebar-width");return je?parseInt(je,10):256}),[G,Y]=v.useState(!1),Q=v.useRef(null);v.useEffect(()=>{if(!G)return;document.body.style.userSelect="none",document.body.style.cursor="col-resize";const je=Je=>{if(!Q.current)return;const Re=Q.current.parentElement?.getBoundingClientRect();if(!Re)return;const dt=Je.clientX-Re.left,he=Math.min(500,Math.max(200,dt));U(he)},Ve=()=>{Y(!1),document.body.style.userSelect="",document.body.style.cursor="",localStorage.setItem("library-sidebar-width",String(ie))};return document.addEventListener("mousemove",je),document.addEventListener("mouseup",Ve),()=>{document.removeEventListener("mousemove",je),document.removeEventListener("mouseup",Ve),document.body.style.userSelect="",document.body.style.cursor=""}},[G,ie]);const[oe,ee]=v.useState(""),[ge,ce]=v.useState("all"),[le,q]=v.useState(""),[L,ne]=v.useState(()=>localStorage.getItem("library-sort-field")||"name"),[xe,we]=v.useState(()=>localStorage.getItem("library-sort-direction")||"asc"),Ne=Qie();v.useEffect(()=>{const je=l.get("folder");if(je){const Ve=parseInt(je,10);p(Ve)}},[l]);const{data:ve}=We({queryKey:["settings"],queryFn:()=>se.getSettings()}),{data:be,isLoading:Ee}=We({queryKey:["library-folders"],queryFn:()=>se.getLibraryFolders()}),{data:ze}=We({queryKey:["library-trash-count"],queryFn:async()=>{try{return(await se.listLibraryTrash(1,0)).total}catch{return 0}},staleTime:3e4}),{data:_e,isLoading:Oe}=We({queryKey:["library-files",m],queryFn:()=>se.getLibraryFiles(m,m===null)}),{data:Ie}=We({queryKey:["library-stats"],queryFn:()=>se.getLibraryStats()}),{data:Ke}=We({queryKey:["users"],queryFn:()=>se.getUsers()}),rt=v.useMemo(()=>{if(!_e)return[];const je=new Set(_e.map(Ve=>Ve.file_type));return Array.from(je).sort()},[_e]),st=v.useMemo(()=>{if(!_e)return[];let je=[..._e];if(oe.trim()){const Ve=oe.toLowerCase();je=je.filter(Je=>Je.filename.toLowerCase().includes(Ve)||Je.print_name&&Je.print_name.toLowerCase().includes(Ve))}if(ge!=="all"&&(je=je.filter(Ve=>Ve.file_type===ge)),le.trim()){const Ve=le.toLowerCase();je=je.filter(Je=>Je.created_by_username&&Je.created_by_username.toLowerCase().includes(Ve))}return je.sort((Ve,Je)=>{let Re=0;switch(L){case"name":Re=(Ve.print_name||Ve.filename).localeCompare(Je.print_name||Je.filename);break;case"date":Re=(Xn(Ve.created_at)?.getTime()??0)-(Xn(Je.created_at)?.getTime()??0);break;case"size":Re=Ve.file_size-Je.file_size;break;case"type":Re=Ve.file_type.localeCompare(Je.file_type);break;case"prints":Re=Ve.print_count-Je.print_count;break}return xe==="asc"?Re:-Re}),je},[_e,oe,ge,le,L,xe]),Le=v.useMemo(()=>{if(!Ie||!ve)return!1;const je=(ve.library_disk_warning_gb||5)*1024*1024*1024;return Ie.disk_free_bytesse.createLibraryFolder(je),onSuccess:()=>{e.invalidateQueries({queryKey:["library-folders"]}),g(!1),n(t("fileManager.toast.folderCreated"),"success")},onError:je=>n(je.message,"error")}),Ce=it({mutationFn:async je=>{const Ve=await se.createExternalFolder(je);return await se.scanExternalFolder(Ve.id),Ve},onSuccess:je=>{e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-stats"]}),_(!1),p(je.id),n(t("fileManager.toast.externalFolderLinked"),"success")},onError:je=>n(je.message,"error")}),Xe=it({mutationFn:je=>se.scanExternalFolder(je),onSuccess:je=>{e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-stats"]}),n(t("fileManager.toast.folderScanned",{added:je.added,removed:je.removed}),"success")},onError:je=>n(je.message,"error")}),Ue=it({mutationFn:je=>se.deleteLibraryFolder(je),onSuccess:()=>{e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-stats"]}),m===z?.id&&p(null),I(null),n(t("fileManager.toast.folderDeleted"),"success")},onError:je=>{I(null),n(je.message,"error")}}),fe=it({mutationFn:je=>se.deleteLibraryFile(je),onSuccess:()=>{e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-stats"]}),e.invalidateQueries({queryKey:["library-trash-count"]}),b(je=>je.filter(Ve=>Ve!==z?.id)),I(null),n(t("fileManager.toast.fileDeleted"),"success")},onError:je=>{I(null),n(je.message,"error")}}),Ae=it({mutationFn:je=>se.bulkDeleteLibrary(je,[]),onSuccess:(je,Ve)=>{e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-stats"]}),e.invalidateQueries({queryKey:["library-trash-count"]}),n(t("fileManager.toast.filesDeleted",{count:Ve.length}),"success"),b([]),I(null)},onError:je=>{I(null),n(je.message,"error")}}),$e=it({mutationFn:({fileIds:je,folderId:Ve})=>se.moveLibraryFiles(je,Ve),onSuccess:()=>{e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-folders"]}),b([]),C(!1),n(t("fileManager.toast.filesMoved"),"success")},onError:je=>n(je.message,"error")}),Be=it({mutationFn:({id:je,data:Ve})=>se.updateLibraryFolder(je,Ve),onSuccess:(je,Ve)=>{e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["project-folders"]}),e.invalidateQueries({queryKey:["archive-folders"]}),M(null);const Je=Ve.data.project_id===0&&Ve.data.archive_id===0;n(t(Je?"fileManager.toast.folderUnlinked":"fileManager.toast.folderLinked"),"success")},onError:je=>n(je.message,"error")}),nt=it({mutationFn:({id:je,filename:Ve})=>se.updateLibraryFile(je,{filename:Ve}),onSuccess:()=>{e.invalidateQueries({queryKey:["library-files"]}),ae(null),n(t("fileManager.toast.fileRenamed"),"success")},onError:je=>{ae(null),n(je.message,"error")}}),gt=it({mutationFn:({id:je,name:Ve})=>se.updateLibraryFolder(je,{name:Ve}),onSuccess:()=>{e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-files"]}),ae(null),n(t("fileManager.toast.folderRenamed"),"success")},onError:je=>{ae(null),n(je.message,"error")}}),yt=it({mutationFn:()=>se.batchGenerateStlThumbnails({all_missing:!0}),onSuccess:je=>{if(e.invalidateQueries({queryKey:["library-files"]}),je.succeeded>0){const Ve=Date.now(),Je={};je.results.forEach(Re=>{Re.success&&(Je[Re.file_id]=Ve)}),ye(Re=>({...Re,...Je}))}je.succeeded>0&&je.failed===0?n(t("fileManager.toast.thumbnailsGenerated",{count:je.succeeded}),"success"):je.succeeded>0&&je.failed>0?n(t("fileManager.toast.thumbnailsGeneratedPartial",{succeeded:je.succeeded,failed:je.failed}),"success"):je.processed===0?n(t("fileManager.toast.noStlMissingThumbnails"),"info"):n(t("fileManager.toast.failedToGenerateThumbnails",{error:je.results[0]?.error||"Unknown error"}),"error")},onError:je=>n(je.message,"error")}),ot=it({mutationFn:je=>se.batchGenerateStlThumbnails({file_ids:[je]}),onSuccess:je=>{if(e.invalidateQueries({queryKey:["library-files"]}),je.succeeded>0){const Ve=je.results[0]?.file_id;Ve&&ye(Je=>({...Je,[Ve]:Date.now()})),n(t("fileManager.toast.thumbnailGenerated"),"success")}else n(t("fileManager.toast.failedToGenerateThumbnail",{error:je.results[0]?.error||"Unknown error"}),"error")},onError:je=>n(je.message,"error")}),Ht=v.useCallback(je=>{const Ve=je.toLowerCase();return Ve.endsWith(".gcode")||Ve.includes(".gcode.")},[]),Kt=v.useMemo(()=>_e?_e.filter(je=>f.includes(je.id)&&Ht(je.filename)):[],[_e,f,Ht]),Zt=v.useCallback(je=>{b(Ve=>Ve.includes(je)?Ve.filter(Je=>Je!==je):[...Ve,je])},[]),Yt=v.useCallback(()=>{st.length>0&&b(st.map(je=>je.id))},[st]),gn=v.useCallback(()=>{b([])},[]),cn=()=>{e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-stats"]})},pt=je=>{se.downloadLibraryFile(je).catch(Ve=>{console.error("Library file download failed:",Ve)})},at=()=>{z&&(z.type==="file"?fe.mutate(z.id):z.type==="folder"?Ue.mutate(z.id):z.type==="bulk"&&Ae.mutate(f))},vt=Ue.isPending||fe.isPending||Ae.isPending,_t=je=>{D(je),localStorage.setItem("library-view-mode",je)},Dt=Ee||Oe,De=v.useMemo(()=>{if(!m||!be)return null;const je=Ve=>{for(const Je of Ve){if(Je.id===m)return Je;const Re=je(Je.children);if(Re)return Re}return null};return je(be)},[m,be]);return r.jsxs("div",{className:"p-4 md:p-8 min-h-[calc(100vh-64px)] lg:h-[calc(100vh-64px)] flex flex-col",children:[r.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4 mb-6",children:[r.jsxs("div",{children:[r.jsxs("h1",{className:"text-2xl font-bold text-white flex items-center gap-3",children:[r.jsx(Fl,{className:"w-7 h-7 text-bambu-green"}),t("fileManager.title")]}),r.jsx("p",{className:"text-bambu-gray mt-1",children:t("fileManager.subtitle")})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsxs("div",{className:"flex items-center bg-bambu-dark rounded-lg p-1",children:[r.jsx("button",{onClick:()=>_t("grid"),className:`p-1.5 rounded transition-colors ${K==="grid"?"bg-bambu-dark-secondary text-white":"text-bambu-gray hover:text-white"}`,title:t("fileManager.gridView"),children:r.jsx(TS,{className:"w-4 h-4"})}),r.jsx("button",{onClick:()=>_t("list"),className:`p-1.5 rounded transition-colors ${K==="list"?"bg-bambu-dark-secondary text-white":"text-bambu-gray hover:text-white"}`,title:t("fileManager.listView"),children:r.jsx(AS,{className:"w-4 h-4"})})]}),r.jsxs(Me,{variant:"secondary",onClick:()=>yt.mutate(),disabled:yt.isPending||!i("library:update_own","library:update_all"),title:i("library:update_own","library:update_all")?t("fileManager.generateThumbnailsForMissing"):t("fileManager.noPermissionGenerateThumbnail"),children:[yt.isPending?r.jsx(ut,{className:"w-4 h-4 mr-2 animate-spin"}):r.jsx(du,{className:"w-4 h-4 mr-2"}),t("fileManager.generateThumbnails")]}),r.jsxs(Me,{variant:"secondary",onClick:()=>_(!0),disabled:!a("library:upload"),title:a("library:upload")?t("fileManager.linkExternalFolder"):t("fileManager.noPermissionCreateFolder"),children:[r.jsx(eC,{className:"w-4 h-4 mr-2"}),t("fileManager.linkExternal")]}),r.jsxs(Me,{variant:"secondary",onClick:()=>g(!0),disabled:!a("library:upload"),title:a("library:upload")?void 0:t("fileManager.noPermissionCreateFolder"),children:[r.jsx(mbe,{className:"w-4 h-4 mr-2"}),t("fileManager.newFolder")]}),a("library:purge")&&r.jsxs(Me,{variant:"secondary",onClick:()=>F(!0),title:t("libraryPurge.headerTooltip"),children:[r.jsx(Jt,{className:"w-4 h-4 mr-2"}),t("libraryPurge.headerButton")]}),i("library:delete_own","library:delete_all")&&r.jsxs(Is,{to:"/files/trash",className:"inline-flex items-center px-3 py-1.5 text-sm rounded bg-bambu-dark-secondary text-bambu-gray hover:text-white hover:bg-bambu-dark transition-colors",title:t("libraryTrash.headerTooltip"),children:[r.jsx(Jt,{className:"w-4 h-4 mr-2"}),t("libraryTrash.headerButton"),typeof ze=="number"&&ze>0&&r.jsx("span",{className:"ml-1.5 px-1.5 py-0.5 text-xs rounded-full bg-bambu-green/20 text-bambu-green",children:ze})]}),r.jsxs(Me,{onClick:()=>T(!0),disabled:!a("library:upload"),title:a("library:upload")?void 0:t("fileManager.noPermissionUpload"),children:[r.jsx(ka,{className:"w-4 h-4 mr-2"}),t("common.upload")]})]})]}),Le&&Ie&&ve&&r.jsxs("div",{className:"flex items-center gap-3 mb-4 p-3 bg-amber-500/10 border border-amber-500/30 rounded-lg",children:[r.jsx(Nn,{className:"w-5 h-5 text-amber-500 flex-shrink-0"}),r.jsxs("div",{className:"flex-1",children:[r.jsx("p",{className:"text-sm text-amber-500 font-medium",children:t("fileManager.lowDiskSpaceWarning")}),r.jsx("p",{className:"text-xs text-amber-500/80",children:t("fileManager.lowDiskSpaceDetails",{free:cs(Ie.disk_free_bytes),total:cs(Ie.disk_total_bytes),threshold:ve.library_disk_warning_gb})})]})]}),Ie&&r.jsxs("div",{className:"flex flex-wrap items-center gap-3 sm:gap-6 mb-6 p-3 bg-bambu-dark-secondary rounded-lg border border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[r.jsx(_T,{className:"w-4 h-4 text-bambu-green"}),r.jsxs("span",{className:"text-bambu-gray",children:[t("fileManager.files"),":"]}),r.jsx("span",{className:"text-white font-medium",children:Ie.total_files})]}),r.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[r.jsx(Fl,{className:"w-4 h-4 text-blue-400"}),r.jsxs("span",{className:"text-bambu-gray",children:[t("fileManager.folders"),":"]}),r.jsx("span",{className:"text-white font-medium",children:Ie.total_folders})]}),r.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[r.jsx(ob,{className:"w-4 h-4 text-amber-400"}),r.jsxs("span",{className:"text-bambu-gray",children:[t("fileManager.size"),":"]}),r.jsx("span",{className:"text-white font-medium",children:cs(Ie.total_size_bytes)})]}),r.jsxs("div",{className:"flex items-center gap-2 text-sm sm:ml-auto",children:[r.jsxs("span",{className:"text-bambu-gray",children:[t("fileManager.free"),":"]}),r.jsx("span",{className:`font-medium ${Le?"text-amber-500":"text-white"}`,children:cs(Ie.disk_free_bytes)})]})]}),r.jsxs("div",{className:"flex-1 flex flex-col lg:flex-row gap-4 lg:gap-6 min-h-0",children:[r.jsx("div",{className:"lg:hidden",children:r.jsxs("select",{value:m??"",onChange:je=>p(je.target.value?parseInt(je.target.value,10):null),className:"w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg px-3 py-2.5 text-white focus:outline-none focus:border-bambu-green",children:[r.jsxs("option",{value:"",children:["📁 ",t("fileManager.allFiles")]}),be&&(()=>{const je=(Ve,Je=0)=>{const Re=[];for(const dt of Ve)Re.push({id:dt.id,name:dt.name,fileCount:dt.file_count,depth:Je}),dt.children.length>0&&Re.push(...je(dt.children,Je+1));return Re};return je(be).map(Ve=>r.jsxs("option",{value:Ve.id,children:["│ ".repeat(Ve.depth),"📂 ",Ve.name," ",Ve.fileCount>0?`(${Ve.fileCount})`:""]},Ve.id))})()]})}),r.jsxs("div",{ref:Q,className:"hidden lg:flex flex-shrink-0 bg-bambu-dark-secondary rounded-lg border border-bambu-dark-tertiary overflow-hidden flex-col relative",style:{width:`${ie}px`},children:[r.jsx("div",{className:`absolute right-0 top-0 bottom-0 w-1.5 cursor-col-resize z-10 group/resize flex items-center justify-center transition-colors ${G?"bg-bambu-green":"hover:bg-bambu-green/50"}`,onMouseDown:je=>{je.preventDefault(),Y(!0)},onDoubleClick:()=>{U(256),localStorage.setItem("library-sidebar-width","256")},title:t("fileManager.dragToResizeTooltip"),children:r.jsxs("div",{className:`flex flex-col gap-1 opacity-0 group-hover/resize:opacity-100 transition-opacity ${G?"opacity-100":""}`,children:[r.jsx("div",{className:"w-0.5 h-0.5 rounded-full bg-white/70"}),r.jsx("div",{className:"w-0.5 h-0.5 rounded-full bg-white/70"}),r.jsx("div",{className:"w-0.5 h-0.5 rounded-full bg-white/70"})]})}),r.jsxs("div",{className:"p-3 border-b border-bambu-dark-tertiary flex items-center justify-between",children:[r.jsx("h2",{className:"text-sm font-medium text-white",children:t("fileManager.folders")}),r.jsxs("div",{className:"flex items-center gap-1",children:[r.jsx("button",{onClick:()=>{const je=!X;O(je),localStorage.setItem("library-collapse-folders",String(je))},className:`text-xs px-1.5 py-0.5 rounded transition-colors ${X?"bg-bambu-green/20 text-bambu-green":"text-bambu-gray hover:text-white hover:bg-bambu-dark"}`,title:t(X?"fileManager.expandFoldersByDefault":"fileManager.collapseFoldersByDefault"),children:t("fileManager.collapse")}),r.jsx("button",{onClick:()=>{const je=!j;B(je),localStorage.setItem("library-wrap-folders",String(je))},className:`text-xs px-1.5 py-0.5 rounded transition-colors ${j?"bg-bambu-green/20 text-bambu-green":"text-bambu-gray hover:text-white hover:bg-bambu-dark"}`,title:t(j?"fileManager.disableTextWrapping":"fileManager.enableTextWrapping"),children:t("fileManager.wrap")})]})]}),r.jsxs("div",{className:"flex-1 overflow-y-auto p-2",children:[r.jsxs("div",{className:`flex items-center gap-2 px-2 py-1.5 rounded cursor-pointer transition-colors ${m===null?"bg-bambu-green/20 text-bambu-green":"hover:bg-bambu-dark text-white"}`,onClick:()=>p(null),children:[r.jsx(Nh,{className:"w-4 h-4"}),r.jsx("span",{className:"text-sm",children:t("fileManager.allFiles")})]}),be?.map(je=>r.jsx(Rce,{folder:je,selectedFolderId:m,onSelect:p,onDelete:Ve=>I({type:"folder",id:Ve}),onLink:M,onRename:Ve=>ae({type:"folder",id:Ve.id,name:Ve.name}),wrapNames:j,defaultExpanded:!X,hasPermission:a,t},`${je.id}-${X?"c":"e"}`))]})]}),r.jsxs("div",{className:"flex-1 flex flex-col min-w-0 min-h-0",children:[De?.is_external&&r.jsxs("div",{className:"flex items-center gap-3 mb-4 p-3 bg-purple-500/10 border border-purple-500/30 rounded-lg",children:[r.jsx(eC,{className:"w-5 h-5 text-purple-400 flex-shrink-0"}),r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("span",{className:"text-sm font-medium text-purple-300",children:t("fileManager.externalFolder")}),De.external_readonly&&r.jsxs("span",{className:"text-xs px-1.5 py-0.5 rounded bg-amber-500/20 text-amber-400 flex items-center gap-1",children:[r.jsx(lc,{className:"w-3 h-3"}),t("fileManager.readOnly")]})]}),r.jsx("p",{className:"text-xs text-bambu-gray truncate font-mono",title:De.external_path||"",children:De.external_path})]}),r.jsxs(Me,{variant:"secondary",size:"sm",onClick:()=>m&&Xe.mutate(m),disabled:Xe.isPending,title:t("fileManager.scanFolder"),children:[Xe.isPending?r.jsx(ut,{className:"w-4 h-4 animate-spin"}):r.jsx(sr,{className:"w-4 h-4"}),r.jsx("span",{className:"ml-1.5",children:t("fileManager.scanFolder")})]})]}),_e&&_e.length>0&&r.jsxs("div",{className:"flex flex-wrap items-center gap-2 sm:gap-3 mb-4 p-2 sm:p-3 bg-bambu-dark-secondary rounded-lg border border-bambu-dark-tertiary sticky top-0 z-10 lg:static",children:[r.jsxs("div",{className:"relative w-full sm:w-auto sm:flex-1 sm:max-w-xs",children:[r.jsx(Sr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),r.jsx("input",{type:"text",placeholder:t("fileManager.searchFiles"),value:oe,onChange:je=>ee(je.target.value),className:"w-full pl-9 pr-3 py-1.5 bg-bambu-dark border border-bambu-dark-tertiary rounded text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green"})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(NS,{className:"w-4 h-4 text-bambu-gray hidden sm:block"}),r.jsxs("select",{value:ge,onChange:je=>ce(je.target.value),className:"bg-bambu-dark border border-bambu-dark-tertiary rounded px-2 py-1.5 text-sm text-white focus:outline-none focus:border-bambu-green",children:[r.jsx("option",{value:"all",children:t("fileManager.allTypes")}),rt.map(je=>r.jsx("option",{value:je,children:je.toUpperCase()},je))]})]}),o&&r.jsxs("div",{className:"relative",children:[r.jsx("input",{type:"text",placeholder:t("fileManager.filterByUser",{defaultValue:"Filter by user"}),value:le,onChange:je=>q(je.target.value),list:"usernames-list",className:`w-32 sm:w-40 px-2 py-1.5 bg-bambu-dark border border-bambu-dark-tertiary rounded text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green ${le?"pr-7":""}`,style:le?{WebkitAppearance:"none",MozAppearance:"textfield"}:void 0}),le&&r.jsx("button",{onClick:()=>q(""),className:"absolute right-2 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white z-10",children:r.jsx(Bt,{className:"w-3 h-3"})}),r.jsx("datalist",{id:"usernames-list",children:Ke?.map(je=>r.jsx("option",{value:je.username},je.id))})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsxs("select",{value:L,onChange:je=>{const Ve=je.target.value;ne(Ve),localStorage.setItem("library-sort-field",Ve)},className:"bg-bambu-dark border border-bambu-dark-tertiary rounded px-2 py-1.5 text-sm text-white focus:outline-none focus:border-bambu-green",children:[r.jsx("option",{value:"name",children:t("common.name")}),r.jsx("option",{value:"date",children:t("common.date")}),r.jsx("option",{value:"size",children:t("fileManager.size")}),r.jsx("option",{value:"type",children:t("common.type")}),r.jsx("option",{value:"prints",children:t("fileManager.prints")})]}),r.jsx("button",{onClick:()=>we(je=>{const Ve=je==="asc"?"desc":"asc";return localStorage.setItem("library-sort-direction",Ve),Ve}),className:"p-1.5 rounded bg-bambu-dark border border-bambu-dark-tertiary hover:border-bambu-green transition-colors",title:t(xe==="asc"?"fileManager.ascending":"fileManager.descending"),children:xe==="asc"?r.jsx(gfe,{className:"w-4 h-4 text-white"}):r.jsx(cfe,{className:"w-4 h-4 text-white"})})]}),(oe||ge!=="all"||le)&&r.jsx("span",{className:"text-sm text-bambu-gray hidden sm:inline",children:t("fileManager.resultsCount",{showing:st.length,total:_e.length})})]}),st.length>0&&r.jsxs("div",{className:"flex flex-wrap items-center gap-2 mb-4 p-2 bg-bambu-dark-secondary rounded-lg border border-bambu-dark-tertiary sticky top-[52px] z-10 lg:static",children:[f.length===st.length&&f.length>0?r.jsxs(Me,{variant:"secondary",size:"sm",onClick:gn,children:[r.jsx(so,{className:"w-4 h-4 sm:mr-1"}),r.jsx("span",{className:"hidden sm:inline",children:t("fileManager.deselectAll")})]}):r.jsxs(Me,{variant:"secondary",size:"sm",onClick:Yt,children:[r.jsx(bs,{className:"w-4 h-4 sm:mr-1"}),r.jsx("span",{className:"hidden sm:inline",children:t("fileManager.selectAll")})]}),f.length>0&&r.jsxs(r.Fragment,{children:[r.jsx("span",{className:"text-sm text-bambu-gray ml-2",children:t("fileManager.selected",{count:f.length})}),r.jsx("div",{className:"hidden sm:block flex-1"}),r.jsxs("div",{className:"w-full sm:w-auto flex flex-wrap items-center gap-2 mt-2 sm:mt-0",children:[Kt.length===1&&r.jsxs(Me,{variant:"primary",size:"sm",onClick:()=>re(Kt[0]),disabled:!a("printers:control"),title:a("printers:control")?void 0:t("fileManager.noPermissionPrint"),children:[r.jsx(fs,{className:"w-4 h-4 sm:mr-1"}),r.jsx("span",{className:"hidden sm:inline",children:t("common.print")})]}),Kt.length===1&&r.jsxs(Me,{variant:"secondary",size:"sm",onClick:()=>de(Kt[0]),disabled:!a("queue:create"),title:a("queue:create")?void 0:t("fileManager.noPermissionAddToQueue"),children:[r.jsx(Zn,{className:"w-4 h-4 sm:mr-1"}),r.jsx("span",{className:"hidden sm:inline",children:t("fileManager.schedulePrint")})]}),r.jsxs(Me,{variant:"secondary",size:"sm",onClick:()=>C(!0),disabled:!i("library:update_own","library:update_all"),title:i("library:update_own","library:update_all")?void 0:t("fileManager.noPermissionMoveFiles"),children:[r.jsx(kxe,{className:"w-4 h-4 sm:mr-1"}),r.jsx("span",{className:"hidden sm:inline",children:t("common.move")})]}),r.jsxs(Me,{variant:"danger",size:"sm",onClick:()=>{f.length===1?I({type:"file",id:f[0]}):I({type:"bulk",id:0,count:f.length})},disabled:!i("library:delete_own","library:delete_all"),title:i("library:delete_own","library:delete_all")?void 0:t("fileManager.noPermissionDeleteFiles"),children:[r.jsx(Jt,{className:"w-4 h-4 sm:mr-1"}),r.jsx("span",{className:"hidden sm:inline",children:t("common.delete")})]}),r.jsxs(Me,{variant:"secondary",size:"sm",onClick:gn,children:[r.jsx(Bt,{className:"w-4 h-4 sm:mr-1"}),r.jsx("span",{className:"hidden sm:inline",children:t("common.clear")})]})]})]})]}),Dt?r.jsx("div",{className:"flex-1 flex items-center justify-center",children:r.jsxs("div",{className:"flex flex-col items-center gap-3",children:[r.jsx(ut,{className:"w-8 h-8 animate-spin text-bambu-green"}),r.jsx("p",{className:"text-sm text-bambu-gray",children:t("fileManager.loadingFiles")})]})}):_e?.length===0?r.jsxs("div",{className:"flex-1 flex flex-col items-center justify-center",children:[r.jsx("div",{className:"p-4 bg-bambu-dark rounded-2xl mb-4",children:r.jsx(Nh,{className:"w-12 h-12 text-bambu-gray/50"})}),r.jsx("h3",{className:"text-lg font-medium text-white mb-2",children:t(m!==null?"fileManager.folderIsEmpty":"fileManager.noFilesYet")}),r.jsx("p",{className:"text-bambu-gray text-center max-w-md mb-6",children:t(m!==null?"fileManager.folderEmptyDescription":"fileManager.noFilesDescription")}),r.jsxs(Me,{onClick:()=>T(!0),disabled:!a("library:upload"),title:a("library:upload")?void 0:t("fileManager.noPermissionUpload"),children:[r.jsx(ar,{className:"w-4 h-4 mr-2"}),t("fileManager.uploadFiles")]})]}):st.length===0?r.jsxs("div",{className:"flex-1 flex flex-col items-center justify-center",children:[r.jsx("div",{className:"p-4 bg-bambu-dark rounded-2xl mb-4",children:r.jsx(Sr,{className:"w-12 h-12 text-bambu-gray/50"})}),r.jsx("h3",{className:"text-lg font-medium text-white mb-2",children:t("fileManager.noMatchingFiles")}),r.jsx("p",{className:"text-bambu-gray text-center max-w-md mb-6",children:t("fileManager.noMatchingFilesDescription")}),r.jsx(Me,{variant:"secondary",onClick:()=>{ee(""),ce("all")},children:t("fileManager.clearFilters")})]}):K==="grid"?r.jsx("div",{className:"flex-1 lg:overflow-y-auto",children:r.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 2xl:grid-cols-6 gap-4",children:st.map(je=>r.jsx(ait,{file:je,isSelected:f.includes(je.id),isMobile:Ne,t,onSelect:Zt,onDelete:Ve=>I({type:"file",id:Ve}),onDownload:pt,onAddToQueue:Ve=>{const Je=_e?.find(Re=>Re.id===Ve);Je&&de(Je)},onPrint:R,onSlice:ue,useSlicerApi:ve?.use_slicer_api??!1,onPreview3d:Ve=>{vw(Ve.filename)?c(`/gcode-viewer?library_file=${Ve.id}`):$(Ve)},onRename:Ve=>ae({type:"file",id:Ve.id,name:Ve.filename}),onGenerateThumbnail:Ve=>ot.mutate(Ve.id),thumbnailVersion:pe[je.id],hasPermission:a,canModify:s,authEnabled:o},je.id))})}):r.jsx("div",{className:"flex-1 lg:overflow-y-auto",children:r.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg border border-bambu-dark-tertiary overflow-hidden",children:[r.jsxs("div",{className:`hidden sm:grid ${o?"grid-cols-[auto_1fr_120px_100px_100px_100px_80px]":"grid-cols-[auto_1fr_100px_100px_100px_80px]"} gap-4 px-4 py-2 bg-bambu-dark-secondary border-b border-bambu-dark-tertiary text-xs text-bambu-gray font-medium`,children:[r.jsx("div",{className:"w-6"}),r.jsx("div",{children:t("common.name")}),o&&r.jsx("div",{children:t("fileManager.uploadedBy",{defaultValue:"Uploaded By"})}),r.jsx("div",{children:t("common.type")}),r.jsx("div",{children:t("fileManager.size")}),r.jsx("div",{children:t("fileManager.prints")}),r.jsx("div",{})]}),st.map(je=>r.jsxs("div",{className:`grid ${o?"grid-cols-[auto_1fr_120px_100px_100px_100px_80px]":"grid-cols-[auto_1fr_100px_100px_100px_80px]"} gap-4 px-4 py-3 items-center border-b border-bambu-dark-tertiary last:border-b-0 cursor-pointer hover:bg-bambu-dark/50 transition-colors ${f.includes(je.id)?"bg-bambu-green/10":""}`,onClick:()=>Zt(je.id),children:[r.jsx("div",{className:`w-5 h-5 rounded border-2 flex items-center justify-center ${f.includes(je.id)?"bg-bambu-green border-bambu-green":"border-bambu-gray/50"}`,children:f.includes(je.id)&&r.jsx("div",{className:"w-2 h-2 bg-white rounded-sm"})}),r.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[r.jsxs("div",{className:"relative group/thumb",children:[r.jsx("div",{className:"w-10 h-10 rounded bg-bambu-dark flex-shrink-0 overflow-hidden",children:je.thumbnail_path?r.jsx("img",{src:`${se.getLibraryFileThumbnailUrl(je.id)}${pe[je.id]?(se.getLibraryFileThumbnailUrl(je.id).includes("?")?"&":"?")+`v=${pe[je.id]}`:""}`,alt:"",className:"w-full h-full object-cover"}):r.jsx("div",{className:"w-full h-full flex items-center justify-center",children:r.jsx(Nh,{className:"w-5 h-5 text-bambu-gray/50"})})}),je.thumbnail_path&&r.jsx("div",{className:"absolute left-0 top-full mt-2 z-50 hidden group-hover/thumb:block",children:r.jsx("div",{className:"w-48 h-48 rounded-lg bg-bambu-dark-secondary border border-bambu-dark-tertiary shadow-xl overflow-hidden",children:r.jsx("img",{src:`${se.getLibraryFileThumbnailUrl(je.id)}${pe[je.id]?(se.getLibraryFileThumbnailUrl(je.id).includes("?")?"&":"?")+`v=${pe[je.id]}`:""}`,alt:je.filename,className:"w-full h-full object-contain"})})})]}),r.jsx("div",{className:"min-w-0",children:r.jsx("div",{className:"text-sm text-white truncate",children:je.print_name||je.filename})})]}),o&&r.jsx("div",{className:"text-sm text-bambu-gray flex items-center gap-1",children:je.created_by_username?r.jsxs(r.Fragment,{children:[r.jsx(Vm,{className:"w-3 h-3"}),r.jsx("span",{className:"truncate",children:je.created_by_username})]}):"-"}),r.jsx("div",{children:r.jsx("span",{className:`text-xs px-1.5 py-0.5 rounded font-medium ${je.file_type==="3mf"?"bg-bambu-green/20 text-bambu-green":je.file_type==="gcode"?"bg-blue-500/20 text-blue-400":je.file_type==="stl"?"bg-purple-500/20 text-purple-400":"bg-bambu-gray/20 text-bambu-gray"}`,children:je.file_type.toUpperCase()})}),r.jsx("div",{className:"text-sm text-bambu-gray",children:cs(je.file_size)}),r.jsx("div",{className:"text-sm text-bambu-gray",children:je.print_count>0?`${je.print_count}x`:"-"}),r.jsxs("div",{className:"flex items-center gap-1",onClick:Ve=>Ve.stopPropagation(),children:[vw(je.filename)&&r.jsxs(r.Fragment,{children:[r.jsx("button",{onClick:()=>a("printers:control")&&R(je),className:`p-1.5 rounded transition-colors ${a("printers:control")?"hover:bg-bambu-dark text-bambu-gray hover:text-bambu-green":"text-bambu-gray/50 cursor-not-allowed"}`,title:a("printers:control")?t("common.print"):t("fileManager.noPermissionPrint"),disabled:!a("printers:control"),children:r.jsx(pr,{className:"w-4 h-4"})}),r.jsx("button",{onClick:()=>{a("queue:create")&&de(je)},className:`p-1.5 rounded transition-colors ${a("queue:create")?"hover:bg-bambu-dark text-bambu-gray hover:text-white":"text-bambu-gray/50 cursor-not-allowed"}`,title:a("queue:create")?t("fileManager.schedulePrint"):t("fileManager.noPermissionAddToQueue"),disabled:!a("queue:create"),children:r.jsx(Zn,{className:"w-4 h-4"})})]}),(ve?.use_slicer_api??!1)&&Ice(je.filename)&&r.jsx("button",{onClick:()=>a("library:upload")&&ue(je),className:`p-1.5 rounded transition-colors ${a("library:upload")?"hover:bg-bambu-dark text-bambu-gray hover:text-bambu-green":"text-bambu-gray/50 cursor-not-allowed"}`,title:a("library:upload")?t("slice.action"):t("fileManager.noPermissionSlice"),disabled:!a("library:upload"),children:r.jsx(cu,{className:"w-4 h-4"})}),(je.file_type==="3mf"||je.file_type==="gcode"||je.file_type==="stl")&&r.jsx("button",{onClick:()=>{a("library:read")&&(vw(je.filename)?c(`/gcode-viewer?library_file=${je.id}`):$(je))},className:`p-1.5 rounded transition-colors ${a("library:read")?"hover:bg-bambu-dark text-bambu-gray hover:text-bambu-green":"text-bambu-gray/50 cursor-not-allowed"}`,title:a("library:read")?"3D Preview":"You do not have permission to preview files",disabled:!a("library:read"),children:r.jsx(Ni,{className:"w-4 h-4"})}),r.jsx("button",{onClick:()=>a("library:read")&&pt(je.id),className:`p-1.5 rounded transition-colors ${a("library:read")?"hover:bg-bambu-dark text-bambu-gray hover:text-white":"text-bambu-gray/50 cursor-not-allowed"}`,title:a("library:read")?t("common.download"):t("fileManager.noPermissionDownload"),disabled:!a("library:read"),children:r.jsx(Yr,{className:"w-4 h-4"})}),r.jsx("button",{onClick:()=>s("library","update",je.created_by_id)&&ae({type:"file",id:je.id,name:je.filename}),className:`p-1.5 rounded transition-colors ${s("library","update",je.created_by_id)?"hover:bg-bambu-dark text-bambu-gray hover:text-white":"text-bambu-gray/50 cursor-not-allowed"}`,title:s("library","update",je.created_by_id)?t("common.rename"):t("fileManager.noPermissionRenameFile"),disabled:!s("library","update",je.created_by_id),children:r.jsx(oi,{className:"w-4 h-4"})}),je.file_type==="stl"&&r.jsx("button",{onClick:()=>s("library","update",je.created_by_id)&&ot.mutate(je.id),className:`p-1.5 rounded transition-colors ${s("library","update",je.created_by_id)?"hover:bg-bambu-dark text-bambu-gray hover:text-bambu-green":"text-bambu-gray/50 cursor-not-allowed"}`,title:s("library","update",je.created_by_id)?t("fileManager.generateThumbnail"):t("fileManager.noPermissionGenerateThumbnail"),disabled:ot.isPending||!s("library","update",je.created_by_id),children:r.jsx(du,{className:"w-4 h-4"})}),r.jsx("button",{onClick:()=>s("library","delete",je.created_by_id)&&I({type:"file",id:je.id}),className:`p-1.5 rounded transition-colors ${s("library","delete",je.created_by_id)?"hover:bg-bambu-dark text-bambu-gray hover:text-red-400":"text-bambu-gray/50 cursor-not-allowed"}`,title:s("library","delete",je.created_by_id)?t("common.delete"):t("fileManager.noPermissionDeleteFile"),disabled:!s("library","delete",je.created_by_id),children:r.jsx(Jt,{className:"w-4 h-4"})})]})]},je.id))]})})]})]}),w&&r.jsx(Jat,{parentId:m,onClose:()=>g(!1),onSave:je=>tt.mutate(je),isLoading:tt.isPending,t}),x&&r.jsx(eit,{onClose:()=>_(!1),onSave:je=>Ce.mutate(je),isLoading:Ce.isPending,t}),N&&be&&r.jsx(nit,{folders:be,selectedFiles:f,currentFolderId:m,onClose:()=>C(!1),onMove:je=>$e.mutate({fileIds:f,folderId:je}),isLoading:$e.isPending,t}),P&&r.jsx(Uie,{folderId:m,onClose:()=>T(!1),onUploadComplete:cn}),A&&r.jsx(Zat,{onClose:()=>F(!1)}),S&&r.jsx(rit,{folder:S,onClose:()=>M(null),onLink:je=>Be.mutate({id:S.id,data:je}),isLoading:Be.isPending,t}),z&&r.jsx(vn,{title:z.type==="folder"?t("fileManager.deleteFolder"):z.type==="bulk"?t("fileManager.deleteFilesCount",{count:z.count}):t("fileManager.deleteFile"),message:z.type==="folder"?t("fileManager.deleteFolderConfirm"):z.type==="bulk"?t("fileManager.deleteFilesConfirm",{count:z.count}):t("fileManager.deleteFileConfirm"),confirmText:t("common.delete"),variant:"danger",isLoading:vt,loadingText:t("fileManager.deleting"),onConfirm:at,onCancel:()=>I(null)}),H&&r.jsx(wc,{mode:"reprint",libraryFileId:H.id,archiveName:H.print_name||H.filename,onClose:()=>R(null),onSuccess:()=>{R(null),e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["archives"]})}}),Z&&r.jsx(wc,{mode:"reprint",libraryFileId:Z.id,archiveName:Z.print_name||Z.filename,onClose:()=>re(null),onSuccess:()=>{re(null),b([]),e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["archives"]})}}),J&&r.jsx(wc,{mode:"add-to-queue",libraryFileId:J.id,archiveName:J.print_name||J.filename,onClose:()=>de(null),onSuccess:()=>{de(null),b([]),e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["queue"]}),e.invalidateQueries({queryKey:["archives"]})}}),me&&r.jsx(FA,{source:{kind:"libraryFile",id:me.id,filename:me.filename},onClose:()=>ue(null)}),Te&&r.jsx(Xat,{libraryFileId:Te.id,title:Te.print_name||Te.filename,fileType:Te.file_type,onClose:()=>$(null)}),W&&r.jsx(tit,{type:W.type,currentName:W.name,onClose:()=>ae(null),onSave:je=>{W.type==="file"?nt.mutate({id:W.id,filename:je}):gt.mutate({id:W.id,name:je})},isLoading:nt.isPending||gt.isPending,t})]})}function sit(t){const e=Xn(t);if(!e)return"";const n=Math.ceil((e.getTime()-Date.now())/(1e3*60*60*24));return n<=0?"any moment":n===1?"1 day":`${n} days`}function hQ(t){const e=Xn(t);return e?e.toLocaleString():t}function oit(){const{t}=kt(),e=Di(),n=en(),{showToast:a}=rn(),{hasPermission:i,authEnabled:s}=cr(),[o,l]=v.useState(null),[c,d]=v.useState(new Set),u=!s||i("library:purge"),m=We({queryKey:["library-trash"],queryFn:()=>se.listLibraryTrash(200,0)}),p=We({queryKey:["library-trash-settings"],queryFn:()=>se.getLibraryTrashSettings(),enabled:u}),[f,b]=v.useState(null);v.useEffect(()=>{p.data&&f===null&&b(p.data.retention_days)},[p.data,f]);const w=it({mutationFn:H=>{const R=p.data;return se.updateLibraryTrashSettings({retention_days:H,auto_purge_enabled:R?.auto_purge_enabled??!1,auto_purge_days:R?.auto_purge_days??90,auto_purge_include_never_printed:R?.auto_purge_include_never_printed??!0})},onSuccess:H=>{a(t("libraryTrash.toast.retentionSaved",{days:H.retention_days}),"success"),n.invalidateQueries({queryKey:["library-trash-settings"]}),n.invalidateQueries({queryKey:["library-trash"]})},onError:H=>a(H.message||t("libraryTrash.toast.retentionFailed"),"error")}),g=it({mutationFn:H=>se.restoreLibraryTrash(H),onSuccess:()=>{a(t("libraryTrash.toast.restored"),"success"),n.invalidateQueries({queryKey:["library-trash"]}),n.invalidateQueries({queryKey:["library-trash-count"]}),n.invalidateQueries({queryKey:["library-files"]}),n.invalidateQueries({queryKey:["library-folders"]})},onError:H=>a(H.message||t("libraryTrash.toast.restoreFailed"),"error")}),x=it({mutationFn:H=>se.hardDeleteLibraryTrash(H),onSuccess:()=>{a(t("libraryTrash.toast.purged"),"success"),n.invalidateQueries({queryKey:["library-trash"]}),n.invalidateQueries({queryKey:["library-trash-count"]})},onError:H=>a(H.message||t("libraryTrash.toast.purgeFailed"),"error")}),_=it({mutationFn:()=>se.emptyLibraryTrash(),onSuccess:H=>{a(t("libraryTrash.toast.emptied",{count:H.deleted}),"success"),n.invalidateQueries({queryKey:["library-trash"]}),n.invalidateQueries({queryKey:["library-trash-count"]})},onError:H=>a(H.message||t("libraryTrash.toast.emptyFailed"),"error")}),N=it({mutationFn:H=>Promise.all(H.map(R=>se.restoreLibraryTrash(R))),onSuccess:(H,R)=>{a(t("libraryTrash.toast.bulkRestored",{count:R.length}),"success"),d(new Set),n.invalidateQueries({queryKey:["library-trash"]}),n.invalidateQueries({queryKey:["library-trash-count"]}),n.invalidateQueries({queryKey:["library-files"]}),n.invalidateQueries({queryKey:["library-folders"]})},onError:H=>a(H.message||t("libraryTrash.toast.restoreFailed"),"error")}),C=it({mutationFn:H=>Promise.all(H.map(R=>se.hardDeleteLibraryTrash(R))),onSuccess:(H,R)=>{a(t("libraryTrash.toast.bulkPurged",{count:R.length}),"success"),d(new Set),n.invalidateQueries({queryKey:["library-trash"]}),n.invalidateQueries({queryKey:["library-trash-count"]})},onError:H=>a(H.message||t("libraryTrash.toast.purgeFailed"),"error")}),P=v.useMemo(()=>m.data?.items??[],[m.data?.items]),T=m.data?.retention_days??30,A=v.useMemo(()=>P.reduce((H,R)=>H+R.file_size,0),[P]),F=P.length>0&&P.every(H=>c.has(H.id)),S=c.size>0&&!F,M=H=>{d(R=>{const Z=new Set(R);return Z.has(H)?Z.delete(H):Z.add(H),Z})},z=()=>{d(H=>H.size===P.length?new Set:new Set(P.map(R=>R.id)))},I=()=>{o&&(o.type==="delete"?x.mutate(o.id):o.type==="bulkDelete"?C.mutate(Array.from(c)):_.mutate(),l(null))};return r.jsxs("div",{className:"p-6 max-w-screen-2xl mx-auto",children:[r.jsx("div",{className:"flex items-center gap-3 mb-4",children:r.jsxs(Is,{to:"/files",className:"inline-flex items-center gap-1 text-sm text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-200",children:[r.jsx(vT,{className:"w-4 h-4"})," ",t("libraryTrash.backToFiles")]})}),r.jsxs("div",{className:"flex items-start justify-between mb-6 gap-4 flex-wrap",children:[r.jsxs("div",{children:[r.jsx("h1",{className:"text-2xl font-bold text-gray-900 dark:text-gray-100",children:t("libraryTrash.title")}),r.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-400 mt-1",children:u?t("libraryTrash.subtitleAdmin",{days:T}):t("libraryTrash.subtitleUser",{days:T})})]}),P.length>0&&r.jsxs(Me,{variant:"secondary",onClick:()=>l({type:"empty"}),className:"text-red-600 dark:text-red-400",children:[r.jsx(Jt,{className:"w-4 h-4 mr-1"}),t("libraryTrash.emptyTrash")]})]}),u&&p.data&&r.jsxs("div",{className:"mb-4 border border-gray-200 dark:border-gray-700 rounded-lg p-3 flex items-center gap-3 bg-gray-50 dark:bg-gray-800/40",children:[r.jsx("label",{htmlFor:"retention-days",className:"text-sm font-medium text-gray-700 dark:text-gray-300",children:t("libraryTrash.retentionLabel")}),r.jsx("input",{id:"retention-days",type:"number",min:1,max:365,value:f??p.data.retention_days,onChange:H=>b(Math.max(1,Math.min(365,parseInt(H.target.value||"0",10)||0))),className:"w-20 rounded border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-sm px-2 py-1 text-gray-900 dark:text-gray-100"}),r.jsx("span",{className:"text-sm text-gray-600 dark:text-gray-400",children:t("libraryTrash.days")}),r.jsxs(Me,{variant:"secondary",onClick:()=>f!=null&&w.mutate(f),disabled:w.isPending||f==null||f===p.data.retention_days,className:"ml-auto",children:[r.jsx(us,{className:"w-4 h-4 mr-1"}),t("common.save")]})]}),m.isLoading?r.jsxs("div",{className:"flex items-center gap-2 text-gray-500 dark:text-gray-400",children:[r.jsx(ut,{className:"w-4 h-4 animate-spin"})," ",t("libraryTrash.loading")]}):P.length===0?r.jsx("div",{className:"border border-dashed border-gray-300 dark:border-gray-700 rounded-lg p-12 text-center",children:r.jsx("p",{className:"text-gray-500 dark:text-gray-400",children:t("libraryTrash.empty")})}):r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"flex items-center justify-between mb-2",children:[r.jsx("div",{className:"text-xs text-gray-500 dark:text-gray-400",children:t("libraryTrash.summary",{count:P.length,size:cs(A)})}),c.size>0&&r.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[r.jsx("span",{className:"text-gray-600 dark:text-gray-400",children:t("libraryTrash.selectionCount",{count:c.size})}),r.jsxs(Me,{variant:"secondary",onClick:()=>N.mutate(Array.from(c)),disabled:N.isPending,children:[r.jsx(gs,{className:"w-4 h-4 mr-1"}),t("libraryTrash.bulkRestore")]}),r.jsxs(Me,{variant:"secondary",onClick:()=>l({type:"bulkDelete",count:c.size}),disabled:C.isPending,className:"text-red-600 dark:text-red-400",children:[r.jsx(Jt,{className:"w-4 h-4 mr-1"}),t("libraryTrash.bulkPurge")]})]})]}),r.jsx("div",{className:"border border-gray-200 dark:border-gray-700 rounded-lg overflow-x-auto",children:r.jsxs("table",{className:"w-full text-sm",children:[r.jsx("thead",{className:"bg-gray-50 dark:bg-gray-800 text-left text-gray-600 dark:text-gray-300",children:r.jsxs("tr",{children:[r.jsx("th",{className:"px-3 py-2 w-10",children:r.jsx("input",{type:"checkbox",checked:F,ref:H=>{H&&(H.indeterminate=S)},onChange:z,"aria-label":t("libraryTrash.selectAll"),className:"rounded border-gray-300 cursor-pointer"})}),r.jsx("th",{className:"px-3 py-2 font-medium",children:t("libraryTrash.col.filename")}),r.jsx("th",{className:"px-3 py-2 font-medium",children:t("libraryTrash.col.folder")}),r.jsx("th",{className:"px-3 py-2 font-medium text-right",children:t("libraryTrash.col.size")}),r.jsx("th",{className:"px-3 py-2 font-medium whitespace-nowrap",children:t("libraryTrash.col.deleted")}),r.jsx("th",{className:"px-3 py-2 font-medium whitespace-nowrap",children:t("libraryTrash.col.autoPurge")}),u&&r.jsx("th",{className:"px-3 py-2 font-medium",children:t("libraryTrash.col.owner")}),r.jsx("th",{className:"px-3 py-2 font-medium text-right",children:t("libraryTrash.col.actions")})]})}),r.jsx("tbody",{className:"divide-y divide-gray-100 dark:divide-gray-800",children:P.map(H=>r.jsxs("tr",{className:"hover:bg-gray-50 dark:hover:bg-gray-800/50",children:[r.jsx("td",{className:"px-3 py-2",children:r.jsx("input",{type:"checkbox",checked:c.has(H.id),onChange:()=>M(H.id),"aria-label":t("libraryTrash.selectOne",{filename:H.filename}),className:"rounded border-gray-300 cursor-pointer"})}),r.jsx("td",{className:"px-3 py-2 text-gray-900 dark:text-gray-100 truncate max-w-md",title:H.filename,children:H.filename}),r.jsx("td",{className:"px-3 py-2 text-gray-600 dark:text-gray-400",children:H.folder_name??"—"}),r.jsx("td",{className:"px-3 py-2 text-right text-gray-600 dark:text-gray-400 tabular-nums whitespace-nowrap",children:cs(H.file_size)}),r.jsx("td",{className:"px-3 py-2 text-gray-600 dark:text-gray-400 whitespace-nowrap",children:hQ(H.deleted_at)}),r.jsx("td",{className:"px-3 py-2 text-gray-600 dark:text-gray-400 whitespace-nowrap",children:r.jsx("span",{title:hQ(H.auto_purge_at),children:t("libraryTrash.autoPurgeIn",{when:sit(H.auto_purge_at)})})}),u&&r.jsx("td",{className:"px-3 py-2 text-gray-600 dark:text-gray-400",children:H.created_by_username??"—"}),r.jsxs("td",{className:"px-3 py-2 text-right whitespace-nowrap",children:[r.jsxs("button",{onClick:()=>g.mutate(H.id),disabled:g.isPending,className:"inline-flex items-center gap-1 px-2 py-1 text-xs text-blue-600 hover:text-blue-800 dark:text-blue-400 dark:hover:text-blue-300",children:[r.jsx(gs,{className:"w-3.5 h-3.5"}),t("libraryTrash.restore")]}),r.jsxs("button",{onClick:()=>l({type:"delete",id:H.id,filename:H.filename}),disabled:x.isPending,className:"inline-flex items-center gap-1 px-2 py-1 text-xs text-red-600 hover:text-red-800 dark:text-red-400 dark:hover:text-red-300 ml-2",children:[r.jsx(Jt,{className:"w-3.5 h-3.5"}),t("libraryTrash.purgeNow")]})]})]},H.id))})]})})]}),o&&r.jsx(vn,{onCancel:()=>l(null),onConfirm:I,title:o.type==="delete"?t("libraryTrash.confirm.purgeTitle"):o.type==="bulkDelete"?t("libraryTrash.confirm.bulkPurgeTitle"):t("libraryTrash.confirm.emptyTitle"),message:o.type==="delete"?t("libraryTrash.confirm.purgeBody",{filename:o.filename}):o.type==="bulkDelete"?t("libraryTrash.confirm.bulkPurgeBody",{count:o.count}):t("libraryTrash.confirm.emptyBody",{count:P.length}),confirmText:t("libraryTrash.confirm.cta"),variant:"danger"}),m.isError&&r.jsxs("div",{className:"mt-4 text-sm text-red-600 dark:text-red-400",children:[m.error?.message??t("libraryTrash.loadError"),r.jsx(Me,{variant:"secondary",onClick:()=>e("/files"),className:"ml-3",children:t("libraryTrash.backToFiles")})]})]})}function lit(t,e){const n=`token=${encodeURIComponent(e)}`;let a=0;return t.querySelectorAll('img[src*="/api/v1/"], video[src*="/api/v1/"]').forEach(i=>{const s=i.getAttribute("src")||"";if(s.includes(n))return;const o=s.replace(/([?&])token=[^&]*(&|$)/,(c,d,u)=>u==="&"?d:""),l=o.includes("?")?"&":"?";i.src=`${o}${l}${n}`,a+=1}),a}function Oce(){const{authEnabled:t,user:e}=cr(),n=en(),a=v.useRef(!1),{data:i}=We({queryKey:["camera-stream-token",e?.id??null],queryFn:()=>se.getCameraStreamToken(),enabled:t?!!e:!0,staleTime:3e3*1e3,refetchInterval:3e3*1e3});v.useEffect(()=>{const s=i?.token??null;return m6(s),s&&lit(document,s),()=>m6(null)},[i?.token]),v.useEffect(()=>{if(!t)return;const s=o=>{const l=o.target;if(!(l instanceof HTMLImageElement||l instanceof HTMLVideoElement))return;const c=l.src||"",d=qZ();!d||!c.includes(`token=${encodeURIComponent(d)}`)||a.current||(a.current=!0,n.invalidateQueries({queryKey:["camera-stream-token"]}),setTimeout(()=>{a.current=!1},5e3))};return document.addEventListener("error",s,!0),()=>document.removeEventListener("error",s,!0)},[t,n])}const uN=5,cit=2e3,dit=3e4,uit=5e3;function mit(){const{t}=kt(),e=en(),{showToast:n}=rn(),{hasPermission:a,authEnabled:i,user:s}=cr(),{printerId:o}=_S(),l=parseInt(o||"0",10),[c]=ab(),d=parseInt(c.get("fps")||"15",10),u=Math.min(Math.max(isNaN(d)?15:d,1),30);Oce();const{data:m}=We({queryKey:["camera-stream-token",s?.id??null],queryFn:()=>se.getCameraStreamToken(),enabled:i?!!s:!0,staleTime:3e3*1e3}),p=m?.token??qZ(),[f,b]=v.useState("stream"),[w,g]=v.useState(!1),[x,_]=v.useState(!1),[N,C]=v.useState(!0),[P,T]=v.useState(Date.now()),[A,F]=v.useState(!1),[S,M]=v.useState(!1),[z,I]=v.useState(0),[H,R]=v.useState(!1),[Z,re]=v.useState(0),[J,de]=v.useState(1),[me,ue]=v.useState({x:0,y:0}),[W,ae]=v.useState(!1),[pe,ye]=v.useState({x:0,y:0}),[Te,$]=v.useState(null),[K,D]=v.useState(null),j=v.useRef(null),B=v.useRef(null),X=v.useRef(null),O=v.useRef(null),ie=v.useRef(null),{data:U}=We({queryKey:["printer",l],queryFn:()=>se.getPrinter(l),enabled:l>0}),{data:G}=We({queryKey:["printerStatus",l],queryFn:()=>se.getPrinterStatus(l),refetchInterval:3e4,enabled:l>0}),Y=it({mutationFn:Ue=>se.setChamberLight(l,Ue),onMutate:async Ue=>{await e.cancelQueries({queryKey:["printerStatus",l]});const fe=e.getQueryData(["printerStatus",l]);return e.setQueryData(["printerStatus",l],Ae=>({...Ae,chamber_light:Ue})),{previousStatus:fe}},onSuccess:(Ue,fe)=>{n(`Chamber light ${fe?"on":"off"}`)},onError:(Ue,fe,Ae)=>{Ae?.previousStatus&&e.setQueryData(["printerStatus",l],Ae.previousStatus),n(Ue.message||t("printers.toast.failedToControlChamberLight"),"error")}}),Q=(G?.state==="RUNNING"||G?.state==="PAUSE")&&(G?.printable_objects_count??0)>=2;v.useEffect(()=>(U&&(document.title=`${U.name} - Camera`),()=>{document.title="Bambuddy"}),[U]);const oe=v.useRef(!1);v.useEffect(()=>{const Ue=`/api/v1/printers/${l}/camera/stop`;oe.current=!1;const fe=()=>{if(l>0&&!oe.current){oe.current=!0;const Be={},nt=Gm();nt&&(Be.Authorization=`Bearer ${nt}`),fetch(Ue,{method:"POST",keepalive:!0,headers:Be}).catch(()=>{})}},Ae=()=>{fe()};window.addEventListener("beforeunload",Ae);const $e=j.current;return()=>{window.removeEventListener("beforeunload",Ae),$e&&($e.src=""),fe()}},[l]),v.useEffect(()=>{if(N&&!A){const fe=setTimeout(()=>{C(!1)},f==="stream"?3e3:2e4);return()=>clearTimeout(fe)}},[f,N,P,A]),v.useEffect(()=>{const Ue=()=>{const fe=!!document.fullscreenElement;M(fe),de(1),ue({x:0,y:0}),f==="stream"&&!A&&(j.current&&(j.current.src=""),setTimeout(()=>{C(!0),T(Date.now())},200))};return document.addEventListener("fullscreenchange",Ue),()=>document.removeEventListener("fullscreenchange",Ue)},[f,A]),v.useEffect(()=>{let Ue;const fe=()=>{clearTimeout(Ue),Ue=setTimeout(()=>{localStorage.setItem("cameraWindowState",JSON.stringify({width:window.outerWidth,height:window.outerHeight,left:window.screenX,top:window.screenY}))},500)};return window.addEventListener("resize",fe),()=>{clearTimeout(Ue),window.removeEventListener("resize",fe)}},[]),v.useEffect(()=>()=>{X.current&&clearTimeout(X.current),O.current&&clearInterval(O.current),ie.current&&clearInterval(ie.current)},[]);const ee=v.useCallback(()=>{if(z>=uN){R(!1),_(!0);return}const Ue=Math.min(cit*Math.pow(2,z),dit);R(!0),re(Math.ceil(Ue/1e3)),O.current=setInterval(()=>{re(fe=>fe<=1?(O.current&&clearInterval(O.current),0):fe-1)},1e3),X.current=setTimeout(()=>{I(fe=>fe+1),R(!1),C(!0),_(!1),j.current&&(j.current.src=""),T(Date.now())},Ue)},[z]);v.useEffect(()=>{if(f!=="stream"||N||H||A){ie.current&&(clearInterval(ie.current),ie.current=null);return}return ie.current=setInterval(async()=>{try{const Ue=await se.getCameraStatus(l);(Ue.stalled||!Ue.active&&!x)&&(console.log(`Stream issue detected: stalled=${Ue.stalled}, active=${Ue.active}, reconnecting...`),ie.current&&(clearInterval(ie.current),ie.current=null),C(!1),ee())}catch{}},uit),()=>{ie.current&&(clearInterval(ie.current),ie.current=null)}},[f,N,x,H,A,l,ee]);const ge=()=>{C(!1),f==="stream"&&z{if(C(!1),_(!1),I(0),R(!1),X.current&&clearTimeout(X.current),O.current&&clearInterval(O.current),j.current&&!localStorage.getItem("cameraWindowState")){const Ue=j.current,fe=Ue.naturalWidth,Ae=Ue.naturalHeight;if(fe>0&&Ae>0){const nt=window.outerWidth-window.innerWidth,gt=window.outerHeight-window.innerHeight,yt=fe+16+nt,ot=Ae+45+16+gt;try{window.resizeTo(yt,ot)}catch{}}}},le=()=>{if(l>0){const Ue={},fe=Gm();fe&&(Ue.Authorization=`Bearer ${fe}`),fetch(`/api/v1/printers/${l}/camera/stop`,{method:"POST",headers:Ue}).catch(()=>{})}},q=Ue=>{f===Ue||A||(F(!0),C(!0),_(!1),I(0),R(!1),de(1),ue({x:0,y:0}),X.current&&clearTimeout(X.current),O.current&&clearInterval(O.current),j.current&&(j.current.src=""),f==="stream"&&le(),setTimeout(()=>{b(Ue),T(Date.now()),F(!1)},100))},L=()=>{A||(F(!0),C(!0),_(!1),I(0),R(!1),X.current&&clearTimeout(X.current),O.current&&clearInterval(O.current),j.current&&(j.current.src=""),f==="stream"&&le(),setTimeout(()=>{T(Date.now()),F(!1)},100))},ne=()=>{B.current&&(document.fullscreenElement?document.exitFullscreen():B.current.requestFullscreen())},xe=()=>{de(Ue=>Math.min(Ue+.5,4))},we=()=>{de(Ue=>{const fe=Math.max(Ue-.5,1);return fe===1&&ue({x:0,y:0}),fe})},Ne=Ue=>{Ue.preventDefault(),Ue.deltaY<0?xe():we()},ve=Ue=>{J>1&&(Ue.preventDefault(),ae(!0),ye({x:Ue.clientX-me.x,y:Ue.clientY-me.y}))},be=v.useCallback(()=>{if(!B.current)return{x:300,y:200};const Ue=B.current.getBoundingClientRect(),fe=Ue.width*(J-1)/2,Ae=Ue.height*(J-1)/2;return{x:Math.max(50,fe),y:Math.max(50,Ae)}},[J]),Ee=Ue=>{if(W&&J>1){const fe=Ue.clientX-pe.x,Ae=Ue.clientY-pe.y,$e=be();ue({x:Math.max(-$e.x,Math.min($e.x,fe)),y:Math.max(-$e.y,Math.min($e.y,Ae))})}},ze=()=>{ae(!1)},_e=Ue=>{if(Ue.length<2)return 0;const fe=Ue[0].clientX-Ue[1].clientX,Ae=Ue[0].clientY-Ue[1].clientY;return Math.sqrt(fe*fe+Ae*Ae)},Oe=Ue=>Ue.length<2?{x:Ue[0].clientX,y:Ue[0].clientY}:{x:(Ue[0].clientX+Ue[1].clientX)/2,y:(Ue[0].clientY+Ue[1].clientY)/2},Ie=Ue=>{Ue.touches.length===2?(Ue.preventDefault(),$(_e(Ue.touches)),D(Oe(Ue.touches))):Ue.touches.length===1&&J>1&&(Ue.preventDefault(),ae(!0),ye({x:Ue.touches[0].clientX-me.x,y:Ue.touches[0].clientY-me.y}))},Ke=Ue=>{if(Ue.touches.length===2&&Te!==null){Ue.preventDefault();const fe=_e(Ue.touches),Ae=fe/Te;de(Be=>{const nt=Math.max(1,Math.min(4,Be*Ae));return nt===1&&ue({x:0,y:0}),nt}),$(fe);const $e=Oe(Ue.touches);if(K){const Be=be();ue(nt=>({x:Math.max(-Be.x,Math.min(Be.x,nt.x+($e.x-K.x))),y:Math.max(-Be.y,Math.min(Be.y,nt.y+($e.y-K.y)))}))}D($e)}else if(Ue.touches.length===1&&W&&J>1){Ue.preventDefault();const fe=Ue.touches[0].clientX-pe.x,Ae=Ue.touches[0].clientY-pe.y,$e=be();ue({x:Math.max(-$e.x,Math.min($e.x,fe)),y:Math.max(-$e.y,Math.min($e.y,Ae))})}},rt=Ue=>{Ue.touches.length<2&&($(null),D(null)),Ue.touches.length===0&&ae(!1)},st=()=>{de(1),ue({x:0,y:0})},Le=i&&!p,tt=Ue=>p?`${Ue}&token=${encodeURIComponent(p)}`:Ra(Ue),Ce=A||Le?"":tt(f==="stream"?`/api/v1/printers/${l}/camera/stream?fps=${u}&t=${P}`:`/api/v1/printers/${l}/camera/snapshot?t=${P}`),Xe=N||A||H;return l?r.jsxs("div",{ref:B,className:"min-h-screen bg-black flex flex-col",children:[r.jsxs("div",{className:"flex items-center justify-between px-4 py-2 bg-bambu-dark-secondary border-b border-bambu-dark-tertiary",children:[r.jsxs("h1",{className:"text-sm font-medium text-white flex items-center gap-2",children:[r.jsx(fy,{className:"w-4 h-4"}),U?.name||`Printer ${l}`]}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsxs("div",{className:"flex bg-bambu-dark rounded p-0.5",children:[r.jsx("button",{onClick:()=>q("stream"),disabled:Xe,className:`px-3 py-1 text-xs rounded transition-colors ${f==="stream"?"bg-bambu-green text-white":"text-bambu-gray hover:text-white disabled:opacity-50"}`,children:t("camera.live")}),r.jsx("button",{onClick:()=>q("snapshot"),disabled:Xe,className:`px-3 py-1 text-xs rounded transition-colors ${f==="snapshot"?"bg-bambu-green text-white":"text-bambu-gray hover:text-white disabled:opacity-50"}`,children:t("camera.snapshot")})]}),r.jsx("button",{onClick:()=>Y.mutate(!G?.chamber_light),disabled:!G?.connected||Y.isPending||!a("printers:control"),className:`p-1.5 rounded disabled:opacity-50 ${G?.chamber_light?"bg-yellow-500/20 hover:bg-yellow-500/30":"hover:bg-bambu-dark-tertiary"}`,title:a("printers:control")?t("camera.chamberLight"):t("printers.permission.noControl"),children:r.jsx(t4,{on:G?.chamber_light??!1,className:"w-4 h-4"})}),r.jsx("button",{onClick:()=>g(!0),disabled:!Q||!a("printers:control"),className:`p-1.5 rounded disabled:opacity-50 ${Q&&a("printers:control")?"hover:bg-bambu-dark-tertiary":""}`,title:a("printers:control")?t(Q?"printers.skipObjects.tooltip":"printers.skipObjects.onlyWhilePrinting"):t("printers.permission.noControl"),children:r.jsx(OT,{className:"w-4 h-4 text-bambu-gray"})}),r.jsx("button",{onClick:L,disabled:Xe,className:"p-1.5 hover:bg-bambu-dark-tertiary rounded disabled:opacity-50",title:t(f==="stream"?"camera.restartStream":"camera.refreshSnapshot"),children:r.jsx(sr,{className:`w-4 h-4 text-bambu-gray ${Xe?"animate-spin":""}`})}),r.jsx("button",{onClick:ne,className:"p-1.5 hover:bg-bambu-dark-tertiary rounded",title:t(S?"camera.exitFullscreen":"camera.fullscreen"),children:S?r.jsx(EZ,{className:"w-4 h-4 text-bambu-gray"}):r.jsx(pxe,{className:"w-4 h-4 text-bambu-gray"})})]})]}),r.jsx("div",{className:"flex-1 flex items-center justify-center p-2 overflow-hidden",onWheel:Ne,onMouseMove:Ee,onMouseUp:ze,onMouseLeave:ze,onTouchStart:Ie,onTouchMove:Ke,onTouchEnd:rt,style:{touchAction:"none"},children:r.jsxs("div",{className:"relative w-full h-full flex items-center justify-center",children:[(N||A)&&!H&&r.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/50 z-10",children:r.jsxs("div",{className:"text-center",children:[r.jsx(sr,{className:"w-8 h-8 text-bambu-gray animate-spin mx-auto mb-2"}),r.jsx("p",{className:"text-sm text-bambu-gray",children:t(f==="stream"?"camera.connectingToCamera":"camera.capturingSnapshot")})]})}),H&&r.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/80 z-10",children:r.jsxs("div",{className:"text-center p-4",children:[r.jsx(mu,{className:"w-10 h-10 text-orange-400 mx-auto mb-3"}),r.jsx("p",{className:"text-white mb-2",children:t("camera.connectionLost")}),r.jsx("p",{className:"text-sm text-bambu-gray mb-3",children:t("camera.reconnecting",{countdown:Z,attempt:Math.min(z+1,uN),max:uN})}),r.jsx("button",{onClick:L,className:"px-4 py-2 bg-bambu-green text-white text-sm rounded hover:bg-bambu-green/80 transition-colors",children:t("camera.reconnectNow")})]})}),x&&!H&&r.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black z-10",children:r.jsxs("div",{className:"text-center p-4",children:[r.jsx(Nn,{className:"w-12 h-12 text-orange-400 mx-auto mb-3"}),r.jsx("p",{className:"text-white mb-2",children:t("camera.cameraUnavailable")}),r.jsx("p",{className:"text-xs text-bambu-gray mb-4 max-w-md",children:t("camera.cameraUnavailableDesc")}),r.jsx("button",{onClick:L,className:"px-4 py-2 bg-bambu-green text-white rounded hover:bg-bambu-green/80 transition-colors",children:t("camera.retry")})]})}),r.jsx("img",{ref:j,src:Ce,alt:t("camera.cameraStream"),className:"max-w-full max-h-full object-contain select-none",style:{transform:`scale(${J}) translate(${me.x/J}px, ${me.y/J}px) rotate(${U?.camera_rotation||0}deg)`,...U?.camera_rotation===90||U?.camera_rotation===270?{maxWidth:"100vh",maxHeight:"100vw"}:{},cursor:J>1?W?"grabbing":"grab":"default"},onError:Ce?ge:void 0,onLoad:Ce?ce:void 0,onMouseDown:ve,draggable:!1},P),r.jsxs("div",{className:"absolute bottom-4 left-4 flex items-center gap-1.5 bg-black/60 rounded-lg px-2 py-1.5",children:[r.jsx("button",{onClick:we,disabled:J<=1,className:"p-1.5 hover:bg-white/10 rounded disabled:opacity-30",title:t("camera.zoomOut"),children:r.jsx(SO,{className:"w-4 h-4 text-white"})}),r.jsxs("button",{onClick:st,className:"px-2 py-1 text-sm text-white hover:bg-white/10 rounded min-w-[48px]",title:t("camera.resetZoom"),children:[Math.round(J*100),"%"]}),r.jsx("button",{onClick:xe,disabled:J>=4,className:"p-1.5 hover:bg-white/10 rounded disabled:opacity-30",title:t("camera.zoomIn"),children:r.jsx(wO,{className:"w-4 h-4 text-white"})})]})]})}),r.jsx(n4,{printerId:l,isOpen:w,onClose:()=>g(!1)})]}):r.jsx("div",{className:"min-h-screen bg-black flex items-center justify-center",children:r.jsx("p",{className:"text-white",children:t("camera.invalidPrinterId")})})}function pit(t,e,n){if(!t)return"";if(!e)return t;const a=e.match(/plate_(\d+)\.gcode/);return a&&parseInt(a[1],10)>1?`${t} — ${n("printers.plateNumber","Plate {{number}}",{number:a[1]})}`:t}function hit(t){const e=t.get("show")?.split(",")||["progress","layers","eta","filename","status"],n=parseInt(t.get("fps")||"15",10),a=Math.min(Math.max(isNaN(n)?15:n,1),30),i=t.get("camera"),s=i!=="false"&&i!=="0";return{size:t.get("size")||"medium",fps:a,showCamera:s,showProgress:e.includes("progress"),showLayers:e.includes("layers"),showEta:e.includes("eta"),showFilename:e.includes("filename"),showStatus:e.includes("status"),showPrinter:e.includes("printer")}}function fit(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 git(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 bit(){const{printerId:t}=_S(),[e]=ab(),{t:n}=kt(),a=en(),i=parseInt(t||"0",10),[s,o]=v.useState(Date.now()),l=v.useMemo(()=>hit(e),[e]),c=git(l.size),{data:d}=We({queryKey:["printer",i],queryFn:()=>se.getPrinter(i),enabled:i>0}),{data:u}=We({queryKey:["printerStatus",i],queryFn:()=>se.getPrinterStatus(i),enabled:i>0,refetchInterval:2e3}),{data:m}=We({queryKey:["settings"],queryFn:se.getSettings}),p=m?.time_format||"system";v.useEffect(()=>{if(!i)return;const _=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/api/v1/ws`,N=new WebSocket(_);return N.onmessage=C=>{try{const P=JSON.parse(C.data);P.type==="printer_status"&&P.printer_id===i&&a.setQueryData(["printerStatus",i],P.status)}catch{}},N.onerror=()=>{},()=>{N.close()}},[i,a]),v.useEffect(()=>(document.title=d?`${d.name} - ${n("streamOverlay.title")}`:n("streamOverlay.title"),()=>{document.title="Bambuddy"}),[d,n]);const f=()=>{setTimeout(()=>{o(Date.now())},3e3)};if(!i)return r.jsx("div",{className:"min-h-screen bg-black flex items-center justify-center",children:r.jsx("p",{className:"text-white",children:n("streamOverlay.invalidPrinterId")})});if(!u)return r.jsx("div",{className:"min-h-screen bg-black flex items-center justify-center",children:r.jsx("p",{className:"text-gray-400",children:n("common.loading")})});const b=u.state==="RUNNING"||u.state==="PAUSE",w=u.progress||0,g=Ra(`/api/v1/printers/${i}/camera/stream?fps=${l.fps}&t=${s}`);return r.jsxs("div",{className:"min-h-screen bg-black relative overflow-hidden",children:[l.showCamera&&r.jsx("img",{src:g,alt:n("streamOverlay.cameraStream"),className:"absolute inset-0 w-full h-full object-contain",style:d?.camera_rotation?{transform:`rotate(${d.camera_rotation}deg)`}:void 0,onError:f},s),r.jsx("a",{href:"https://github.com/maziggy/bambuddy",target:"_blank",rel:"noopener noreferrer",className:"absolute top-4 right-4 z-10",children:r.jsx("img",{src:"/img/bambuddy_logo_dark_transparent.png",alt:"Bambuddy",className:`${c.logoHeight} object-contain drop-shadow-lg hover:scale-105 transition-transform`})}),r.jsx("div",{className:"absolute bottom-0 left-0 right-0 z-10 bg-gradient-to-t from-black/80 via-black/60 to-transparent",children:r.jsxs("div",{className:`${c.container}`,children:[l.showPrinter&&d&&r.jsxs("div",{className:`flex items-center ${c.gap} mb-2`,children:[r.jsx(pr,{className:`${c.icon} text-white/70`}),r.jsx("span",{className:`${c.text} text-white font-medium`,children:d.name})]}),l.showFilename&&u.current_print&&r.jsx("div",{className:`${c.textLarge} text-white font-semibold mb-2 truncate drop-shadow-md`,children:pit(u.current_print.replace(/\.gcode\.3mf$|\.3mf$|\.gcode$/i,""),u.gcode_file,n)}),l.showStatus&&r.jsx("div",{className:`${c.text} text-white/70 mb-2`,children:fit(u,n)}),l.showProgress&&b&&r.jsxs("div",{className:"mb-3",children:[r.jsxs("div",{className:`flex items-center justify-between mb-1 ${c.text}`,children:[r.jsx("span",{className:"text-white/70",children:n("streamOverlay.progress")}),r.jsxs("span",{className:"text-white font-bold",children:[Math.round(w),"%"]})]}),r.jsx("div",{className:`w-full bg-white/20 rounded-full ${c.progressHeight}`,children:r.jsx("div",{className:`bg-bambu-green ${c.progressHeight} rounded-full transition-all duration-500`,style:{width:`${w}%`}})})]}),b&&(l.showLayers||l.showEta)&&r.jsxs("div",{className:`flex items-center ${c.gap} flex-wrap`,children:[l.showLayers&&u.layer_num!=null&&u.total_layers!=null&&u.total_layers>0&&r.jsxs("div",{className:`flex items-center ${c.gap} text-white/70`,children:[r.jsx(oa,{className:c.icon}),r.jsxs("span",{className:c.text,children:[r.jsx("span",{className:"text-white",children:u.layer_num}),r.jsx("span",{className:"mx-1",children:"/"}),r.jsx("span",{children:u.total_layers})]})]}),l.showEta&&u.remaining_time!=null&&u.remaining_time>0&&r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:`flex items-center ${c.gap} text-white/70`,children:[r.jsx(Xd,{className:c.icon}),r.jsx("span",{className:`${c.text} text-white`,children:ds(u.remaining_time*60)})]}),r.jsxs("div",{className:`flex items-center ${c.gap} text-white/70`,children:[r.jsx(Zn,{className:c.icon}),r.jsxs("span",{className:`${c.text} text-white`,children:[n("streamOverlay.eta")," ",CO(u.remaining_time,p,n)]})]})]})]}),!b&&r.jsx("div",{className:`${c.text} text-white/70 py-2`,children:u.connected?n("streamOverlay.printerIdle"):n("streamOverlay.printerOffline")})]})})]})}function xit(){const{t}=kt(),{id:e}=_S(),{mode:n}=cb(),{data:a,isLoading:i,error:s}=We({queryKey:["external-link",e],queryFn:()=>se.getExternalLink(Number(e)),enabled:!!e});return i?r.jsx("div",{className:"flex items-center justify-center h-full",children:r.jsx(ut,{className:"w-8 h-8 text-bambu-green animate-spin"})}):s||!a?r.jsxs("div",{className:"flex flex-col items-center justify-center h-full gap-4 text-bambu-gray",children:[r.jsx(Nn,{className:"w-12 h-12"}),r.jsx("p",{children:t("common.linkNotFound")})]}):r.jsx("iframe",{src:a.url,className:"h-full w-full border-0",style:{colorScheme:n},title:a.name,sandbox:"allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox"})}function fQ(){const{id:t}=_S(),e=Di(),n=en(),{t:a}=kt(),{showToast:i}=rn(),s=!!t,[o,l]=v.useState(""),[c,d]=v.useState(""),[u,m]=v.useState([]),[p,f]=v.useState(""),[b,w]=v.useState(!1),{data:g,isLoading:x}=We({queryKey:["group",t],queryFn:()=>se.getGroup(Number(t)),enabled:s}),{data:_,isLoading:N}=We({queryKey:["permissions"],queryFn:()=>se.getPermissions()});s&&g&&!b&&(l(g.name),d(g.description||""),m(g.permissions),w(!0));const C=it({mutationFn:J=>se.createGroup(J),onSuccess:()=>{n.invalidateQueries({queryKey:["groups"]}),n.invalidateQueries({queryKey:["group"]}),i(a("groups.toast.created")),e("/settings?tab=users")},onError:J=>{i(J.message,"error")}}),P=it({mutationFn:J=>se.updateGroup(Number(t),J),onSuccess:J=>{n.invalidateQueries({queryKey:["groups"]}),J&&n.setQueryData(["group",t],J),i(a("groups.toast.updated")),e("/settings?tab=users")},onError:J=>{i(J.message,"error")}}),T=C.isPending||P.isPending,A=()=>{if(!o.trim()){i(a("groups.toast.enterGroupName"),"error");return}s?P.mutate({name:o!==g?.name?o:void 0,description:c,permissions:u}):C.mutate({name:o,description:c||void 0,permissions:u})},F=J=>{m(de=>de.includes(J)?de.filter(me=>me!==J):[...de,J])},S=(J,de)=>{const me=J.permissions.map(ue=>ue.value);m(ue=>{const W=ue.filter(ae=>!me.includes(ae));return de?[...W,...me]:W})},M=J=>J.permissions.every(de=>u.includes(de.value)),z=J=>{const de=J.permissions.filter(me=>u.includes(me.value)).length;return de>0&&de{_&&m(_.all_permissions)},H=()=>{m([])},R=p.toLowerCase(),Z=v.useMemo(()=>_?R?_.categories.map(J=>({...J,permissions:J.permissions.filter(de=>de.label.toLowerCase().includes(R))})).filter(J=>J.permissions.length>0):_.categories:[],[_,R]),re=_?.all_permissions.length??0;return x||N?r.jsx("div",{className:"flex items-center justify-center py-16",children:r.jsx(ut,{className:"w-8 h-8 text-bambu-green animate-spin"})}):r.jsxs("div",{className:"space-y-6 max-w-5xl mx-auto",children:[r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("button",{onClick:()=>e("/settings?tab=users"),className:"p-2 rounded-lg hover:bg-bambu-dark-tertiary text-bambu-gray hover:text-white transition-colors",children:r.jsx(vT,{className:"w-5 h-5"})}),r.jsx("h1",{className:"text-xl font-bold text-white",children:a(s?"groups.editor.title":"groups.editor.createTitle")})]}),s&&g?.is_system&&r.jsxs("div",{className:"flex items-center gap-3 px-4 py-3 rounded-lg bg-yellow-500/10 border border-yellow-500/20 text-yellow-400 text-sm",children:[r.jsx(Nn,{className:"w-4 h-4 shrink-0"}),a("groups.form.systemGroupWarning")]}),r.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:a("groups.form.groupName")}),r.jsx("input",{type:"text",value:o,onChange:J=>l(J.target.value),disabled:s&&g?.is_system,className:"w-full px-4 py-3 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors disabled:opacity-50",placeholder:a("groups.form.groupNamePlaceholder")})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:a("groups.form.description")}),r.jsx("input",{type:"text",value:c,onChange:J=>d(J.target.value),className:"w-full px-4 py-3 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors",placeholder:a("groups.form.descriptionPlaceholder")})]})]}),r.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-3",children:[r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsxs("span",{className:"text-sm text-bambu-gray",children:[a("groups.editor.permissionsSelected",{count:u.length})," / ",re]}),r.jsx(Me,{size:"sm",variant:"ghost",onClick:I,children:a("groups.editor.selectAll")}),r.jsx(Me,{size:"sm",variant:"ghost",onClick:H,children:a("groups.editor.clearAll")})]}),r.jsxs("div",{className:"relative",children:[r.jsx(Sr,{className:"w-4 h-4 absolute left-3 top-1/2 -translate-y-1/2 text-bambu-gray"}),r.jsx("input",{type:"text",value:p,onChange:J=>f(J.target.value),placeholder:a("groups.editor.search"),className:"pl-9 pr-4 py-2 text-sm bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors w-64"})]})]}),Z.length===0?r.jsx("div",{className:"text-center py-12 text-bambu-gray",children:a("groups.editor.noResults")}):r.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:Z.map(J=>{const de=_.categories.find(pe=>pe.name===J.name),me=de.permissions.filter(pe=>u.includes(pe.value)).length,ue=de.permissions.length,W=M(de),ae=z(de);return r.jsxs(Ct,{children:[r.jsxs("div",{className:"sticky top-0 z-10 flex items-center justify-between px-4 py-3 bg-bambu-dark-secondary border-b border-bambu-dark-tertiary rounded-t-xl",children:[r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsxs("button",{type:"button",onClick:()=>S(de,!W),className:`w-5 h-5 rounded border flex items-center justify-center transition-colors shrink-0 ${W?"bg-bambu-green border-bambu-green":ae?"bg-bambu-green/50 border-bambu-green":"border-bambu-gray hover:border-white"}`,children:[W&&r.jsx(_r,{className:"w-3 h-3 text-white"}),ae&&!W&&r.jsx(tC,{className:"w-3 h-3 text-white"})]}),r.jsx(Sl,{className:"w-4 h-4 text-bambu-gray shrink-0"}),r.jsx("span",{className:"text-white font-medium text-sm",children:J.name})]}),r.jsxs("span",{className:"text-xs text-bambu-gray tabular-nums",children:[me,"/",ue]})]}),r.jsx("div",{className:"p-3 space-y-1",children:J.permissions.map(pe=>r.jsxs("label",{className:"flex items-center gap-3 px-2 py-1.5 rounded hover:bg-bambu-dark-secondary cursor-pointer",children:[r.jsx("input",{type:"checkbox",checked:u.includes(pe.value),onChange:()=>F(pe.value),className:"w-4 h-4 rounded border-bambu-gray text-bambu-green focus:ring-bambu-green focus:ring-offset-0 bg-bambu-dark-secondary"}),r.jsx("span",{className:"text-sm text-bambu-gray",children:pe.label})]},pe.value))})]},J.name)})}),r.jsx("div",{className:"h-16"}),r.jsxs("div",{className:"fixed bottom-0 left-0 right-0 z-20 px-6 py-3 bg-bambu-dark-secondary border-t border-bambu-dark-tertiary flex items-center justify-center gap-3",children:[r.jsx(Me,{variant:"secondary",onClick:()=>e("/settings?tab=users"),children:a("common.cancel")}),r.jsx(Me,{onClick:A,disabled:T||!o.trim(),children:T?r.jsxs(r.Fragment,{children:[r.jsx(ut,{className:"w-4 h-4 animate-spin"}),a("common.saving")]}):r.jsxs(r.Fragment,{children:[r.jsx(us,{className:"w-4 h-4"}),a("common.save")]})})]})]})}const yit=1.65,gQ=["#1DB954","#3B82F6","#F59E0B","#EF4444","#8B5CF6"];function ww(t,e,n){return`${t}||${e??""}||${n??""}`}function Um(t,e){const n=new Date(t);return n.setDate(n.getDate()+Math.round(e)),n}function wS(t){return t.toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})}function Sw(t){return t.toLocaleDateString(void 0,{month:"short",day:"numeric"})}function vit(t){if(t.length<2)return null;const e=[...t].sort((c,d)=>new Date(c.created_at).getTime()-new Date(d.created_at).getTime()),n=Date.now(),a=Math.LN2/30,i=[];for(let c=1;cc+d.weight,0);if(s===0)return null;const o=i.reduce((c,d)=>c+d.rate*d.weight,0)/s,l=i.reduce((c,d)=>c+d.weight*(d.rate-o)**2,0)/s;return{rate:o,stdDev:Math.sqrt(l)}}function wit(t){const e=t.reduce((s,o)=>s+o.weight_used,0);if(e===0)return null;const n=Date.now(),a=t.reduce((s,o)=>{const l=new Date(o.created_at).getTime();return lse.getAllUsageHistory(5e3),staleTime:6e4,enabled:o}),{data:A=[]}=We({queryKey:["shopping-list"],queryFn:se.getShoppingList,staleTime:3e4,enabled:o}),F=C?.forecast_global_lead_time_days??0,S=v.useMemo(()=>{const de=new Map;for(const me of P)de.set(ww(me.material,me.subtype,me.brand),me);return de},[P]),M=v.useMemo(()=>{const de=new Map;for(const me of T){const ue=de.get(me.spool_id)??[];ue.push(me),de.set(me.spool_id,ue)}return de},[T]),z=v.useMemo(()=>{const de=new Map;for(const me of t){if(me.archived_at)continue;const ue=ww(me.material,me.subtype,me.brand),W=de.get(ue)??{key:ue,material:me.material,subtype:me.subtype,brand:me.brand,spools:[]};W.spools.push(me),de.set(ue,W)}return[...de.values()]},[t]),I=v.useMemo(()=>{const de=new Date;return de.setHours(0,0,0,0),z.map(me=>{const ue=S.get(me.key)??null,W=ue?.lead_time_days??0,ae=Math.max(F,W),pe=ue?.safety_margin_value??14,ye=ue?.safety_margin_unit??"days",Te=me.spools.reduce((L,ne)=>L+Math.max(0,ne.label_weight-ne.weight_used),0),$=me.spools.reduce((L,ne)=>L+ne.label_weight,0),K=me.spools.reduce((L,ne)=>L+ne.weight_used,0),D=[];for(const L of me.spools)D.push(...M.get(L.id)??[]);let j=null,B=null,X="none";const O=vit(D);if(O!==null)j=O.rate,B=O.stdDev,X="history";else{const L=wit(me.spools);L!==null&&(j=L,X="delta")}const ie=B??(j!==null?j*.2:0),U=yit*ie*Math.sqrt(ae),G=ye==="g"?pe:j!==null?j*pe:pe*5,Y=U+G,Q=j!==null?j*ae+Y:0,oe=j&&j>0?Math.floor(Te/j):null,ee=oe!==null?Um(de,oe):null,ge=j&&j>0?Math.floor((Te-Q)/j):null,ce=ge!==null?Um(de,Math.max(0,ge)):null,le=oe!==null&&ae>0&&oe<=ae,q=!le&&ge!==null&&ge<=0;return{group:me,settings:ue,totalRemainingG:Te,totalLabelG:$,totalSpools:me.spools.length,totalUsedG:K,dailyRateG:j,dailyRateStdDev:B,rateTier:X,effectiveLeadTimeDays:ae,safetyStockG:Y,reorderPointG:Q,daysRemaining:oe,daysUntilROP:ge,projectedEmptyDate:ee,reorderTriggerDate:ce,reorderAlert:q,stockBreakAlert:le}})},[z,S,M,F]),H=v.useMemo(()=>{const de=[...I];return de.sort((me,ue)=>{let W=0,ae=0;switch(u){case"material":W=[me.group.material,me.group.subtype??"",me.group.brand??""].join(" ").toLowerCase(),ae=[ue.group.material,ue.group.subtype??"",ue.group.brand??""].join(" ").toLowerCase();break;case"used":W=me.totalUsedG,ae=ue.totalUsedG;break;case"days_left":W=me.daysRemaining??999999,ae=ue.daysRemaining??999999;break;case"stock":W=me.totalRemainingG,ae=ue.totalRemainingG;break}const pe=Wae?1:0;return p==="asc"?pe:-pe}),de},[I,u,p]),R=v.useMemo(()=>I.filter(de=>!de.settings?.alerts_snoozed&&(de.stockBreakAlert||de.reorderAlert)),[I]),Z=v.useMemo(()=>[...I].filter(de=>de.dailyRateG!==null).sort((de,me)=>me.totalUsedG-de.totalUsedG).slice(0,5),[I]);if(!o)return r.jsxs("div",{className:"flex flex-col items-center justify-center py-16 text-bambu-gray gap-3",children:[r.jsx(lc,{className:"w-8 h-8 opacity-40"}),r.jsx("p",{className:"text-sm",children:a("forecast.noReadAccess")})]});function re(de){u===de?f(me=>me==="asc"?"desc":"asc"):(m(de),f(de==="days_left"?"asc":"desc"))}const J=A.length>0?A.length:null;return r.jsxs("div",{className:"space-y-5",children:[r.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[R.length>0&&r.jsxs("button",{onClick:()=>d(de=>!de),className:`flex items-center gap-2 px-3 py-1.5 rounded-lg border text-sm font-medium transition-colors ${R.some(de=>de.stockBreakAlert)?"bg-red-500/15 border-red-500/30 text-red-300 hover:bg-red-500/25":"bg-yellow-500/15 border-yellow-500/30 text-yellow-300 hover:bg-yellow-500/25"}`,children:[r.jsx(Nn,{className:"w-4 h-4"}),a("forecast.alertCount",{count:R.length}),c?r.jsx(tl,{className:"w-3.5 h-3.5"}):r.jsx(Ln,{className:"w-3.5 h-3.5"})]}),l&&r.jsx(Pit,{value:F,onSave:de=>{se.updateSettings({forecast_global_lead_time_days:de}).then(()=>{e.invalidateQueries({queryKey:["settings"]}),n(a("forecast.globalLeadTimeSaved"),"success")})}}),r.jsxs("button",{onClick:()=>x(de=>!de),className:"relative flex items-center gap-2 px-3 py-1.5 rounded-lg border border-bambu-dark-tertiary text-bambu-gray hover:bg-bambu-dark-tertiary text-sm transition-colors ml-auto",children:[r.jsx(lb,{className:"w-4 h-4"}),r.jsx("span",{className:"hidden sm:inline",children:a("forecast.shoppingList")}),J&&r.jsx("span",{className:"absolute -top-1.5 -right-1.5 w-4 h-4 rounded-full bg-bambu-green text-white text-[10px] font-bold flex items-center justify-center",children:J})]})]}),c&&R.length>0&&r.jsx("div",{className:"space-y-2",children:R.map(de=>r.jsx(kit,{forecast:de,onCart:()=>w(de)},de.group.key))}),g&&r.jsx(Mit,{items:A,forecasts:I,globalLeadTime:F,canWrite:l,onClose:()=>x(!1),onRemove:de=>{se.removeFromShoppingList(de).then(()=>e.invalidateQueries({queryKey:["shopping-list"]})).catch(()=>n(a("forecast.failedSaveSettings"),"error"))},onClear:()=>{se.clearShoppingList().then(()=>e.invalidateQueries({queryKey:["shopping-list"]})).catch(()=>n(a("forecast.failedSaveSettings"),"error"))}}),Z.length>0&&r.jsx(Cit,{forecasts:Z,days:_,onDaysChange:N}),I.length===0?r.jsxs("div",{className:"flex flex-col items-center justify-center py-16 text-bambu-gray",children:[r.jsx(LS,{className:"w-10 h-10 mb-3 opacity-40"}),r.jsx("p",{className:"text-sm",children:a("forecast.noSpools")})]}):r.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg overflow-hidden border border-bambu-dark-tertiary",children:[r.jsx("div",{className:"overflow-x-auto",children:r.jsxs("table",{className:"w-full",children:[r.jsx("thead",{children:r.jsxs("tr",{className:"border-b border-bambu-dark-tertiary bg-bambu-dark-tertiary/30",children:[r.jsx("th",{className:"w-8 px-4 py-3"}),r.jsx(mN,{col:"material",active:u,dir:p,onSort:re,children:a("forecast.sku")}),r.jsx(mN,{col:"stock",active:u,dir:p,onSort:re,children:a("forecast.stock")}),r.jsx(mN,{col:"used",active:u,dir:p,onSort:re,children:a("forecast.dailyRate")}),r.jsx(mN,{col:"days_left",active:u,dir:p,onSort:re,children:a("forecast.daysLeft")}),r.jsx("th",{className:"px-4 py-3 text-left text-xs font-medium text-bambu-gray uppercase tracking-wide",children:a("forecast.emptyBy")}),r.jsx("th",{className:"px-4 py-3 text-left text-xs font-medium text-bambu-gray uppercase tracking-wide",children:a("forecast.reorderBy")}),r.jsx("th",{className:"w-24 px-4 py-3"})]})}),r.jsx("tbody",{className:"divide-y divide-bambu-dark-tertiary",children:H.map(de=>r.jsx(Tit,{forecast:de,globalLeadTime:F,canWrite:l,onSaved:()=>e.invalidateQueries({queryKey:["sku-settings"]}),onCart:()=>w(de),showToast:n},de.group.key))})]})}),r.jsxs("div",{className:"flex flex-wrap items-center gap-4 px-4 py-3 text-xs text-bambu-gray border-t border-bambu-dark-tertiary bg-bambu-dark-tertiary/20",children:[r.jsxs("span",{className:"flex items-center gap-1.5",children:[r.jsx("span",{className:"w-2 h-2 rounded-full bg-bambu-green inline-block"}),a("forecast.trendLegend")]}),r.jsxs("span",{className:"flex items-center gap-1.5",children:[r.jsx("span",{className:"w-2 h-2 rounded-full bg-blue-400 inline-block"}),a("forecast.estimatedLegend")]}),r.jsxs("span",{className:"flex items-center gap-1.5",children:[r.jsx("span",{className:"w-2 h-2 rounded-full bg-bambu-gray/40 inline-block"}),a("forecast.noDataLegend")]})]})]}),b&&r.jsx(Dit,{forecast:b,onClose:()=>w(null),onAdd:de=>{se.addToShoppingList(de).then(()=>{e.invalidateQueries({queryKey:["shopping-list"]}),n(a("forecast.addedToCart"),"success"),w(null),x(!0)}).catch(()=>n(a("forecast.failedAddItem"),"error"))}})]})}function mN({col:t,active:e,dir:n,onSort:a,children:i}){const s=e===t;return r.jsx("th",{className:"px-4 py-3 text-left text-xs font-medium text-bambu-gray uppercase tracking-wide cursor-pointer select-none hover:text-white transition-colors",onClick:()=>a(t),children:r.jsxs("span",{className:"inline-flex items-center",children:[i,s?n==="asc"?r.jsx(Hm,{className:"w-3 h-3 ml-1 text-bambu-green"}):r.jsx(Bh,{className:"w-3 h-3 ml-1 text-bambu-green"}):r.jsx(wT,{className:"w-3 h-3 ml-1 opacity-40"})]})})}function kit({forecast:t,onCart:e}){const{t:n}=kt(),a=[t.group.brand,t.group.material,t.group.subtype].filter(Boolean).join(" "),i=t.stockBreakAlert;return r.jsxs("div",{className:`flex items-center gap-3 px-4 py-3 rounded-lg border text-sm ${i?"bg-red-500/10 border-red-500/30 text-red-300":"bg-yellow-500/10 border-yellow-500/30 text-yellow-300"}`,children:[r.jsx(Nn,{className:"w-4 h-4 flex-shrink-0"}),r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsx("span",{className:"font-medium",children:a}),i?r.jsxs("span",{className:"ml-2 text-xs opacity-80",children:[n("forecast.stockBreakRisk")," — ",n("forecast.stockBreakDetail",{days:t.daysRemaining,lt:t.effectiveLeadTimeDays})]}):r.jsxs("span",{className:"ml-2 text-xs opacity-80",children:[n("forecast.reorderNow")," — ",n("forecast.reorderTriggerPassed",{date:t.reorderTriggerDate?wS(t.reorderTriggerDate):"—"})]})]}),r.jsxs("button",{onClick:e,className:"flex items-center gap-1.5 px-2.5 py-1 rounded border border-current text-xs opacity-70 hover:opacity-100 transition-opacity",children:[r.jsx(lb,{className:"w-3 h-3"})," ",n("forecast.order")]})]})}const Nit=[{label:"1W",value:7},{label:"1M",value:30},{label:"6M",value:180}];function Cit({forecasts:t,days:e,onDaysChange:n}){const{t:a}=kt(),i=Array.from({length:e+1},(u,m)=>m),s=t.map((u,m)=>({key:u.group.key,label:[u.group.brand,u.group.material,u.group.subtype].filter(Boolean).join(" "),color:gQ[m%gQ.length],rop:u.reorderPointG,points:Sit(u,e)})),o=i.map(u=>{const m={day:u,label:Sw(Um(new Date,u))};for(const p of s){const f=p.points.find(b=>b.day===u);m[p.key]=f?.stock??0}return m}),l=(()=>{for(let u=e;u>=0;u--)if(s.some(m=>o[u]?.[m.key]>0))return u;return e})(),c=o.slice(0,l+1),d=s.filter(u=>u.rop>0);return r.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg overflow-hidden border border-bambu-dark-tertiary p-4",children:[r.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[r.jsx(LS,{className:"w-4 h-4 text-bambu-green"}),r.jsx("h3",{className:"text-sm font-semibold text-white",children:a("forecast.chartTitle")}),r.jsx("span",{className:"text-xs text-bambu-gray ml-1 hidden sm:inline",children:a("forecast.dashedLinesROP")}),r.jsx("div",{className:"ml-auto flex items-center bg-bambu-dark-tertiary rounded-lg p-0.5",children:Nit.map(u=>r.jsx("button",{onClick:()=>n(u.value),className:`px-2.5 py-1 text-xs font-medium rounded-md transition-colors ${e===u.value?"bg-bambu-dark-secondary text-white shadow":"text-bambu-gray hover:text-white"}`,children:u.label},u.value))})]}),r.jsx(eu,{width:"100%",height:220,children:r.jsxs(s5,{data:c,margin:{top:4,right:8,bottom:0,left:0},children:[r.jsx("defs",{children:s.map(u=>r.jsxs("linearGradient",{id:`grad-${u.key}`,x1:"0",y1:"0",x2:"0",y2:"1",children:[r.jsx("stop",{offset:"5%",stopColor:u.color,stopOpacity:.25}),r.jsx("stop",{offset:"95%",stopColor:u.color,stopOpacity:.02})]},u.key))}),r.jsx(Cm,{strokeDasharray:"3 3",stroke:"#374151",strokeOpacity:.5}),r.jsx(Pm,{dataKey:"label",tick:{fill:"#6B7280",fontSize:10},interval:Math.max(0,Math.ceil(l/8)-1),axisLine:!1,tickLine:!1}),r.jsx(Tm,{tick:{fill:"#6B7280",fontSize:10},axisLine:!1,tickLine:!1,tickFormatter:u=>u>=1e3?`${(u/1e3).toFixed(1)}kg`:`${u}g`,width:48}),r.jsx(nu,{contentStyle:{background:"#1a1a2e",border:"1px solid #374151",borderRadius:8,fontSize:12},labelStyle:{color:"#9CA3AF"},itemStyle:{color:"#E5E7EB"},formatter:(u,m)=>{if(typeof u!="number")return"";const p=s.find(f=>f.key===String(m));return`${u}g — ${p?.label??m}`}}),r.jsx(j4,{formatter:u=>{const m=s.find(p=>p.key===u);return r.jsx("span",{style:{color:"#9CA3AF",fontSize:11},children:m?.label??u})}}),s.map(u=>r.jsx(DA,{type:"monotone",dataKey:u.key,stroke:u.color,strokeWidth:2,fill:`url(#grad-${u.key})`,dot:!1,activeDot:{r:3}},u.key)),d.map(u=>r.jsx(ru,{y:u.rop,stroke:u.color,strokeDasharray:"4 3",strokeOpacity:.6},`rop-${u.key}`))]})})]})}function Pit({value:t,onSave:e}){const{t:n}=kt(),[a,i]=v.useState(!1),[s,o]=v.useState(String(t));function l(){const c=parseInt(s,10);isNaN(c)||c<0||(e(c),i(!1))}return r.jsxs("div",{className:"flex items-center gap-2 px-3 py-1.5 bg-bambu-dark-tertiary/40 rounded-lg border border-bambu-dark-tertiary text-xs text-bambu-gray",children:[r.jsx(Ci,{className:"w-3.5 h-3.5 flex-shrink-0","aria-label":n("forecast.globalLeadTimeHint")}),r.jsxs("span",{className:"hidden sm:inline",children:[n("forecast.globalLeadTime"),":"]}),a?r.jsxs("form",{className:"flex items-center gap-1.5",onSubmit:c=>{c.preventDefault(),l()},children:[r.jsx("input",{type:"number",min:0,max:365,value:s,onChange:c=>o(c.target.value),className:"w-14 px-1.5 py-0.5 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-sm text-white focus:outline-none focus:border-bambu-green",autoFocus:!0}),r.jsx("span",{className:"text-bambu-gray",children:"d"}),r.jsx("button",{type:"submit",className:"px-2 py-0.5 bg-bambu-green text-white text-xs rounded hover:bg-bambu-green/80",children:n("forecast.save")}),r.jsx("button",{type:"button",onClick:()=>i(!1),className:"text-xs text-bambu-gray hover:text-white",children:"✕"})]}):r.jsxs("div",{className:"flex items-center gap-1.5",children:[r.jsxs("span",{className:"font-semibold text-white",children:[t,"d"]}),r.jsx("button",{onClick:()=>{o(String(t)),i(!0)},className:"p-0.5 text-bambu-gray hover:text-white rounded transition-colors",children:r.jsx(fc,{className:"w-3 h-3"})})]})]})}function Tit({forecast:t,globalLeadTime:e,canWrite:n,onSaved:a,onCart:i,showToast:s}){const{t:o}=kt(),[l,c]=v.useState(!1),[d,u]=v.useState(!1),[m,p]=v.useState(!1),[f,b]=v.useState(String(t.settings?.lead_time_days??0)),[w,g]=v.useState(String(t.settings?.safety_margin_value??14)),[x,_]=v.useState(t.settings?.safety_margin_unit??"days");v.useEffect(()=>{d||b(String(t.settings?.lead_time_days??0))},[t.settings?.lead_time_days,d]),v.useEffect(()=>{m||(g(String(t.settings?.safety_margin_value??14)),_(t.settings?.safety_margin_unit??"days"))},[t.settings?.safety_margin_value,t.settings?.safety_margin_unit,m]);const N=it({mutationFn:se.upsertSkuSettings,onSuccess:()=>{a(),s(o("forecast.settingsSaved"),"success")},onError:()=>s(o("forecast.failedSaveSettings"),"error")}),C=t.settings?.alerts_snoozed??!1,P=[t.group.brand,t.group.material,t.group.subtype].filter(Boolean).join(" "),T=t.group.spools[0]?.rgba?`#${t.group.spools[0].rgba.substring(0,6)}`:"#4B5563",A=t.totalLabelG>0?Math.round(t.totalRemainingG/t.totalLabelG*100):0,F=C||t.daysRemaining===null?"text-bambu-gray":t.stockBreakAlert?"text-red-400":t.reorderAlert||t.daysRemaining<30?"text-yellow-400":"text-green-400";function S(H,R,Z,re=C){N.mutate({material:t.group.material,subtype:t.group.subtype,brand:t.group.brand,lead_time_days:H,safety_margin_value:R,safety_margin_unit:Z,alerts_snoozed:re})}function M(H){H.stopPropagation(),S(t.settings?.lead_time_days??0,t.settings?.safety_margin_value??14,t.settings?.safety_margin_unit??"days",!C)}const z=t.rateTier==="history"?r.jsxs("span",{className:"inline-flex items-center gap-1 text-xs px-1.5 py-0.5 rounded bg-bambu-green/15 text-bambu-green",children:[r.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-bambu-green"}),o("forecast.trend")]}):t.rateTier==="delta"?r.jsxs("span",{className:"inline-flex items-center gap-1 text-xs px-1.5 py-0.5 rounded bg-blue-400/15 text-blue-400",children:[r.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-blue-400"}),o("forecast.estimated")]}):r.jsxs("span",{className:"inline-flex items-center gap-1 text-xs px-1.5 py-0.5 rounded bg-bambu-dark-tertiary text-bambu-gray/60",children:[r.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-bambu-gray/40"}),o("forecast.noData")]}),I=C?"":t.stockBreakAlert?"bg-red-500/5":t.reorderAlert?"bg-yellow-500/5":"";return r.jsxs(r.Fragment,{children:[r.jsxs("tr",{className:`cursor-pointer hover:bg-bambu-dark-tertiary/40 transition-colors ${I} ${C?"opacity-50":""}`,onClick:()=>c(H=>!H),children:[r.jsx("td",{className:"px-4 py-3",children:r.jsx("span",{className:"block w-3 h-3 rounded-full border border-black/20",style:{backgroundColor:T}})}),r.jsxs("td",{className:"px-4 py-3",children:[r.jsx("div",{className:"text-sm font-medium text-white",children:P}),r.jsx("div",{className:"text-xs text-bambu-gray",children:o("forecast.spoolCount",{count:t.totalSpools})})]}),r.jsxs("td",{className:"px-4 py-3 min-w-[120px]",children:[r.jsx("div",{className:"h-1.5 bg-bambu-dark-tertiary rounded-full overflow-hidden mb-1 w-24",children:r.jsx("div",{className:`h-full rounded-full ${A>50?"bg-bambu-green":A>20?"bg-yellow-500":"bg-red-500"}`,style:{width:`${Math.min(A,100)}%`}})}),r.jsxs("span",{className:"text-xs text-bambu-gray",children:[Math.round(t.totalRemainingG),"g"]})]}),r.jsxs("td",{className:"px-4 py-3",children:[r.jsx("div",{className:"text-sm text-white",children:t.dailyRateG!==null?`${t.dailyRateG.toFixed(1)}g/d`:"—"}),r.jsx("div",{className:"mt-0.5",children:z})]}),r.jsx("td",{className:"px-4 py-3",children:r.jsx("span",{className:`text-sm font-semibold ${F}`,children:t.daysRemaining!==null?`${t.daysRemaining}d`:r.jsx("span",{className:"text-bambu-gray font-normal",children:"—"})})}),r.jsx("td",{className:"px-4 py-3",children:r.jsx("span",{className:"text-sm text-bambu-gray",children:t.projectedEmptyDate?wS(t.projectedEmptyDate):"—"})}),r.jsx("td",{className:"px-4 py-3",children:r.jsx("span",{className:`text-sm font-medium ${!C&&t.reorderAlert?"text-yellow-400":"text-bambu-gray"}`,children:t.reorderTriggerDate?wS(t.reorderTriggerDate):"—"})}),r.jsx("td",{className:"px-4 py-3",onClick:H=>H.stopPropagation(),children:r.jsxs("div",{className:"flex items-center justify-end gap-1",children:[n&&r.jsx("button",{onClick:i,className:"p-1.5 text-bambu-gray hover:text-bambu-green rounded transition-colors",title:o("forecast.addToCart"),children:r.jsx(lb,{className:"w-4 h-4"})}),!C&&(t.stockBreakAlert?r.jsx(Nn,{className:"w-4 h-4 text-red-400","aria-label":o("forecast.stockBreakRisk")}):t.reorderAlert?r.jsx(Nn,{className:"w-4 h-4 text-yellow-400","aria-label":o("forecast.reorderNow")}):t.daysRemaining!==null?r.jsx(_r,{className:"w-4 h-4 text-bambu-green/50"}):null),n&&r.jsx("button",{onClick:M,className:`p-1 rounded transition-colors ${C?"text-bambu-gray/70 hover:text-white":"text-bambu-dark-tertiary hover:text-bambu-gray"}`,title:o(C?"forecast.alertsEnabled":"forecast.alertsSnoozed"),children:r.jsx(NZ,{className:"w-3.5 h-3.5"})}),r.jsx("button",{onClick:H=>{H.stopPropagation(),c(R=>!R)},className:"p-1.5 text-bambu-gray hover:text-white rounded transition-colors",children:l?r.jsx(tl,{className:"w-4 h-4"}):r.jsx(Ln,{className:"w-4 h-4"})})]})})]}),l&&r.jsx("tr",{className:"bg-bambu-dark-tertiary/10",children:r.jsx("td",{colSpan:8,className:"px-6 py-4",children:r.jsxs("div",{className:"space-y-4",children:[r.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[r.jsx(hF,{label:o("forecast.effectiveLeadTime"),value:`${t.effectiveLeadTimeDays}d`,hint:o("forecast.effectiveLeadTimeHint",{global:e,sku:t.settings?.lead_time_days??0})}),r.jsx(hF,{label:o("forecast.safetyMarginLabel"),value:`${Math.round(t.safetyStockG)}g`,hint:o("forecast.safetyMarginHint")}),r.jsx(hF,{label:o("forecast.reorderPoint"),value:`${Math.round(t.reorderPointG)}g`,hint:o("forecast.reorderPointHint")})]}),n&&r.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[r.jsx(Ait,{label:o("forecast.skuLeadTimeOverride"),hint:o("forecast.skuLeadTimeHint"),unit:o("forecast.leadTime"),editing:d,value:t.settings?.lead_time_days??0,inputValue:f,onInputChange:b,onEdit:()=>{b(String(t.settings?.lead_time_days??0)),u(!0)},onSave:()=>{const H=parseInt(f,10);!isNaN(H)&&H>=0&&(S(H,t.settings?.safety_margin_value??14,x),u(!1))},onCancel:()=>u(!1),isPending:N.isPending,saveLabel:o("forecast.save"),cancelLabel:o("forecast.cancel")}),r.jsx(jit,{value:t.settings?.safety_margin_value??14,unit:x,editing:m,inputValue:w,dailyRateG:t.dailyRateG,onInputChange:g,onUnitChange:H=>_(H),onEdit:()=>{g(String(t.settings?.safety_margin_value??14)),_(t.settings?.safety_margin_unit??"days"),p(!0)},onSave:()=>{const H=parseInt(w,10);!isNaN(H)&&H>=0&&(S(t.settings?.lead_time_days??0,H,x),p(!1))},onCancel:()=>p(!1),isPending:N.isPending,saveLabel:o("forecast.save"),cancelLabel:o("forecast.cancel"),safetyMarginLabel:o("forecast.safetyMarginLabel")})]}),t.group.spools.length>1&&r.jsxs("div",{className:"border-t border-bambu-dark-tertiary pt-3",children:[r.jsx("p",{className:"text-xs text-bambu-gray mb-2",children:o("forecast.individualSpools")}),r.jsx("div",{className:"bg-bambu-dark-secondary rounded-lg overflow-hidden border border-bambu-dark-tertiary",children:r.jsxs("table",{className:"w-full",children:[r.jsx("thead",{children:r.jsxs("tr",{className:"border-b border-bambu-dark-tertiary bg-bambu-dark-tertiary/30",children:[r.jsx("th",{className:"px-4 py-2 text-left text-xs font-medium text-bambu-gray uppercase tracking-wide",children:"#"}),r.jsx("th",{className:"px-4 py-2 text-left text-xs font-medium text-bambu-gray uppercase tracking-wide",children:o("inventory.remaining")}),r.jsx("th",{className:"px-4 py-2 text-left text-xs font-medium text-bambu-gray uppercase tracking-wide",children:o("inventory.used")}),r.jsx("th",{className:"px-4 py-2 text-left text-xs font-medium text-bambu-gray uppercase tracking-wide",children:o("forecast.labelWeight")})]})}),r.jsx("tbody",{className:"divide-y divide-bambu-dark-tertiary",children:t.group.spools.map(H=>{const R=Math.max(0,H.label_weight-H.weight_used),Z=H.label_weight>0?R/H.label_weight*100:0;return r.jsxs("tr",{className:"hover:bg-bambu-dark-tertiary/30 transition-colors",children:[r.jsx("td",{className:"px-4 py-2",children:r.jsxs("span",{className:"text-xs font-mono text-bambu-gray/70",children:["#",H.id]})}),r.jsx("td",{className:"px-4 py-2",children:r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("div",{className:"w-24 h-1.5 bg-bambu-dark-tertiary rounded-full overflow-hidden flex-shrink-0",children:r.jsx("div",{className:`h-full rounded-full ${Z>50?"bg-bambu-green":Z>20?"bg-yellow-500":"bg-red-500"}`,style:{width:`${Math.min(Z,100)}%`}})}),r.jsxs("span",{className:"text-sm text-white",children:[Math.round(R),"g"]})]})}),r.jsx("td",{className:"px-4 py-2",children:r.jsxs("span",{className:"text-sm text-bambu-gray",children:[Math.round(H.weight_used),"g"]})}),r.jsx("td",{className:"px-4 py-2",children:r.jsxs("span",{className:"text-sm text-bambu-gray",children:[H.label_weight,"g"]})})]},H.id)})})]})})]})]})})})]})}function hF({label:t,value:e,hint:n}){return r.jsxs("div",{className:"bg-bambu-dark-tertiary/40 rounded-lg p-3",title:n,children:[r.jsx("div",{className:"text-xs text-bambu-gray mb-1",children:t}),r.jsx("div",{className:"text-lg font-semibold text-white",children:e})]})}function Ait({label:t,hint:e,unit:n,editing:a,value:i,inputValue:s,onInputChange:o,onEdit:l,onSave:c,onCancel:d,isPending:u,saveLabel:m="Save",cancelLabel:p="Cancel"}){return r.jsxs("div",{className:"bg-bambu-dark-tertiary/40 rounded-lg p-3 space-y-1",children:[r.jsxs("div",{className:"flex items-center gap-1.5",children:[r.jsx("span",{className:"text-xs font-medium text-white",children:t}),r.jsx("span",{title:e,children:r.jsx(Ci,{className:"w-3 h-3 text-bambu-gray/50"})})]}),a?r.jsxs("form",{className:"flex items-center gap-2",onSubmit:f=>{f.preventDefault(),c()},children:[r.jsx("input",{type:"number",min:0,max:365,value:s,onChange:f=>o(f.target.value),className:"w-20 px-2 py-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-sm text-white focus:outline-none focus:border-bambu-green",autoFocus:!0,disabled:u}),r.jsx("span",{className:"text-xs text-bambu-gray",children:n}),r.jsx("button",{type:"submit",disabled:u,className:"px-2 py-1 bg-bambu-green text-white text-xs rounded hover:bg-bambu-green/80 disabled:opacity-50",children:m}),r.jsx("button",{type:"button",onClick:d,disabled:u,className:"px-2 py-1 text-xs text-bambu-gray hover:text-white",children:p})]}):r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("span",{className:"text-lg font-semibold text-white",children:i}),r.jsx("span",{className:"text-xs text-bambu-gray",children:n}),r.jsx("button",{onClick:l,className:"p-1 text-bambu-gray hover:text-white rounded transition-colors",children:r.jsx(fc,{className:"w-3 h-3"})})]})]})}function jit({value:t,unit:e,editing:n,inputValue:a,dailyRateG:i,onInputChange:s,onUnitChange:o,onEdit:l,onSave:c,onCancel:d,isPending:u,saveLabel:m="Save",cancelLabel:p="Cancel",safetyMarginLabel:f="Safety Margin"}){const{t:b}=kt(),w=e==="g"?t:i!==null?Math.round(i*t):null,g=e==="days"?b("forecast.safetyMarginHintDays",{approx:w!==null?b("forecast.safetyMarginHintDaysApprox",{g:w}):""}):b("forecast.safetyMarginHintG",{approx:i!==null?b("forecast.safetyMarginHintGApprox",{days:Math.round(t/i)}):""});return r.jsxs("div",{className:"bg-bambu-dark-tertiary/40 rounded-lg p-3 space-y-1",children:[r.jsxs("div",{className:"flex items-center gap-1.5",children:[r.jsx("span",{className:"text-xs font-medium text-white",children:f}),r.jsx("span",{title:g,children:r.jsx(Ci,{className:"w-3 h-3 text-bambu-gray/50"})})]}),n?r.jsxs("form",{className:"flex items-center gap-2 flex-wrap",onSubmit:x=>{x.preventDefault(),c()},children:[r.jsx("input",{type:"number",min:0,max:e==="g"?1e4:365,value:a,onChange:x=>s(x.target.value),className:"w-20 px-2 py-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-sm text-white focus:outline-none focus:border-bambu-green",autoFocus:!0,disabled:u}),r.jsxs("div",{className:"flex bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded overflow-hidden text-xs",children:[r.jsx("button",{type:"button",onClick:()=>o("days"),className:`px-2 py-1 transition-colors ${e==="days"?"bg-bambu-green text-white":"text-bambu-gray hover:text-white"}`,children:"days"}),r.jsx("button",{type:"button",onClick:()=>o("g"),className:`px-2 py-1 transition-colors ${e==="g"?"bg-bambu-green text-white":"text-bambu-gray hover:text-white"}`,children:"g"})]}),r.jsx("button",{type:"submit",disabled:u,className:"px-2 py-1 bg-bambu-green text-white text-xs rounded hover:bg-bambu-green/80 disabled:opacity-50",children:m}),r.jsx("button",{type:"button",onClick:d,disabled:u,className:"px-2 py-1 text-xs text-bambu-gray hover:text-white",children:p})]}):r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("span",{className:"text-lg font-semibold text-white",children:t}),r.jsx("span",{className:"text-xs text-bambu-gray",children:e}),w!==null&&e==="days"&&r.jsxs("span",{className:"text-xs text-bambu-gray/60",children:["≈ ",w,"g"]}),e==="g"&&i!==null&&r.jsxs("span",{className:"text-xs text-bambu-gray/60",children:["≈ ",Math.round(t/i),"d"]}),r.jsx("button",{onClick:l,className:"p-1 text-bambu-gray hover:text-white rounded transition-colors",children:r.jsx(fc,{className:"w-3 h-3"})})]})]})}function Mit({items:t,forecasts:e,globalLeadTime:n,canWrite:a,onClose:i,onRemove:s,onClear:o}){const{t:l}=kt(),c=en(),[d,u]=v.useState("list"),m=it({mutationFn:async({id:g,status:x,item:_,avgSpoolG:N})=>{if(await se.updateShoppingListStatus(g,x),x==="received"&&_){const C=N??1e3,P={material:_.material,subtype:_.subtype,brand:_.brand,label_weight:C,core_weight:0,core_weight_catalog_id:null,color_name:null,rgba:null,extra_colors:null,effect_type:null,nozzle_temp_min:null,nozzle_temp_max:null,note:_.note??null,tag_uid:null,tray_uuid:null,data_origin:"manual",tag_type:null,cost_per_kg:null,last_scale_weight:null,last_weighed_at:null,weight_used:0,slicer_filament:null,slicer_filament_name:null,added_full:null,last_used:null,encode_time:null,category:"Stock",low_stock_threshold_pct:null};await se.bulkCreateSpools(P,_.quantity_spools),await se.removeFromShoppingList(g)}},onSuccess:()=>{c.invalidateQueries({queryKey:["shopping-list"]}),c.invalidateQueries({queryKey:["spools"]})}}),p=v.useMemo(()=>{const g=new Map;for(const x of e)g.set(x.group.key,x);return g},[e]),f=v.useMemo(()=>t.map(g=>({item:g,forecast:p.get(ww(g.material,g.subtype,g.brand))??null})),[t,p]),b=v.useMemo(()=>f.filter(({forecast:g})=>!g||g.dailyRateG===null?!1:g.stockBreakAlert||g.daysRemaining!==null&&g.daysRemaining<=g.effectiveLeadTimeDays),[f]);function w(){const g=[l("forecast.qty"),l("forecast.material"),"Brand","Subtype",`${l("forecast.weight")} (g)`,`${l("forecast.leadTime")} (d)`,l("forecast.expectedRestock"),l("forecast.status"),l("forecast.note")],x=t.map(T=>{const A=p.get(ww(T.material,T.subtype,T.brand))??null,F=A&&A.totalSpools>0?A.totalLabelG/A.totalSpools:1e3,S=Math.round(T.quantity_spools*F),M=A?.effectiveLeadTimeDays??n??0,z=M>0?wS(Um(new Date,M)):"";return[T.quantity_spools,T.material,T.brand??"",T.subtype??"",S,M||"",z,T.status,T.note??""].map(I=>`"${String(I).replace(/"/g,'""')}"`).join(",")}),_=[g.join(","),...x].join(` -`),N=new Blob([_],{type:"text/csv"}),C=URL.createObjectURL(N),P=document.createElement("a");P.href=C,P.download=`shopping-list-${new Date().toISOString().slice(0,10)}.csv`,P.click(),setTimeout(()=>URL.revokeObjectURL(C),100)}return r.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg overflow-hidden border border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"flex items-center justify-between px-4 py-3 border-b border-bambu-dark-tertiary bg-bambu-dark-tertiary/30",children:[r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx(lb,{className:"w-4 h-4 text-bambu-green"}),r.jsx("h3",{className:"text-sm font-semibold text-white",children:l("forecast.shoppingList")}),r.jsx("span",{className:"text-xs text-bambu-gray",children:l("forecast.shoppingListItems",{count:t.length})}),t.length>0&&r.jsxs("div",{className:"flex bg-bambu-dark-tertiary rounded-md p-0.5 ml-1",children:[r.jsxs("button",{onClick:()=>u("list"),className:`flex items-center gap-1.5 px-2 py-0.5 text-xs font-medium rounded transition-colors ${d==="list"?"bg-bambu-dark-secondary text-white shadow":"text-bambu-gray hover:text-white"}`,children:[r.jsx(Br,{className:"w-3 h-3"}),l("forecast.listView")]}),r.jsxs("button",{onClick:()=>u("logistics"),className:`flex items-center gap-1.5 px-2 py-0.5 text-xs font-medium rounded transition-colors ${d==="logistics"?"bg-bambu-dark-secondary text-white shadow":"text-bambu-gray hover:text-white"}`,children:[r.jsx(Hfe,{className:"w-3 h-3"}),l("forecast.logisticsView"),b.length>0&&r.jsx("span",{className:"w-3.5 h-3.5 rounded-full bg-red-500 text-white text-[9px] font-bold flex items-center justify-center",children:b.length})]})]})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[t.length>0&&r.jsxs(r.Fragment,{children:[r.jsxs("button",{onClick:w,className:"flex items-center gap-1.5 text-xs text-bambu-gray hover:text-white transition-colors px-2 py-1 rounded border border-bambu-dark-tertiary hover:bg-bambu-dark-tertiary",children:[r.jsx(Yr,{className:"w-3 h-3"}),l("forecast.downloadCsv")]}),a&&r.jsx("button",{onClick:o,className:"text-xs text-red-400 hover:text-red-300 transition-colors px-2 py-1 rounded border border-red-500/20 hover:bg-red-500/10",children:l("forecast.clearAll")})]}),r.jsx("button",{onClick:i,className:"p-1 text-bambu-gray hover:text-white transition-colors",children:r.jsx(Bt,{className:"w-4 h-4"})})]})]}),t.length===0?r.jsxs("div",{className:"flex flex-col items-center py-8 text-bambu-gray",children:[r.jsx(Br,{className:"w-8 h-8 mb-2 opacity-30"}),r.jsx("p",{className:"text-sm",children:l("forecast.shoppingListEmpty")})]}):d==="list"?r.jsx("div",{className:"overflow-x-auto",children:r.jsxs("table",{className:"w-full",children:[r.jsx("thead",{children:r.jsxs("tr",{className:"border-b border-bambu-dark-tertiary bg-bambu-dark-tertiary/20",children:[r.jsx("th",{className:"px-4 py-2 text-left text-xs font-medium text-bambu-gray uppercase tracking-wide",children:l("forecast.qty")}),r.jsx("th",{className:"px-4 py-2 text-left text-xs font-medium text-bambu-gray uppercase tracking-wide",children:l("forecast.material")}),r.jsx("th",{className:"px-4 py-2 text-left text-xs font-medium text-bambu-gray uppercase tracking-wide",children:l("forecast.weight")}),r.jsx("th",{className:"px-4 py-2 text-left text-xs font-medium text-bambu-gray uppercase tracking-wide",children:l("forecast.leadTime")}),r.jsx("th",{className:"px-4 py-2 text-left text-xs font-medium text-bambu-gray uppercase tracking-wide",children:l("forecast.expectedRestock")}),r.jsx("th",{className:"px-4 py-2 text-left text-xs font-medium text-bambu-gray uppercase tracking-wide",children:l("forecast.status")}),r.jsx("th",{className:"px-4 py-2 text-left text-xs font-medium text-bambu-gray uppercase tracking-wide",children:l("forecast.note")}),r.jsx("th",{className:"px-4 py-2 text-right text-xs font-medium text-bambu-gray uppercase tracking-wide",children:l("forecast.actions")})]})}),r.jsx("tbody",{className:"divide-y divide-bambu-dark-tertiary",children:t.map(g=>{const x=[g.brand,g.material,g.subtype].filter(Boolean).join(" "),_=b.some(z=>z.item.id===g.id),N=p.get(ww(g.material,g.subtype,g.brand))??null,C=N&&N.totalSpools>0?N.totalLabelG/N.totalSpools:1e3,P=Math.round(g.quantity_spools*C),T=N?.effectiveLeadTimeDays??n??0,A=T>0?Um(new Date,T):null,F=g.status==="purchased"||g.status==="received",S=g.status==="received",M=m.isPending;return r.jsxs("tr",{className:`hover:bg-bambu-dark-tertiary/30 transition-colors ${_&&!F?"bg-red-500/5":""}`,children:[r.jsx("td",{className:"px-4 py-2.5",children:r.jsxs("span",{className:"text-sm font-semibold text-bambu-green",children:[g.quantity_spools,"×"]})}),r.jsx("td",{className:"px-4 py-2.5",children:r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("span",{className:"text-sm text-white",children:x}),_&&!F&&r.jsx(Nn,{className:"w-3.5 h-3.5 text-red-400 flex-shrink-0","aria-label":l("forecast.stockBreakBefore")})]})}),r.jsx("td",{className:"px-4 py-2.5",children:r.jsx("span",{className:"text-sm text-white",children:P>=1e3?`${(P/1e3).toFixed(1)}kg`:`${P}g`})}),r.jsx("td",{className:"px-4 py-2.5",children:r.jsx("span",{className:"text-sm text-bambu-gray",children:T>0?`${T}d`:"—"})}),r.jsx("td",{className:"px-4 py-2.5",children:r.jsx("span",{className:"text-sm text-bambu-gray",children:A?wS(A):"—"})}),r.jsx("td",{className:"px-4 py-2.5",children:r.jsx("span",{className:`inline-flex items-center px-2 py-0.5 rounded text-xs font-medium ${S?"bg-bambu-green/20 text-bambu-green":F?"bg-blue-400/20 text-blue-400":"bg-bambu-dark-tertiary text-bambu-gray"}`,children:l(S?"forecast.received":F?"forecast.purchased":"forecast.pending")})}),r.jsx("td",{className:"px-4 py-2.5",children:r.jsx("span",{className:"text-xs text-bambu-gray",children:g.note||"—"})}),r.jsx("td",{className:"px-4 py-2.5",children:r.jsx("div",{className:"flex items-center justify-end gap-1",children:a&&r.jsxs(r.Fragment,{children:[r.jsx("button",{onClick:()=>m.mutate({id:g.id,status:F?"pending":"purchased"}),disabled:M||S,title:l(F?"forecast.resetToPending":"forecast.markPurchased"),className:`p-1 rounded transition-colors disabled:opacity-30 ${F?"text-blue-400 hover:text-bambu-gray":"text-bambu-gray hover:text-blue-400"}`,children:F?r.jsx(gs,{className:"w-3.5 h-3.5"}):r.jsx(Tge,{className:"w-3.5 h-3.5"})}),r.jsx("button",{onClick:()=>m.mutate({id:g.id,status:"received",item:g,avgSpoolG:C}),disabled:M||!F||S,title:l("forecast.markReceived"),className:"p-1 rounded transition-colors text-bambu-gray hover:text-bambu-green disabled:opacity-30",children:r.jsx(Axe,{className:"w-3.5 h-3.5"})}),r.jsx("button",{onClick:()=>s(g.id),className:"p-1 text-bambu-gray hover:text-red-400 transition-colors",title:l("forecast.remove"),children:r.jsx(Jt,{className:"w-3.5 h-3.5"})})]})})})]},g.id)})})]})}):r.jsx("div",{className:"divide-y divide-bambu-dark-tertiary",children:f.filter(({item:g})=>g.status!=="received").map(({item:g,forecast:x})=>r.jsx(Eit,{item:g,forecast:x,globalLeadTime:n,canWrite:a,onRemove:()=>s(g.id)},g.id))})]})}function Eit({item:t,forecast:e,globalLeadTime:n,canWrite:a,onRemove:i}){const{t:s}=kt(),o=[t.brand,t.material,t.subtype].filter(Boolean).join(" "),l=v.useMemo(()=>{if(!e||e.dailyRateG===null||e.dailyRateG<=0)return null;const u=e.dailyRateG,m=e.effectiveLeadTimeDays,p=e.totalSpools>0?e.totalLabelG/e.totalSpools:1e3,f=t.quantity_spools*p,b=Math.max(0,e.totalRemainingG-u*m),w=b+f,g=Math.ceil(w/u),x=Math.min(m+g+5,365),_=[];for(let N=0;N<=x;N++){const C=Sw(Um(new Date,N));if(N===m)_.push({day:N,label:C,stock:Math.round(b),rop:Math.round(e.reorderPointG),safetyStock:Math.round(e.safetyStockG)}),_.push({day:N,label:C,stock:Math.round(w),rop:Math.round(e.reorderPointG),safetyStock:Math.round(e.safetyStockG),arrival:!0});else{const P=N{if(!e||e.dailyRateG===null||e.dailyRateG<=0)return null;const u=Math.floor(e.totalRemainingG/e.dailyRateG);return uu>=1e3?`${(u/1e3).toFixed(1)}kg`:`${u}g`,width:44}),r.jsx(nu,{contentStyle:{background:"#1a1a2e",border:"1px solid #374151",borderRadius:8,fontSize:11},labelStyle:{color:"#9CA3AF"},formatter:(u,m)=>typeof u!="number"?"":m==="stock"?`${u}g — ${s("forecast.stock")}`:m==="rop"?`${u}g — ${s("forecast.reorderPoint")}`:m==="safetyStock"?`${u}g — ${s("forecast.safetyMarginLabel")}`:`${u}`}),r.jsx(DA,{type:"linear",dataKey:"stock",stroke:"#1DB954",strokeWidth:2,fill:`url(#cart-post-${t.id})`,dot:!1,activeDot:{r:3}}),e.reorderPointG>0&&r.jsx(ru,{y:e.reorderPointG,stroke:"#F59E0B",strokeDasharray:"5 3",strokeOpacity:.8,label:{value:"ROP",position:"insideTopRight",fill:"#F59E0B",fontSize:9}}),e.safetyStockG>0&&r.jsx(ru,{y:e.safetyStockG,stroke:"#6B7280",strokeDasharray:"3 3",strokeOpacity:.6,label:{value:"SS",position:"insideTopRight",fill:"#6B7280",fontSize:9}}),r.jsx(ru,{x:Sw(Um(new Date,l.lt)),stroke:"#3B82F6",strokeWidth:1.5,strokeDasharray:"4 3",strokeOpacity:.9,label:{value:`+${l.arrivalG>=1e3?`${(l.arrivalG/1e3).toFixed(1)}kg`:`${Math.round(l.arrivalG)}g`} arrives (d${l.lt})`,position:"insideTopLeft",fill:"#3B82F6",fontSize:9}}),c!==null&&r.jsx(ru,{x:Sw(Um(new Date,c)),stroke:"#EF4444",strokeWidth:1.5,strokeOpacity:.9,label:{value:"OUT",position:"insideTopLeft",fill:"#EF4444",fontSize:9}})]})}),r.jsxs("div",{className:"flex flex-wrap items-center gap-3 mt-2 text-[10px] text-bambu-gray",children:[r.jsxs("span",{className:"flex items-center gap-1",children:[r.jsx("span",{className:"inline-block w-4 border-t-2 border-yellow-400 border-dashed"})," ",s("forecast.ropLabel")]}),r.jsxs("span",{className:"flex items-center gap-1",children:[r.jsx("span",{className:"inline-block w-4 border-t border-bambu-gray border-dashed"})," ",s("forecast.safetyStockLegend")]}),r.jsxs("span",{className:"flex items-center gap-1",children:[r.jsx("span",{className:"inline-block w-4 border-t-2 border-blue-400 border-dashed"})," ",s("forecast.stockArrivalLegend")]}),d&&r.jsxs("span",{className:"flex items-center gap-1 text-red-400",children:[r.jsx("span",{className:"inline-block w-4 border-t-2 border-red-400"})," ",s("forecast.stockoutLegend")]})]})]}):null]})}function Dit({forecast:t,onClose:e,onAdd:n}){const{t:a}=kt(),i=[t.group.brand,t.group.material,t.group.subtype].filter(Boolean).join(" "),[s,o]=v.useState("qty"),[l,c]=v.useState("1"),[d,u]=v.useState("30"),[m,p]=v.useState(""),f=v.useMemo(()=>{if(!t.dailyRateG||t.dailyRateG<=0)return null;const g=t.dailyRateG*Number(d),x=t.group.spools.length>0?t.group.spools.reduce((_,N)=>_+N.label_weight,0)/t.group.spools.length:1e3;return Math.ceil(g/x)},[t,d]),b=s==="qty"?parseInt(l,10)||1:f??1;function w(g){g.preventDefault(),n({material:t.group.material,subtype:t.group.subtype,brand:t.group.brand,quantity_spools:b,note:m||null})}return r.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm p-4",children:r.jsxs("div",{className:"bg-bambu-dark-secondary rounded-2xl border border-bambu-dark-tertiary w-full max-w-sm shadow-2xl",children:[r.jsxs("div",{className:"flex items-center justify-between px-5 pt-5 pb-4 border-b border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(lb,{className:"w-5 h-5 text-bambu-green"}),r.jsx("h2",{className:"text-base font-semibold text-white",children:a("forecast.addToCartTitle")})]}),r.jsx("button",{onClick:e,className:"p-1 text-bambu-gray hover:text-white transition-colors",children:r.jsx(Bt,{className:"w-5 h-5"})})]}),r.jsxs("form",{onSubmit:w,className:"p-5 space-y-4",children:[r.jsx("div",{className:"text-sm text-bambu-gray",children:i}),r.jsxs("div",{className:"flex bg-bambu-dark-tertiary rounded-lg p-0.5",children:[r.jsx("button",{type:"button",onClick:()=>o("qty"),className:`flex-1 py-1.5 text-xs font-medium rounded-md transition-colors ${s==="qty"?"bg-bambu-dark-secondary text-white shadow":"text-bambu-gray hover:text-white"}`,children:a("forecast.byQuantity")}),r.jsx("button",{type:"button",onClick:()=>o("duration"),className:`flex-1 py-1.5 text-xs font-medium rounded-md transition-colors ${s==="duration"?"bg-bambu-dark-secondary text-white shadow":"text-bambu-gray hover:text-white"}`,children:a("forecast.byDuration")})]}),s==="qty"?r.jsxs("div",{className:"space-y-1.5",children:[r.jsx("label",{className:"text-xs text-bambu-gray",children:a("forecast.numberOfSpools")}),r.jsx("input",{type:"number",min:1,max:99,value:l,onChange:g=>c(g.target.value),className:"w-full px-3 py-2 bg-bambu-dark-tertiary border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:outline-none focus:border-bambu-green",autoFocus:!0})]}):r.jsxs("div",{className:"space-y-2",children:[r.jsxs("div",{className:"space-y-1.5",children:[r.jsx("label",{className:"text-xs text-bambu-gray",children:a("forecast.lastHowManyDays")}),r.jsx("input",{type:"number",min:1,max:365,value:d,onChange:g=>u(g.target.value),className:"w-full px-3 py-2 bg-bambu-dark-tertiary border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:outline-none focus:border-bambu-green",autoFocus:!0})]}),t.dailyRateG!==null?r.jsxs("div",{className:"flex items-center gap-2 px-3 py-2 bg-bambu-dark-tertiary/50 rounded-lg",children:[r.jsx("span",{className:"text-xs text-bambu-gray",children:"≈"}),r.jsx("span",{className:"text-sm font-semibold text-bambu-green",children:a("forecast.spoolCount",{count:f??0})}),r.jsxs("span",{className:"text-xs text-bambu-gray",children:["at ",t.dailyRateG.toFixed(1),"g/day"]})]}):r.jsx("div",{className:"text-xs text-yellow-400 px-1",children:a("forecast.noUsageQty")})]}),r.jsxs("div",{className:"space-y-1.5",children:[r.jsx("label",{className:"text-xs text-bambu-gray",children:a("forecast.noteOptional")}),r.jsx("input",{type:"text",maxLength:200,value:m,onChange:g=>p(g.target.value),placeholder:a("forecast.notePlaceholder"),className:"w-full px-3 py-2 bg-bambu-dark-tertiary border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/40 focus:outline-none focus:border-bambu-green"})]}),r.jsxs("div",{className:"flex items-center gap-3 pt-1",children:[r.jsx("button",{type:"submit",className:"flex-1 py-2 bg-bambu-green text-white text-sm font-medium rounded-lg hover:bg-bambu-green/80 transition-colors",children:a("forecast.addNSpools",{count:b})}),r.jsx("button",{type:"button",onClick:e,className:"px-4 py-2 text-sm text-bambu-gray hover:text-white border border-bambu-dark-tertiary rounded-lg transition-colors",children:a("forecast.cancel")})]})]})]})})}const YI={material:"",subtype:"",brand:"",color_name:"",rgba:"808080FF",extra_colors:"",effect_type:"",label_weight:1e3,core_weight:250,core_weight_catalog_id:null,weight_used:0,slicer_filament:"",note:"",cost_per_kg:null,category:"",low_stock_threshold_pct:null,storage_location:"",spoolman_filament_id:null},Fit=new Set(["material","subtype","brand","rgba","color_name","label_weight"]);function zce(t,e=!1,n=!1){const a={};return e||n?(!t.material&&!t.spoolman_filament_id&&(a.material="Material is required"),{isValid:Object.keys(a).length===0,errors:a}):(t.slicer_filament||(a.slicer_filament="Slicer preset is required"),t.material||(a.material="Material is required"),t.brand||(a.brand="Brand is required"),t.subtype||(a.subtype="Subtype is required"),{isValid:Object.keys(a).length===0,errors:a})}const Uce=["PLA","PETG","ABS","TPU","ASA","PC","PA","PVA","HIPS","PA-CF","PETG-CF","PLA-CF"],Lit=["Bambu","PolyLite","PolyTerra","eSUN","Overture","Fiberon","SUNLU","Inland","Hatchbox","Generic"],_w=["Basic","Matte","Silk","Silk+","Tough","Tough+","HF","High Flow","Engineering","Galaxy","Glow","Marble","Metal","Rainbow","Sparkle","Wood","Translucent","Transparent","Clear","Lite","Pro","Plus","Max","Super","Ultra","Flex","Soft","Hard","Strong","Impact","Heat Resistant","UV Resistant","ESD","Conductive","Magnetic","Gradient","Dual Color","Tri Color","Multicolor"],Bce=[{name:"Black",hex:"000000"},{name:"White",hex:"FFFFFF"},{name:"Gray",hex:"808080"},{name:"Red",hex:"FF0000"},{name:"Orange",hex:"FFA500"},{name:"Yellow",hex:"FFFF00"},{name:"Green",hex:"00AE42"},{name:"Blue",hex:"0066FF"},{name:"Purple",hex:"8B00FF"},{name:"Pink",hex:"FF69B4"},{name:"Brown",hex:"8B4513"},{name:"Silver",hex:"C0C0C0"}],Rit=[{name:"Dark Red",hex:"8B0000"},{name:"Crimson",hex:"DC143C"},{name:"Coral",hex:"FF7F50"},{name:"Salmon",hex:"FA8072"},{name:"Dark Orange",hex:"FF8C00"},{name:"Peach",hex:"FFDAB9"},{name:"Gold",hex:"FFD700"},{name:"Khaki",hex:"F0E68C"},{name:"Lemon",hex:"FFF44F"},{name:"Lime",hex:"32CD32"},{name:"Forest Green",hex:"228B22"},{name:"Olive",hex:"808000"},{name:"Mint",hex:"98FF98"},{name:"Teal",hex:"008080"},{name:"Navy",hex:"000080"},{name:"Sky Blue",hex:"87CEEB"},{name:"Royal Blue",hex:"4169E1"},{name:"Cyan",hex:"00FFFF"},{name:"Turquoise",hex:"40E0D0"},{name:"Violet",hex:"EE82EE"},{name:"Magenta",hex:"FF00FF"},{name:"Indigo",hex:"4B0082"},{name:"Lavender",hex:"E6E6FA"},{name:"Plum",hex:"DDA0DD"},{name:"Hot Pink",hex:"FF69B4"},{name:"Rose",hex:"FF007F"},{name:"Blush",hex:"FFB6C1"},{name:"Chocolate",hex:"D2691E"},{name:"Tan",hex:"D2B48C"},{name:"Beige",hex:"F5F5DC"},{name:"Maroon",hex:"800000"},{name:"Dark Gray",hex:"404040"},{name:"Light Gray",hex:"D3D3D3"},{name:"Charcoal",hex:"36454F"},{name:"Ivory",hex:"FFFFF0"},{name:"Bambu Green",hex:"00AE42"},{name:"Jade White",hex:"E8E8E8"},{name:"Titan Gray",hex:"5A5A5A"}],bQ=[...Bce,...Rit],Hce="bambuddy-recent-colors",Iit=8,Oit=[{code:"GFL00",name:"Bambu PLA Basic",displayName:"Bambu PLA Basic",isCustom:!1,allCodes:["GFL00"]},{code:"GFL01",name:"Bambu PLA Matte",displayName:"Bambu PLA Matte",isCustom:!1,allCodes:["GFL01"]},{code:"GFL05",name:"Generic PLA",displayName:"Generic PLA",isCustom:!1,allCodes:["GFL05"]},{code:"GFG00",name:"Bambu PETG Basic",displayName:"Bambu PETG Basic",isCustom:!1,allCodes:["GFG00"]},{code:"GFG05",name:"Generic PETG",displayName:"Generic PETG",isCustom:!1,allCodes:["GFG05"]},{code:"GFB00",name:"Bambu ABS Basic",displayName:"Bambu ABS Basic",isCustom:!1,allCodes:["GFB00"]},{code:"GFB05",name:"Generic ABS",displayName:"Generic ABS",isCustom:!1,allCodes:["GFB05"]},{code:"GFA00",name:"Bambu ASA Basic",displayName:"Bambu ASA Basic",isCustom:!1,allCodes:["GFA00"]},{code:"GFU00",name:"Bambu TPU 95A",displayName:"Bambu TPU 95A",isCustom:!1,allCodes:["GFU00"]},{code:"GFU05",name:"Generic TPU",displayName:"Generic TPU",isCustom:!1,allCodes:["GFU05"]},{code:"GFC00",name:"Bambu PC Basic",displayName:"Bambu PC Basic",isCustom:!1,allCodes:["GFC00"]},{code:"GFN00",name:"Bambu PA Basic",displayName:"Bambu PA Basic",isCustom:!1,allCodes:["GFN00"]},{code:"GFN05",name:"Generic PA",displayName:"Generic PA",isCustom:!1,allCodes:["GFN05"]},{code:"GFS00",name:"Bambu PLA-CF",displayName:"Bambu PLA-CF",isCustom:!1,allCodes:["GFS00"]},{code:"GFT00",name:"Bambu PETG-CF",displayName:"Bambu PETG-CF",isCustom:!1,allCodes:["GFT00"]},{code:"GFNC0",name:"Bambu PA-CF",displayName:"Bambu PA-CF",isCustom:!1,allCodes:["GFNC0"]},{code:"GFV00",name:"Bambu PVA",displayName:"Bambu PVA",isCustom:!1,allCodes:["GFV00"]}];function Jh(t){let e=t.replace(/@.*$/,"").trim();e=e.replace(/\(Custom\)/i,"").trim(),e=e.replace(/^[#*]+\s*/,"").trim();const n=["PLA-CF","PETG-CF","ABS-GF","ASA-CF","PA-CF","PAHT-CF","PA6-CF","PA6-GF","PPA-CF","PPA-GF","PET-CF","PPS-CF","PC-CF","PC-ABS","ABS-GF","PCTG","PETG","PLA","ABS","ASA","PC","PA","TPU","PVA","HIPS","BVOH","PPS","PEEK","PEI"];let a="",i=-1;for(const c of n){const d=e.toUpperCase().indexOf(c.toUpperCase());if(d!==-1){a=c,i=d;break}}let s="";i>0&&(s=e.substring(0,i).trim(),s=s.replace(/[-_\s]+$/,""));let o="";i!==-1&&a&&(o=e.substring(i+a.length).trim(),o=o.replace(/^[-_\s]+/,""));let l="";for(const c of _w)if(o.toLowerCase().includes(c.toLowerCase())){l=c;break}if(!l&&s)for(const c of _w){const d=new RegExp(`\\s+${c}$`,"i");if(d.test(s)){l=c,s=s.replace(d,"").trim();break}}return{brand:s,material:a,variant:l}}function qce(t,e){const n=new Set(Lit);for(const a of t){const{brand:i}=Jh(a.name);i&&i.length>1&&n.add(i)}if(e)for(const a of e)if(a.filament_vendor&&a.filament_vendor.length>1)n.add(a.filament_vendor);else{const{brand:i}=Jh(a.name);i&&i.length>1&&n.add(i)}return Array.from(n).sort((a,i)=>a.localeCompare(i))}function zit(t){const e=t.filter(a=>a.preset_type==="filament");return e.length===0?[]:e.map(a=>{const i=a.filament_type||String(a.id),s=Array.from(new Set([i,String(a.id)]));return{code:i,name:a.name,displayName:a.name,isCustom:!1,allCodes:s}}).sort((a,i)=>a.displayName.localeCompare(i.displayName))}function $ce(t,e,n,a){const i=[],s=[],o=new Set;for(const u of t)if(u.is_custom){const m=u.name.toUpperCase();(e.size===0||Array.from(e).some(f=>m.includes(f))||!m.includes("@"))&&(i.push({code:u.setting_id,name:u.name,displayName:`${u.name} (Custom)`,isCustom:!0,allCodes:[u.setting_id]}),o.add(u.setting_id))}else s.push({code:u.setting_id,name:u.name,displayName:u.name,isCustom:!1,allCodes:[u.setting_id]}),o.add(u.setting_id);const l=n&&n.length>0?zit(n):[],c=[];if(a&&a.length>0)for(const u of a){const m=u.filament_id.startsWith("GF")?"GFS"+u.filament_id.slice(2):u.filament_id;o.has(u.filament_id)||o.has(m)||c.push({code:u.filament_id,name:u.name,displayName:u.name,isCustom:!1,allCodes:[u.filament_id,m]})}const d=[...i,...s,...l,...c];return d.length===0?Oit:d.sort((u,m)=>u.displayName.localeCompare(m.displayName))}function Vce(t,e){if(!t)return;let n=e.find(a=>a.code===t);if(n||(n=e.find(a=>a.allCodes.includes(t))),!n){const a=t.toLowerCase();n=e.find(i=>i.code.toLowerCase()===a||i.allCodes.some(s=>s.toLowerCase()===a))}return n}function Gce(){try{const t=localStorage.getItem(Hce);if(t)return JSON.parse(t)}catch{}return[]}function Wce(t,e){const n=e.filter(i=>i.hex.toUpperCase()!==t.hex.toUpperCase()),a=[t,...n].slice(0,Iit);try{localStorage.setItem(Hce,JSON.stringify(a))}catch{}return a}function fF(t,e){if(!e.material)return!1;const a=(t.name||"").replace(/^High Flow[_\s]+/i,"").replace(/^Standard[_\s]+/i,"").replace(/^HF[_\s]+/i,"").replace(/^S[_\s]+/i,"").trim(),i=Jh(a);return!(!(i.material.toUpperCase()===e.material.toUpperCase())||e.brand&&!(i.brand.toLowerCase().includes(e.brand.toLowerCase())||e.brand.toLowerCase().includes(i.brand.toLowerCase()))||e.subtype&&!(i.variant.toLowerCase().includes(e.subtype.toLowerCase())||e.subtype.toLowerCase().includes(i.variant.toLowerCase())||a.toLowerCase().includes(e.subtype.toLowerCase())))}function Kce({formData:t,updateField:e,cloudAuthenticated:n,loadingCloudPresets:a,presetInputValue:i,setPresetInputValue:s,selectedPresetOption:o,filamentOptions:l,availableBrands:c,availableMaterials:d,quickAdd:u,quantity:m,onQuantityChange:p,errors:f}){const{t:b}=kt(),[w,g]=v.useState(!1),[x,_]=v.useState(!1),[N,C]=v.useState(!1),[P,T]=v.useState(!1),[A,F]=v.useState(""),[S,M]=v.useState(""),[z,I]=v.useState(""),[H,R]=v.useState(String(t.label_weight)),[Z,re]=v.useState(!1),J=v.useRef(null),de=v.useRef(null),me=v.useRef(null),ue=v.useRef(null);v.useEffect(()=>{const $=K=>{J.current&&!J.current.contains(K.target)&&g(!1),ue.current&&!ue.current.contains(K.target)&&T(!1),de.current&&!de.current.contains(K.target)&&_(!1),me.current&&!me.current.contains(K.target)&&C(!1)};return document.addEventListener("mousedown",$),()=>document.removeEventListener("mousedown",$)},[]);const W=v.useMemo(()=>{if(!i)return l;const $=i.toLowerCase();return l.filter(K=>K.displayName.toLowerCase().includes($)||K.code.toLowerCase().includes($))},[l,i]),ae=v.useMemo(()=>{if(!A)return c;const $=A.toLowerCase();return c.filter(D=>D.toLowerCase().includes($)).sort((D,j)=>{const B=D.toLowerCase()===$,X=j.toLowerCase()===$;return B&&!X?-1:!B&&X?1:D.localeCompare(j)})},[c,A]),pe=v.useMemo(()=>{if(!S)return _w;const $=S.toLowerCase();return _w.filter(K=>K.toLowerCase().includes($))},[S]),ye=v.useMemo(()=>{if(!z)return d;const $=z.toLowerCase();return d.filter(D=>D.toLowerCase().includes($)).sort((D,j)=>{const B=D.toLowerCase()===$,X=j.toLowerCase()===$;return B&&!X?-1:!B&&X?1:D.localeCompare(j)})},[z,d]);v.useEffect(()=>{Z||R(String(t.label_weight))},[t.label_weight,Z]);const Te=$=>{e("slicer_filament",$.code),s($.displayName),g(!1);const K=Jh($.name);K.material&&e("material",K.material),K.brand&&e("brand",K.brand),K.variant&&e("subtype",K.variant)};return r.jsxs("div",{className:"space-y-4",children:[!u&&r.jsx("div",{className:"flex items-center gap-2 text-xs text-bambu-gray",children:a?r.jsxs(r.Fragment,{children:[r.jsx(ut,{className:"w-3 h-3 animate-spin"})," ",b("inventory.loadingPresets")]}):n?r.jsxs(r.Fragment,{children:[r.jsx(Hh,{className:"w-3 h-3 text-bambu-green"})," ",b("inventory.cloudConnected")]}):r.jsxs(r.Fragment,{children:[r.jsx(UF,{className:"w-3 h-3"})," ",b("inventory.cloudNotConnected")]})}),!u&&r.jsxs("div",{children:[r.jsxs("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:[b("inventory.slicerPreset")," *"]}),r.jsxs("div",{className:"relative",ref:J,children:[r.jsx(Sr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50 pointer-events-none"}),r.jsx("input",{type:"text",className:"w-full pl-9 pr-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green",placeholder:b("inventory.searchPresets"),value:i,onChange:$=>{s($.target.value),g(!0)},onFocus:()=>{g(!0),s("")}}),w&&r.jsx("div",{className:"absolute z-50 w-full mt-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-lg max-h-64 overflow-y-auto",children:W.length===0?r.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:b("inventory.noPresetsFound")}):W.map($=>r.jsx("button",{type:"button",className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary truncate ${o?.code===$.code?"bg-bambu-green/10 text-bambu-green":"text-white"}`,onClick:()=>Te($),children:$.displayName},`${$.code}::${$.name}`))})]}),o&&r.jsxs("div",{className:"mt-1 text-xs text-bambu-gray",children:[b("inventory.selectedPreset"),": ",r.jsx("span",{className:"font-mono text-bambu-green",children:o.code})]}),f?.slicer_filament&&r.jsx("p",{className:"mt-1 text-xs text-red-400",children:f.slicer_filament})]}),r.jsxs("div",{children:[r.jsxs("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:[b("inventory.material")," *"]}),r.jsxs("div",{className:"relative",ref:ue,children:[r.jsx("input",{type:"text",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green",placeholder:b("inventory.selectMaterial"),value:P?z:t.material,onChange:$=>{I($.target.value),T(!0)},onFocus:()=>{T(!0),I("")}}),r.jsx(Ln,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50 pointer-events-none"}),P&&r.jsxs("div",{className:"absolute z-50 w-full mt-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-lg max-h-48 overflow-y-auto",children:[ye.length===0?r.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:b("inventory.noResults")}):ye.map($=>r.jsx("button",{type:"button",className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary ${t.material===$?"bg-bambu-green/10 text-bambu-green":"text-white"}`,onClick:()=>{e("material",$),T(!1),I("")},children:$},$)),z&&!ye.includes(z)&&r.jsx("button",{type:"button",className:"w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary text-bambu-green border-t border-bambu-dark-tertiary",onClick:()=>{e("material",z),T(!1),I("")},children:b("inventory.useCustomMaterial",{material:z})})]})]}),f?.material&&r.jsx("p",{className:"mt-1 text-xs text-red-400",children:f.material})]}),r.jsxs("div",{children:[r.jsxs("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:[b("inventory.brand"),!u&&" *"]}),r.jsxs("div",{className:"relative",ref:de,children:[r.jsx("input",{type:"text",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green",placeholder:b("inventory.searchBrand"),value:x?A:t.brand,onChange:$=>{F($.target.value),_(!0)},onFocus:()=>{_(!0),F("")}}),r.jsx(Ln,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50 pointer-events-none"}),x&&r.jsxs("div",{className:"absolute z-50 w-full mt-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-lg max-h-48 overflow-y-auto",children:[ae.length===0?r.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:b("inventory.noResults")}):ae.map($=>r.jsx("button",{type:"button",className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary ${t.brand===$?"bg-bambu-green/10 text-bambu-green":"text-white"}`,onClick:()=>{e("brand",$),_(!1),F("")},children:$},$)),A&&!ae.includes(A)&&r.jsx("button",{type:"button",className:"w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary text-bambu-green border-t border-bambu-dark-tertiary",onClick:()=>{e("brand",A),_(!1),F("")},children:b("inventory.useCustomBrand",{brand:A})})]})]}),f?.brand&&r.jsx("p",{className:"mt-1 text-xs text-red-400",children:f.brand})]}),r.jsxs("div",{children:[r.jsxs("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:[b("inventory.subtype"),!u&&" *"]}),r.jsxs("div",{className:"relative",ref:me,children:[r.jsx("input",{type:"text",value:N?S:t.subtype,onChange:$=>{M($.target.value),C(!0)},onFocus:()=>{C(!0),M("")},placeholder:"Basic, Matte, Silk...",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green"}),r.jsx(Ln,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50 pointer-events-none"}),N&&r.jsxs("div",{className:"absolute z-50 w-full mt-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-lg max-h-48 overflow-y-auto",children:[pe.length===0?r.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:b("inventory.noResults")}):pe.map($=>r.jsx("button",{type:"button",className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary ${t.subtype===$?"bg-bambu-green/10 text-bambu-green":"text-white"}`,onClick:()=>{e("subtype",$),C(!1),M("")},children:$},$)),S&&!_w.some($=>$.toLowerCase()===S.toLowerCase().trim())&&r.jsx("button",{type:"button",className:"w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary text-bambu-green border-t border-bambu-dark-tertiary",onClick:()=>{e("subtype",S),C(!1),M("")},children:b("inventory.useCustomBrand",{brand:S})})]})]}),f?.subtype&&r.jsx("p",{className:"mt-1 text-xs text-red-400",children:f.subtype})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:b("inventory.labelWeight")}),r.jsxs("div",{className:"relative",children:[r.jsx("input",{type:"number",className:"w-full px-3 py-2 pr-7 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:outline-none focus:border-bambu-green",value:H,min:0,onFocus:()=>re(!0),onChange:$=>R($.target.value),onBlur:()=>{re(!1);const $=H.trim(),K=Number($);if(!$||!Number.isFinite(K)||K<0){R(String(t.label_weight));return}const D=Math.round(K);e("label_weight",D),R(String(D))}}),r.jsx("span",{className:"absolute right-2 top-1/2 -translate-y-1/2 text-xs text-bambu-gray",children:"g"})]})]}),u&&r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:b("inventory.quantity")}),r.jsx("input",{type:"number",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:outline-none focus:border-bambu-green",value:m,min:1,max:100,onChange:$=>{const K=Math.max(1,Math.min(100,parseInt($.target.value)||1));p(K)}})]})]})}function Uit(t){const e=t.split(/[\s,]+/).map(i=>i.trim().replace(/^#/,"")).filter(Boolean),n=[],a=[];for(const i of e)(i.length===6||i.length===8)&&/^[0-9a-fA-F]+$/.test(i)?n.push(i.toLowerCase()):a.push(i);return{value:n.join(","),invalid:a}}function Yce({formData:t,updateField:e,recentColors:n,onColorUsed:a,catalogColors:i}){const{t:s}=kt(),[o,l]=v.useState(!1),[c,d]=v.useState(""),u=t.rgba.replace("#","").substring(0,6),m=F=>u.toUpperCase()===F.toUpperCase(),p=(F,S)=>{e("rgba",F.toUpperCase()+"FF"),e("color_name",S),a({name:S,hex:F})},f=v.useMemo(()=>{if(i.length===0)return[];const F=t.brand?.trim(),S=t.material?.toLowerCase().trim(),M=t.subtype?.toLowerCase().trim();if(!F&&!S)return[];const z=F?F.toLowerCase().split(/[\s\-_]+/).filter(R=>R.length>=2):[],I=R=>{if(z.length===0)return!0;const Z=R.toLowerCase();return z.some(re=>Z.includes(re))};if(F&&!S){const R=i.filter(Z=>I(Z.manufacturer));if(R.length>0)return R.map(Z=>({name:Z.color_name,hex:Z.hex_color.replace("#","").substring(0,6),manufacturer:Z.manufacturer,material:typeof Z.material=="string"?Z.material:void 0}))}const H=S&&M?`${S} ${M}`:"";if(H){const R=i.filter(re=>I(re.manufacturer)&&re.material?.toLowerCase()===H);if(R.length>0)return R.map(re=>({name:re.color_name,hex:re.hex_color.replace("#","").substring(0,6),manufacturer:re.manufacturer,material:typeof re.material=="string"?re.material:void 0}));const Z=H.replace(/\+$/,"");if(Z!==H){const re=i.filter(J=>I(J.manufacturer)&&J.material?.toLowerCase()===Z);if(re.length>0)return re.map(J=>({name:J.color_name,hex:J.hex_color.replace("#","").substring(0,6),manufacturer:J.manufacturer,material:typeof J.material=="string"?J.material:void 0}))}}if(S){const R=i.filter(Z=>I(Z.manufacturer)&&(!Z.material||Z.material.toLowerCase().startsWith(S)));if(R.length>0)return R.map(Z=>({name:Z.color_name,hex:Z.hex_color.replace("#","").substring(0,6),manufacturer:Z.manufacturer,material:typeof Z.material=="string"?Z.material:void 0}))}return[]},[i,t.brand,t.material,t.subtype]),b=v.useMemo(()=>{if(!c)return f;if(f.length===0)return[];const F=c.toLowerCase();return f.filter(M=>M.name.toLowerCase().includes(F)||(M.manufacturer?.toLowerCase().includes(F)??!1)||(M.material?.toLowerCase().includes(F)??!1))},[c,f]),w=f.length>0,g=v.useMemo(()=>c?bQ.filter(F=>F.name.toLowerCase().includes(c.toLowerCase())):o?bQ:Bce,[c,o]),[x,_]=v.useState(t.extra_colors),[N,C]=v.useState([]),P=v.useRef(t.extra_colors);v.useEffect(()=>{t.extra_colors!==P.current&&(_(t.extra_colors),C([]),P.current=t.extra_colors)},[t.extra_colors]);const T=v.useMemo(()=>rj({rgba:t.rgba,extraColors:t.extra_colors,effectType:t.effect_type,subtype:t.subtype,effectSize:"bar"}),[t.rgba,t.extra_colors,t.effect_type,t.subtype]),A=F=>{if(_(F),!F.trim()){C([]),P.current="",e("extra_colors","");return}const{value:S,invalid:M}=Uit(F);C(M),P.current=S,e("extra_colors",S)};return r.jsxs("div",{className:"space-y-3",children:[r.jsx("div",{className:"h-10 rounded-lg border border-bambu-dark-tertiary",style:T,"data-testid":"color-preview-banner"}),n.length>0&&r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-bambu-gray shrink-0",children:[r.jsx(Zn,{className:"w-3 h-3"}),r.jsx("span",{children:s("inventory.recentColors")})]}),r.jsx("div",{className:"flex flex-wrap gap-1.5",children:n.map(F=>r.jsx("button",{type:"button",onClick:()=>p(F.hex,F.name),className:`w-6 h-6 rounded border-2 transition-all hover:scale-110 ${m(F.hex)?"border-bambu-green ring-1 ring-bambu-green/30 scale-110":"border-bambu-dark-tertiary"}`,style:{backgroundColor:`#${F.hex}`},title:F.name},F.hex))})]}),r.jsxs("div",{className:"relative",children:[r.jsx(Sr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50 pointer-events-none"}),r.jsx("input",{type:"text",className:"w-full pl-9 pr-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green",placeholder:s("inventory.searchColors"),value:c,onChange:F=>d(F.target.value)})]}),w?r.jsxs("div",{className:"space-y-1.5",children:[r.jsx("span",{className:"text-xs text-bambu-gray",children:c?s("inventory.searchResults"):`${t.brand}${t.material?` ${t.material}`:""}`}),r.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[b.map(F=>r.jsx("button",{type:"button",onClick:()=>p(F.hex,F.name),className:`w-6 h-6 rounded border-2 transition-all hover:scale-110 hover:z-20 relative group ${m(F.hex)?"border-bambu-green ring-1 ring-bambu-green/30 scale-110":"border-bambu-dark-tertiary"}`,style:{backgroundColor:`#${F.hex}`},title:F.manufacturer&&F.material?`${F.name} (${F.manufacturer} — ${F.material})`:F.manufacturer?`${F.name} (${F.manufacturer})`:F.name,children:r.jsx("span",{className:"absolute -bottom-7 left-1/2 -translate-x-1/2 px-2 py-0.5 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-xs whitespace-nowrap opacity-0 group-hover:opacity-100 transition-opacity pointer-events-none z-20 shadow-lg text-white",children:F.manufacturer&&F.material?`${F.name} (${F.manufacturer} — ${F.material})`:F.manufacturer?`${F.name} (${F.manufacturer})`:F.name})},`${F.hex}-${F.name}-${F.manufacturer??""}`)),b.length===0&&r.jsx("p",{className:"text-sm text-bambu-gray py-1",children:s("inventory.noColorsFound")})]})]}):r.jsxs("div",{className:"space-y-1.5",children:[r.jsxs("div",{className:"flex items-center justify-between text-xs text-bambu-gray",children:[r.jsx("span",{children:s(c?"inventory.searchResults":o?"inventory.allColors":"inventory.commonColors")}),!c&&r.jsx("button",{type:"button",onClick:()=>l(!o),className:"flex items-center gap-1 hover:text-white transition-colors",children:o?r.jsxs(r.Fragment,{children:[s("inventory.showLess")," ",r.jsx(tl,{className:"w-3 h-3"})]}):r.jsxs(r.Fragment,{children:[s("inventory.showAll")," ",r.jsx(Ln,{className:"w-3 h-3"})]})})]}),r.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[g.map(F=>r.jsx("button",{type:"button",onClick:()=>p(F.hex,F.name),className:`w-6 h-6 rounded border-2 transition-all hover:scale-110 hover:z-20 relative group ${m(F.hex)?"border-bambu-green ring-1 ring-bambu-green/30 scale-110":"border-bambu-dark-tertiary"}`,style:{backgroundColor:`#${F.hex}`},title:F.name,children:r.jsx("span",{className:"absolute -bottom-7 left-1/2 -translate-x-1/2 px-2 py-0.5 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-xs whitespace-nowrap opacity-0 group-hover:opacity-100 transition-opacity pointer-events-none z-20 shadow-lg text-white",children:F.name})},F.hex)),g.length===0&&r.jsx("p",{className:"text-sm text-bambu-gray py-1",children:s("inventory.noColorsFound")})]})]}),r.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:s("inventory.colorName")}),r.jsx("input",{type:"text",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green",placeholder:s("inventory.colorNamePlaceholder"),value:t.color_name,onChange:F=>e("color_name",F.target.value)})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:s("inventory.hexColor")}),r.jsxs("div",{className:"flex gap-2",children:[r.jsxs("div",{className:"relative flex-1",children:[r.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-bambu-gray",children:"#"}),r.jsx("input",{type:"text",className:"w-full pl-7 pr-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm font-mono uppercase focus:outline-none focus:border-bambu-green",placeholder:"RRGGBB",value:u.toUpperCase(),onChange:F=>{const S=F.target.value.replace("#","").replace(/[^0-9A-Fa-f]/g,"").toUpperCase();if(S.length>8)return;const M=S.length===8?S:S.length===7?S.substring(0,6)+"FF":S.padEnd(6,"0")+"FF";e("rgba",M)}})]}),r.jsx("input",{type:"color",className:"w-11 h-[38px] rounded-lg cursor-pointer border border-bambu-dark-tertiary shrink-0 bg-transparent",value:`#${u}`,onChange:F=>{const S=F.target.value.replace("#","").toUpperCase();e("rgba",S+"FF")},title:s("inventory.pickColor")})]})]})]}),r.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3 pt-2 border-t border-bambu-dark-tertiary/50",children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:s("inventory.extraColorsLabel")}),r.jsx("input",{type:"text",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm font-mono placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green",placeholder:s("inventory.extraColorsPlaceholder"),value:x,onChange:F=>A(F.target.value),"data-testid":"extra-colors-input"}),N.length>0&&r.jsx("p",{className:"text-xs text-red-400 mt-1",children:s("inventory.extraColorsInvalid",{tokens:N.join(", ")})}),!N.length&&r.jsx("p",{className:"text-xs text-bambu-gray/70 mt-1",children:s("inventory.extraColorsHint")})]}),r.jsxs("div",{children:[r.jsxs("label",{className:"block text-sm font-medium text-bambu-gray mb-1 flex items-center gap-1.5",children:[r.jsx(Dg,{className:"w-3.5 h-3.5"}),s("inventory.colorEffectLabel")]}),r.jsxs("div",{className:"flex gap-2 items-stretch",children:[r.jsx("select",{className:"flex-1 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:outline-none focus:border-bambu-green",value:t.effect_type,onChange:F=>e("effect_type",F.target.value),"data-testid":"effect-type-select",children:WI.map(F=>r.jsx("option",{value:F.value,children:s(F.labelKey)},F.value||"none"))}),r.jsx(rU,{rgba:t.rgba,extraColors:t.extra_colors,effectType:t.effect_type,subtype:t.subtype,effectSize:"preview",className:"w-10 h-10",shape:"square"})]})]})]})]})}function Bit({catalog:t,value:e,onChange:n,catalogId:a,onCatalogIdChange:i}){const{t:s}=kt(),[o,l]=v.useState(!1),[c,d]=v.useState(""),u=v.useRef(null),m=v.useRef(null);v.useEffect(()=>{const w=g=>{u.current&&!u.current.contains(g.target)&&l(!1)};return document.addEventListener("mousedown",w),()=>document.removeEventListener("mousedown",w)},[]),v.useEffect(()=>{if(t.length===0)return;const w=t.filter(g=>g.weight===e);if(a){const g=t.find(x=>x.id===a);if(g&&g.weight===e)return}w.length===1?i(w[0].id):w.length===0&&a!==null&&i(null)},[e,t,a,i]);const p=v.useMemo(()=>{if(!c)return t;const w=c.toLowerCase();return t.filter(g=>g.name.toLowerCase().includes(w)||g.weight.toString().includes(w))},[t,c]),f=v.useMemo(()=>t.filter(w=>w.weight===e),[t,e]),b=v.useMemo(()=>{if(o)return c;if(a){const w=t.find(g=>g.id===a);if(w)return w.name}return f.length>0?f[0].name:""},[o,c,a,t,f]);return r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:r.jsxs("span",{className:"flex items-center gap-2",children:[r.jsx(FZ,{className:"w-3.5 h-3.5 text-bambu-gray"}),s("inventory.coreWeight")]})}),r.jsxs("div",{className:"flex gap-2 items-center",children:[r.jsxs("div",{className:"flex-1 min-w-0 relative",ref:u,children:[r.jsx("input",{ref:m,type:"text",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green",placeholder:s("inventory.searchSpoolWeight"),value:b,onFocus:()=>{l(!0),d("")},onChange:w=>{d(w.target.value),l(!0)}}),o&&r.jsx("div",{className:"absolute z-50 w-full mt-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-lg max-h-64 overflow-y-auto",children:p.length===0?r.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:s("inventory.noResults")}):p.map(w=>r.jsxs("button",{type:"button",className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex justify-between items-center ${(a?w.id===a:w.weight===e)?"bg-bambu-green/10 text-bambu-green":"text-white"}`,onClick:()=>{i(w.id),n(w.weight),l(!1),d("")},children:[r.jsx("span",{className:"truncate",children:w.name}),r.jsxs("span",{className:"font-mono text-xs text-bambu-gray ml-2 shrink-0",children:[w.weight,"g"]})]},w.id))})]}),r.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[r.jsx("input",{type:"number",className:"w-16 px-2 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm text-center font-mono focus:outline-none focus:border-bambu-green",value:e,min:0,max:2e3,onChange:w=>{const g=parseInt(w.target.value);!isNaN(g)&&g>=0&&n(g)}}),r.jsx("span",{className:"text-bambu-gray text-sm",children:"g"})]})]})]})}function Xce({formData:t,updateField:e,spoolCatalog:n,currencySymbol:a,availableCategories:i,globalLowStockThreshold:s,spoolmanMode:o=!1}){const{t:l}=kt(),{showToast:c}=rn(),[d,u]=v.useState(""),[m,p]=v.useState(!1),[f,b]=v.useState(""),[w,g]=v.useState(!1),x=Math.max(0,t.label_weight-t.weight_used),_=t.core_weight+x;return v.useEffect(()=>{m||u(String(_))},[m,_]),v.useEffect(()=>{w||b(String(x))},[w,x]),r.jsxs("div",{className:"space-y-4",children:[o?r.jsx("p",{className:"text-xs text-bambu-gray px-1",children:l("inventory.spoolWeightManagedBySpoolman")}):r.jsx(Bit,{catalog:n,value:t.core_weight,onChange:N=>e("core_weight",N),catalogId:t.core_weight_catalog_id,onCatalogIdChange:N=>e("core_weight_catalog_id",N)}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:l("inventory.currentWeight")}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsxs("div",{className:"relative flex-1",children:[r.jsx("input",{type:"number",value:f,min:0,max:t.label_weight,onFocus:()=>g(!0),onChange:N=>{b(N.target.value)},onBlur:()=>{g(!1);const N=f.trim(),C=Number(N);if(!N||!Number.isFinite(C)||C<0||C>t.label_weight){b(String(x));return}const P=Math.round(C);e("weight_used",Math.max(0,t.label_weight-P)),b(String(P))},className:"w-full px-3 py-2 pr-7 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:outline-none focus:border-bambu-green"}),r.jsx("span",{className:"absolute right-2 top-1/2 -translate-y-1/2 text-xs text-bambu-gray",children:"g"})]}),r.jsxs("span",{className:"text-xs text-bambu-gray shrink-0",children:["/ ",t.label_weight,"g"]})]})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:l("inventory.measuredWeight")}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsxs("div",{className:"relative flex-1",children:[r.jsx("input",{type:"number",value:d,min:0,onFocus:()=>p(!0),onChange:N=>{u(N.target.value)},onBlur:()=>{p(!1);const N=d.trim(),C=Number(N),P=t.core_weight,T=t.core_weight+t.label_weight;if(!N||!Number.isFinite(C)||CT){c(l("inventory.measuredWeightError",{min:P,max:T}),"error"),u(String(_));return}const A=Math.round(C),F=Math.max(0,Math.min(t.label_weight,A-t.core_weight));e("weight_used",Math.max(0,t.label_weight-F)),u(String(A))},className:"w-full px-3 py-2 pr-7 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:outline-none focus:border-bambu-green"}),r.jsx("span",{className:"absolute right-2 top-1/2 -translate-y-1/2 text-xs text-bambu-gray",children:"g"})]}),r.jsxs("span",{className:"text-xs text-bambu-gray shrink-0",children:["/ ",t.core_weight+t.label_weight,"g"]})]})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:l("inventory.costPerKg","Cost per kg")}),r.jsx("div",{className:"flex items-center gap-2",children:r.jsxs("div",{className:"relative flex-1",children:[r.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-bambu-gray text-sm pointer-events-none",children:a}),r.jsx("input",{type:"number",value:t.cost_per_kg??"",min:0,step:.01,placeholder:"0.00",onChange:N=>{const C=N.target.value===""?null:parseFloat(N.target.value);e("cost_per_kg",C)},style:{paddingLeft:`${Math.max(2,a.length*.6+1)}rem`},className:"w-full py-2 pr-3 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:outline-none focus:border-bambu-green"})]})})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",htmlFor:"spool-category",children:l("inventory.category")}),r.jsx("input",{id:"spool-category",type:"text",list:"spool-category-options",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green",placeholder:l("inventory.categoryPlaceholder"),value:t.category,maxLength:50,onChange:N=>e("category",N.target.value)}),i.length>0&&r.jsx("datalist",{id:"spool-category-options",children:i.map(N=>r.jsx("option",{value:N},N))})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",htmlFor:"spool-low-stock-threshold",children:l("inventory.lowStockThresholdOverride")}),r.jsx("div",{className:"flex items-center gap-2",children:r.jsxs("div",{className:"relative flex-1",children:[r.jsx("input",{id:"spool-low-stock-threshold",type:"number",className:"w-full px-3 py-2 pr-8 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green",placeholder:String(s),value:t.low_stock_threshold_pct??"",min:1,max:99,step:1,onChange:N=>{const C=N.target.value;if(C===""){e("low_stock_threshold_pct",null);return}const P=Number(C);Number.isFinite(P)&&e("low_stock_threshold_pct",Math.min(99,Math.max(1,Math.round(P))))}}),r.jsx("span",{className:"absolute right-3 top-1/2 -translate-y-1/2 text-xs text-bambu-gray pointer-events-none",children:"%"})]})}),r.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:l("inventory.lowStockThresholdOverrideHelp",{global:s})})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:l("inventory.note")}),r.jsx("textarea",{className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green resize-none min-h-[80px]",placeholder:l("inventory.notePlaceholder"),value:t.note,onChange:N=>e("note",N.target.value)})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:l("inventory.storageLocation")}),r.jsx("input",{type:"text",maxLength:255,className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green",placeholder:l("inventory.storageLocationPlaceholder"),value:t.storage_location,onChange:N=>e("storage_location",N.target.value)})]})]})}function Hit({filaments:t,isLoading:e,selectedId:n,onSelect:a}){const{t:i}=kt(),[s,o]=v.useState(!1),[l,c]=v.useState(""),d=v.useRef(null),u=v.useRef(null),m=v.useMemo(()=>t.find(g=>g.id===n)??null,[t,n]);v.useEffect(()=>{const g=x=>{d.current&&!d.current.contains(x.target)&&(o(!1),c(""))};return document.addEventListener("mousedown",g),()=>document.removeEventListener("mousedown",g)},[]);const p=v.useMemo(()=>{const g=l.toLowerCase().trim();return g?t.filter(x=>x.name.toLowerCase().includes(g)||(x.material?.toLowerCase().includes(g)??!1)||(x.vendor?.name.toLowerCase().includes(g)??!1)||(x.color_name?.toLowerCase().includes(g)??!1)):t},[t,l]);v.useEffect(()=>{s&&u.current?.focus()},[s]);const f=()=>{o(!0),c("")},b=g=>{a(g),o(!1),c("")},w=g=>g?`#${g.replace("#","")}`:"#808080";return r.jsxs("div",{ref:d,className:"relative",children:[r.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:i("inventory.pickFromSpoolmanCatalog")}),r.jsxs("button",{type:"button",onClick:f,className:"w-full flex items-center gap-2 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-left focus:outline-none focus:border-bambu-green hover:border-bambu-gray transition-colors",children:[e?r.jsx(ut,{className:"w-4 h-4 text-bambu-gray animate-spin shrink-0"}):m?r.jsxs(r.Fragment,{children:[r.jsx("span",{className:"w-4 h-4 rounded-full shrink-0 border border-white/20",style:{backgroundColor:w(m.color_hex)},"aria-label":i("inventory.spoolmanFilamentColorSwatch")}),r.jsxs("span",{className:"text-white text-sm truncate flex-1",children:[m.vendor?.name?`${m.vendor.name} — `:"",m.name]})]}):r.jsxs(r.Fragment,{children:[r.jsx(Br,{className:"w-4 h-4 text-bambu-gray shrink-0"}),r.jsx("span",{className:"text-bambu-gray text-sm flex-1",children:i("inventory.spoolmanFilamentCatalog")})]}),r.jsx(Ln,{className:"w-4 h-4 text-bambu-gray shrink-0 ml-auto"})]}),s&&r.jsxs("div",{className:"absolute z-50 w-full mt-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl",children:[r.jsx("div",{className:"p-2 border-b border-bambu-dark-tertiary",children:r.jsx("input",{ref:u,type:"text",value:l,onChange:g=>c(g.target.value),placeholder:i("inventory.pickFromSpoolmanCatalog"),className:"w-full px-2 py-1.5 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-sm placeholder-bambu-gray focus:outline-none focus:border-bambu-green"})}),r.jsx("ul",{className:"max-h-56 overflow-y-auto py-1",children:e?r.jsxs("li",{className:"flex items-center justify-center gap-2 py-4 text-bambu-gray text-sm",children:[r.jsx(ut,{className:"w-4 h-4 animate-spin"}),r.jsx("span",{children:i("common.loading","Loading…")})]}):p.length===0?r.jsx("li",{className:"py-4 text-center text-bambu-gray text-sm",children:i("inventory.noSpoolmanFilaments")}):p.map(g=>r.jsx("li",{children:r.jsxs("button",{type:"button",onClick:()=>b(g),className:`w-full flex items-center gap-2 px-3 py-2 text-left hover:bg-bambu-dark-tertiary transition-colors ${g.id===n?"bg-bambu-dark-tertiary":""}`,children:[r.jsx("span",{className:"w-4 h-4 rounded-full shrink-0 border border-white/20",style:{backgroundColor:w(g.color_hex)},"aria-label":i("inventory.spoolmanFilamentColorSwatch")}),r.jsxs("span",{className:"flex-1 min-w-0",children:[r.jsxs("span",{className:"block text-white text-sm truncate",children:[g.vendor?.name?`${g.vendor.name} — `:"",g.name]}),r.jsxs("span",{className:"block text-bambu-gray text-xs truncate",children:[[g.material,g.color_name].filter(Boolean).join(" · "),g.weight?` · ${g.weight}g`:""]})]})]})},g.id))})]})]})}function Qce({formData:t,printersWithCalibrations:e,selectedProfiles:n,setSelectedProfiles:a,expandedPrinters:i,setExpandedPrinters:s}){const{t:o}=kt(),l=p=>{s(f=>{const b=new Set(f);return b.has(p)?b.delete(p):b.add(p),b})},c=(p,f,b)=>{const w=`${p}:${f}:${b??"null"}`,g=`${p}:${b??"null"}`;a(x=>{const _=new Set(x);if(_.has(w))_.delete(w);else{for(const N of Array.from(_)){const C=N.split(":");`${C[0]}:${C[2]}`===g&&_.delete(N)}_.add(w)}return _})},d=()=>{const p=new Set;for(const{printer:f,calibrations:b}of e){if(!f.connected)continue;const w=b.filter(x=>fF(x,t)),g=new Map;for(const x of w){const _=`${x.extruder_id??"null"}`;g.has(_)||g.set(_,[]),g.get(_).push(x)}for(const[x,_]of g)if(_.length>0){const C=[..._].sort((P,T)=>T.k_value-P.k_value)[0];p.add(`${f.id}:${C.cali_idx}:${x}`)}}a(p)};if(!t.material)return r.jsx("div",{className:"p-6 bg-bambu-dark rounded-lg text-center",children:r.jsx("p",{className:"text-bambu-gray",children:o("inventory.selectMaterialFirst")})});if(e.length===0)return r.jsx("div",{className:"p-6 bg-bambu-dark rounded-lg text-center",children:r.jsx("p",{className:"text-bambu-gray",children:o("inventory.noPrintersConfigured")})});const u=e.reduce((p,{printer:f,calibrations:b})=>f.connected?p+b.filter(w=>fF(w,t)).length:p,0),m=(p,f)=>{const b=`${p.id}:${f.cali_idx}:${f.extruder_id??"null"}`,w=n.has(b);return r.jsxs("label",{className:`flex items-center gap-3 p-3 rounded-lg cursor-pointer transition-all border ${w?"bg-bambu-green/10 border-bambu-green/30":"bg-bambu-dark border-transparent hover:bg-bambu-dark/80"}`,children:[r.jsx("input",{type:"checkbox",checked:w,onChange:()=>c(String(p.id),f.cali_idx,f.extruder_id),className:"w-4 h-4 rounded border-bambu-dark-tertiary text-bambu-green focus:ring-bambu-green"}),r.jsx("div",{className:"flex-1 min-w-0",children:r.jsx("span",{className:`text-sm font-medium ${w?"text-bambu-green":"text-white"}`,children:f.name||f.filament_id})}),r.jsx("div",{className:"flex items-center gap-2 shrink-0",children:r.jsxs("span",{className:"text-xs font-mono px-2 py-0.5 rounded bg-bambu-dark text-bambu-gray",children:["K=",f.k_value.toFixed(3)]})})]},`${f.cali_idx}-${f.extruder_id}`)};return r.jsxs("div",{className:"space-y-4",children:[r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("p",{className:"text-xs text-bambu-gray",children:[o("inventory.matchingFilter"),": ",t.brand||o("inventory.anyBrand")," / ",t.material," / ",t.subtype||o("inventory.anyVariant")]}),u>0&&r.jsxs("button",{type:"button",onClick:d,className:"flex items-center gap-1.5 px-2 py-1 text-xs bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-bambu-gray hover:text-white hover:border-bambu-green transition-colors",children:[r.jsx(Dg,{className:"w-3.5 h-3.5"}),o("inventory.autoSelect")," (",u,")"]})]}),r.jsx("div",{className:"space-y-3",children:e.map(({printer:p,calibrations:f})=>{const b=i.has(String(p.id)),w=f.filter(C=>fF(C,t)),g=w.length,x=w.some(C=>C.extruder_id!==void 0&&C.extruder_id!==null&&C.extruder_id>0),_=w.filter(C=>C.extruder_id===1),N=w.filter(C=>C.extruder_id===0||C.extruder_id===void 0||C.extruder_id===null);return r.jsxs("div",{className:"border border-bambu-dark-tertiary rounded-lg overflow-hidden",children:[r.jsxs("button",{type:"button",onClick:()=>l(String(p.id)),className:"w-full px-4 py-3 flex items-center justify-between bg-bambu-dark-secondary hover:bg-bambu-dark-tertiary transition-colors",children:[r.jsxs("div",{className:"flex items-center gap-3",children:[b?r.jsx(Ln,{className:"w-4 h-4 text-bambu-gray"}):r.jsx(Va,{className:"w-4 h-4 text-bambu-gray"}),r.jsx("span",{className:"font-medium text-white",children:p.name}),g>0?r.jsxs("span",{className:"text-xs px-2 py-0.5 rounded-full bg-bambu-green/20 text-bambu-green",children:[g," ",o(g!==1?"inventory.matches":"inventory.match")]}):r.jsx("span",{className:"text-xs px-2 py-0.5 rounded-full bg-bambu-dark-tertiary text-bambu-gray",children:o("inventory.noMatches")})]}),r.jsx("span",{className:`text-xs px-2 py-1 rounded-full ${p.connected?"bg-green-500/20 text-green-500":"bg-bambu-gray/20 text-bambu-gray"}`,children:p.connected?o("inventory.connected"):o("inventory.offline")})]}),b&&r.jsx("div",{className:"px-4 py-3 space-y-3 bg-bambu-dark border-t border-bambu-dark-tertiary",children:p.connected?g===0?r.jsx("p",{className:"text-sm text-bambu-gray italic py-2",children:o("inventory.noKProfilesMatch")}):x?r.jsxs(r.Fragment,{children:[_.length>0&&r.jsxs("div",{className:"space-y-2",children:[r.jsx("p",{className:"text-xs font-medium text-bambu-gray uppercase tracking-wide",children:o("inventory.leftNozzle")}),r.jsx("div",{className:"space-y-2",children:_.map(C=>m(p,C))})]}),N.length>0&&r.jsxs("div",{className:"space-y-2",children:[r.jsx("p",{className:"text-xs font-medium text-bambu-gray uppercase tracking-wide",children:o("inventory.rightNozzle")}),r.jsx("div",{className:"space-y-2",children:N.map(C=>m(p,C))})]})]}):r.jsx("div",{className:"space-y-2",children:w.map(C=>m(p,C))}):r.jsx("p",{className:"text-sm text-bambu-gray italic py-2",children:o("inventory.printerOffline")})})]},p.id)})}),n.size>0&&r.jsx("div",{className:"p-3 bg-bambu-green/10 border border-bambu-green/30 rounded-lg",children:r.jsxs("p",{className:"text-sm text-white",children:[r.jsx("span",{className:"font-semibold",children:n.size})," ",o("inventory.profilesSelected")]})})]})}function qit(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 $it={completed:"text-bambu-green",failed:"text-red-400",aborted:"text-yellow-400"};function Vit({spoolId:t}){const{t:e}=kt(),n=en(),{showToast:a}=rn(),{data:i,isLoading:s}=We({queryKey:["spool-usage",t],queryFn:()=>se.getSpoolUsageHistory(t)}),o=it({mutationFn:()=>se.clearSpoolUsageHistory(t),onSuccess:()=>{n.invalidateQueries({queryKey:["spool-usage",t]}),a(e("inventory.historyCleared"),"success")}});return s?r.jsx("div",{className:"flex justify-center py-4",children:r.jsx(ut,{className:"w-5 h-5 animate-spin text-bambu-green"})}):!i||i.length===0?r.jsxs("div",{className:"text-center py-4 text-bambu-gray text-sm",children:[r.jsx(Zn,{className:"w-5 h-5 mx-auto mb-2 opacity-50"}),e("inventory.noUsageHistory")]}):r.jsxs("div",{className:"space-y-2",children:[r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsx("h4",{className:"text-sm font-medium text-white",children:e("inventory.usageHistory")}),r.jsxs(Me,{variant:"ghost",size:"sm",onClick:()=>o.mutate(),disabled:o.isPending,className:"text-xs text-bambu-gray hover:text-red-400",children:[r.jsx(Jt,{className:"w-3 h-3 mr-1"}),e("inventory.clearHistory")]})]}),r.jsx("div",{className:"max-h-48 overflow-y-auto space-y-1",children:i.map(l=>r.jsxs("div",{className:"flex items-center justify-between p-2 rounded bg-bambu-dark/50 text-xs",children:[r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsx("span",{className:"text-bambu-gray",children:qit(l.created_at)}),l.print_name&&r.jsx("span",{className:"text-white ml-2 truncate",title:l.print_name,children:l.print_name})]}),r.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0 ml-2",children:[r.jsxs("span",{className:"text-white font-medium",children:[l.weight_used.toFixed(1),"g"]}),r.jsxs("span",{className:"text-bambu-gray",children:["(",l.percent_used,"%)"]}),r.jsx("span",{className:$it[l.status]||"text-bambu-gray",children:l.status})]})]},l.id))})]})}const xQ={tag_uid:null,tray_uuid:null,tag_type:null,data_origin:null};function Git({isOpen:t,onClose:e,spool:n,mode:a,printersWithCalibrations:i=[],currencySymbol:s,onSpoolsCreated:o,spoolmanMode:l=!1,spoolsQueryKey:c=["inventory-spools"]}){const{t:d}=kt(),u=en(),{showToast:m}=rn(),p=a==="edit",f=a==="copy",[b,w]=v.useState(YI),[g,x]=v.useState({}),[_,N]=v.useState("filament"),[C,P]=v.useState(!1),[T,A]=v.useState(!1),[F,S]=v.useState(!1),[M,z]=v.useState(1),[I,H]=v.useState(!1),[R,Z]=v.useState(!1),[re,J]=v.useState([]),[de,me]=v.useState(""),[ue,W]=v.useState([]),[ae,pe]=v.useState([]),[ye,Te]=v.useState([]),[$,K]=v.useState([]),[D,j]=v.useState([]),[B,X]=v.useState([]),[O,ie]=v.useState(new Set),[U,G]=v.useState(new Set),Y=i.length>0?i:B,Q=O.size,{data:oe=[],isLoading:ee,error:ge}=We({queryKey:["spoolman-inventory-filaments"],queryFn:()=>se.getSpoolmanInventoryFilaments(),enabled:l&&t,staleTime:6e4,retry:!1});v.useEffect(()=>{j(Gce())},[]),v.useEffect(()=>{t&&((async()=>{Z(!0);try{const nt=await se.getCloudStatus();if(H(nt.is_authenticated),nt.is_authenticated){const gt=await se.getFilamentPresets();J(gt)}}catch(nt){console.error("Failed to fetch cloud presets:",nt),H(!1)}finally{Z(!1)}})(),l||se.getSpoolCatalog().then(W).catch(console.error),se.getColorCatalog().then(K).catch(console.error),se.getLocalPresets().then(nt=>pe(nt.filament)).catch(console.error),se.getBuiltinFilaments().then(Te).catch(console.error),i.length===0&&(async()=>{try{const nt=await se.getPrinters(),gt=await Promise.all(nt.map(ot=>se.getPrinterStatus(ot.id).catch(()=>null))),yt=[];for(let ot=0;ot({cali_idx:cn.slot_id,filament_id:cn.filament_id,setting_id:cn.setting_id||"",name:cn.name,k_value:parseFloat(cn.k_value)||0,n_coef:parseFloat(cn.n_coef)||0,extruder_id:cn.extruder_id,nozzle_diameter:cn.nozzle_diameter}))}catch{}yt.push({printer:{...Ht,connected:Zt},calibrations:Yt})}X(yt)}catch(nt){console.error("Failed to fetch printer calibrations:",nt)}})())},[t,i.length]);const ce=v.useMemo(()=>$ce(re,new Set,ae,ye),[re,ae,ye]),le=v.useMemo(()=>{const Be=qce(re,ae),nt=$.map(yt=>yt.manufacturer?.trim()).filter(yt=>!!yt),gt=new Set([...Be,...nt]);return Array.from(gt).sort((yt,ot)=>yt.localeCompare(ot))},[re,ae,$]),q=v.useMemo(()=>{const Be=$.map(gt=>gt.material?.trim()).filter(gt=>!!gt),nt=new Set([...Uce,...Be]);return Array.from(nt).sort((gt,yt)=>gt.localeCompare(yt))},[$]),L=v.useMemo(()=>{const Be=[];for(const nt of $){const gt=nt.manufacturer?.trim(),yt=nt.material?.trim();gt&&yt&&Be.push({brand:gt,material:yt})}for(const nt of re){const gt=Jh(nt.name);gt.brand&>.material&&Be.push({brand:gt.brand,material:gt.material})}for(const nt of ae){const gt=Jh(nt.name),yt=nt.filament_vendor?.trim()||gt.brand,ot=gt.material;yt&&ot&&Be.push({brand:yt,material:ot})}return Be},[re,$,ae]),ne=v.useMemo(()=>{const Be=new Map;for(const nt of L){const gt=nt.brand.toLowerCase(),yt=nt.material.toLowerCase();Be.has(gt)||Be.set(gt,new Set),Be.get(gt).add(yt)}return Be},[L]),xe=v.useMemo(()=>{const Be=new Map;for(const nt of L){const gt=nt.brand.toLowerCase(),yt=nt.material.toLowerCase();Be.has(yt)||Be.set(yt,new Set),Be.get(yt).add(gt)}return Be},[L]),we=v.useMemo(()=>{if(!b.material)return le;const Be=b.material.toLowerCase(),nt=xe.get(Be);return!nt||nt.size===0?le:le.filter(gt=>nt.has(gt.toLowerCase()))},[le,b.material,xe]),Ne=v.useMemo(()=>{if(!b.brand)return q;const Be=b.brand.toLowerCase(),nt=ne.get(Be);return!nt||nt.size===0?q:q.filter(gt=>nt.has(gt.toLowerCase()))},[q,b.brand,ne]),ve=v.useMemo(()=>Vce(b.slicer_filament,ce),[b.slicer_filament,ce]);v.useEffect(()=>{if(t){if(n){const Be=n.rgba&&/^[0-9A-Fa-f]{8}$/.test(n.rgba)?n.rgba:"808080FF";if(w({material:n.material||"",subtype:n.subtype||"",brand:n.brand||"",color_name:n.color_name||"",rgba:Be,extra_colors:n.extra_colors||"",effect_type:n.effect_type||"",label_weight:n.label_weight||1e3,core_weight:n.core_weight||250,core_weight_catalog_id:n.core_weight_catalog_id??null,weight_used:f?0:n.weight_used||0,slicer_filament:n.slicer_filament||"",note:n.note||"",cost_per_kg:n.cost_per_kg??null,category:n.category||"",low_stock_threshold_pct:n.low_stock_threshold_pct??null,storage_location:n.storage_location||"",spoolman_filament_id:null}),me(n.slicer_filament_name||n.slicer_filament||""),n.k_profiles&&n.k_profiles.length>0){const nt=new Set;for(const gt of n.k_profiles)gt.cali_idx!==null&>.cali_idx!==void 0&&nt.add(`${gt.printer_id}:${gt.cali_idx}:${gt.extruder??"null"}`);ie(nt)}else ie(new Set)}else w(YI),me(""),ie(new Set),S(!1),z(1);x({}),N("filament"),P(!1),A(!1)}},[t,n,a,f]),v.useEffect(()=>{t&&Y.length>0&&G(new Set(Y.map(Be=>String(Be.printer.id))))},[t,Y]);const be=(Be,nt)=>{const gt=Fit.has(Be);l&>&&b.spoolman_filament_id!==null&&m(d("inventory.spoolmanFilamentUnlinked"),"info"),w(yt=>({...yt,[Be]:nt,...l&>&&yt.spoolman_filament_id!==null?{spoolman_filament_id:null}:{}})),Be==="weight_used"&&P(!0),Be==="storage_location"&&A(!0),g[Be]&&x(yt=>({...yt,[Be]:void 0}))},Ee=Be=>{const nt=Be.material||"",gt=Be.name||"",yt=nt&>.startsWith(nt)?gt.slice(nt.length).trim():gt,ot=(Be.color_hex??"").replace("#","").toUpperCase(),Ht=/^[0-9A-F]{6}$/.test(ot)?ot:"808080";w(Kt=>({...Kt,spoolman_filament_id:Be.id,material:nt,subtype:yt,brand:Be.vendor?.name||"",rgba:`${Ht}FF`,color_name:Be.color_name||"",label_weight:Be.weight??Kt.label_weight})),m(d("inventory.spoolmanFilamentSelected"),"success")},ze=Be=>{j(nt=>Wce(Be,nt))},_e=it({mutationFn:Be=>l?se.createSpoolmanInventorySpool(Be):se.createSpool(Be),onSuccess:async Be=>{Be?.id&&!await fe(Be.id)||(await u.invalidateQueries({queryKey:c}),o&&o([Be]),m(d("inventory.spoolCreated"),"success"),e())},onError:Be=>{Be instanceof _i&&Be.status===503?m(d("inventory.spoolmanUnreachable"),"error"):m(d("inventory.saveFailed"),"error")}}),Oe=it({mutationFn:({data:Be,qty:nt})=>l?se.bulkCreateSpoolmanInventorySpools(Be,nt):se.bulkCreateSpools(Be,nt),onSuccess:async Be=>{const nt=l&&"created"in Be?Be:null,gt=nt?nt.created:Be;if(O.size>0)for(const yt of gt)await fe(yt.id);await u.invalidateQueries({queryKey:c}),o&&o(gt),nt&&nt.failed_count>0?m(d("inventory.spoolsPartiallyCreated",{created:gt.length,total:nt.requested_count}),"warning"):m(d("inventory.spoolsCreated",{count:gt.length}),"success"),e()},onError:Be=>{Be instanceof _i&&Be.status===503?m(d("inventory.spoolmanUnreachable"),"error"):m(d("inventory.saveFailed"),"error")}}),Ie=it({mutationFn:Be=>l?se.updateSpoolmanInventorySpool(n.id,Be):se.updateSpool(n.id,Be),onSuccess:async()=>{n?.id&&!await fe(n.id)||(await u.invalidateQueries({queryKey:c}),m(d("inventory.spoolUpdated"),"success"),e())},onError:Be=>{Be instanceof _i&&Be.status===503?m(d("inventory.spoolmanUnreachable"),"error"):m(d("inventory.saveFailed"),"error")}}),Ke=it({mutationFn:()=>l?se.updateSpoolmanInventorySpool(n.id,xQ):se.updateSpool(n.id,xQ),onSuccess:async()=>{await u.invalidateQueries({queryKey:c}),m(d("inventory.rfidCleared","RFID tag cleared"),"success"),e()},onError:Be=>{Be instanceof _i&&Be.status===503?m(d("inventory.spoolmanUnreachable"),"error"):m(d("inventory.tagClearFailed"),"error")}}),{data:rt}=We({queryKey:["spool-assignments"],queryFn:()=>se.getAssignments(),enabled:t&&p}),st=n?rt?.find(Be=>Be.spool_id===n.id):void 0,{data:Le}=We({queryKey:["inventory-spools"],queryFn:()=>se.getSpools(!0),enabled:t}),{data:tt}=We({queryKey:["settings"],queryFn:se.getSettings,enabled:t}),Ce=(()=>{const Be=new Set;for(const nt of Le??[]){const gt=nt.category?.trim();gt&&Be.add(gt)}return Array.from(Be).sort((nt,gt)=>nt.localeCompare(gt))})(),Xe=tt?.low_stock_threshold??20,Ue=it({mutationFn:()=>{if(!st)throw new Error("No assignment");return se.unassignSpool(st.printer_id,st.ams_id,st.tray_id)},onSuccess:async()=>{await u.invalidateQueries({queryKey:["spool-assignments"]}),m(d("inventory.unassignSuccess","Spool unassigned"),"success"),e()},onError:Be=>{m(Be.message,"error")}}),fe=async Be=>{const nt=l?se.saveSpoolmanKProfiles:se.saveSpoolKProfiles;if(O.size===0)try{return await nt(Be,[]),!0}catch(ot){return console.error("Failed to save K-profiles:",ot),m(d("inventory.kProfileSaveFailed"),"warning"),!1}const gt=[];let yt=0;for(const ot of O){const[Ht,Kt,Zt]=ot.split(":"),Yt=parseInt(Ht),gn=parseInt(Kt),cn=Zt==="null"?0:parseInt(Zt),pt=Y.find(at=>at.printer.id===Yt);if(pt){const at=pt.calibrations.find(vt=>vt.cali_idx===gn);at?gt.push({printer_id:Yt,extruder:cn,nozzle_diameter:at.nozzle_diameter||"0.4",k_value:at.k_value,name:at.name||null,cali_idx:at.cali_idx,setting_id:at.setting_id||null}):yt++}else yt++}if(yt>0)return console.error(`saveKProfiles: ${yt} profile key(s) could not be resolved`,Array.from(O)),m(d("inventory.kProfileSaveFailed"),"warning"),!1;if(gt.length>0)try{return await nt(Be,gt),!0}catch(ot){return console.error("Failed to save K-profiles:",ot),m(d("inventory.kProfileSaveFailed"),"warning"),!1}return!0};if(v.useEffect(()=>{if(!t)return;const Be=nt=>{nt.key==="Escape"&&e()};return document.addEventListener("keydown",Be),()=>document.removeEventListener("keydown",Be)},[t,e]),!t)return null;const Ae=()=>{const Be=zce(b,F,l);if(!Be.isValid){x(Be.errors),(Be.errors.slicer_filament||Be.errors.material||Be.errors.brand||Be.errors.subtype)&&N("filament");return}const nt=ve?.displayName||de||null,gt={material:b.material||null,subtype:b.subtype||null,brand:b.brand||null,color_name:b.color_name||null,rgba:b.rgba||null,extra_colors:b.extra_colors||null,effect_type:b.effect_type||null,label_weight:b.label_weight,...l?{}:{core_weight:b.core_weight,core_weight_catalog_id:b.core_weight_catalog_id},slicer_filament:b.slicer_filament||null,slicer_filament_name:nt,nozzle_temp_min:null,nozzle_temp_max:null,note:b.note||null,cost_per_kg:b.cost_per_kg,category:b.category.trim()||null,low_stock_threshold_pct:b.low_stock_threshold_pct,...l?{spoolman_filament_id:b.spoolman_filament_id}:{}};(!p||C)&&(gt.weight_used=b.weight_used),(!p||T)&&(gt.storage_location=b.storage_location||null),p?Ie.mutate(gt):M>1?Oe.mutate({data:gt,qty:M}):_e.mutate(gt)},$e=_e.isPending||Oe.isPending||Ie.isPending||Ke.isPending||Ue.isPending;return r.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[r.jsx("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-sm",onClick:e}),r.jsxs("div",{className:"relative w-full max-w-xl mx-4 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl max-h-[90vh] flex flex-col",children:[r.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary flex-shrink-0",children:[r.jsx("h2",{className:"text-lg font-semibold text-white",children:d(p?"inventory.editSpool":f?"inventory.copySpool":"inventory.addSpool")}),r.jsx("button",{onClick:e,className:"p-1 text-bambu-gray hover:text-white rounded transition-colors",children:r.jsx(Bt,{className:"w-5 h-5"})})]}),a==="create"&&r.jsxs("div",{className:"flex items-center justify-between px-4 py-2 border-b border-bambu-dark-tertiary flex-shrink-0",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(Nc,{className:"w-4 h-4 text-amber-400"}),r.jsx("span",{className:"text-sm text-white",children:d("inventory.quickAdd")})]}),r.jsx("button",{type:"button",onClick:()=>{S(!F),F||N("filament")},className:`relative inline-flex h-5 w-9 items-center rounded-full transition-colors ${F?"bg-bambu-green":"bg-bambu-dark-tertiary"}`,children:r.jsx("span",{className:`inline-block h-3.5 w-3.5 rounded-full bg-white transition-transform ${F?"translate-x-4":"translate-x-0.5"}`})})]}),r.jsxs("div",{className:"flex border-b border-bambu-dark-tertiary flex-shrink-0",children:[r.jsxs("button",{onClick:()=>N("filament"),className:`flex-1 px-4 py-2.5 text-sm font-medium flex items-center justify-center gap-2 transition-colors ${_==="filament"?"text-bambu-green border-b-2 border-bambu-green":"text-bambu-gray hover:text-white"}`,children:[r.jsx(jS,{className:"w-4 h-4"}),d("inventory.filamentInfoTab")]}),!F&&r.jsxs("button",{onClick:()=>N("pa-profile"),className:`flex-1 px-4 py-2.5 text-sm font-medium flex items-center justify-center gap-2 transition-colors ${_==="pa-profile"?"text-bambu-green border-b-2 border-bambu-green":"text-bambu-gray hover:text-white"}`,children:[r.jsx(yfe,{className:"w-4 h-4"}),d("inventory.paProfileTab"),Q>0&&r.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded-full bg-bambu-green/20 text-bambu-green",children:Q})]})]}),r.jsx("div",{className:"p-4 overflow-y-auto flex-1",style:{scrollbarGutter:"stable"},children:_==="filament"?r.jsxs("div",{className:"space-y-6",children:[l&&!p&&r.jsx("div",{children:ge?r.jsx("p",{className:"text-sm text-red-400 px-1",children:d("inventory.spoolmanCatalogLoadFailed")}):r.jsx(Hit,{filaments:oe,isLoading:ee,selectedId:b.spoolman_filament_id,onSelect:Ee})}),r.jsxs("div",{children:[r.jsx("h3",{className:"text-sm font-semibold text-bambu-gray uppercase tracking-wide mb-3",children:d("inventory.filamentInfo")}),r.jsx(Kce,{formData:b,updateField:be,cloudAuthenticated:I,loadingCloudPresets:R,presetInputValue:de,setPresetInputValue:me,selectedPresetOption:ve,filamentOptions:ce,availableBrands:we,availableMaterials:Ne,quickAdd:F,quantity:M,onQuantityChange:z,errors:g})]}),r.jsxs("div",{children:[r.jsx("h3",{className:"text-sm font-semibold text-bambu-gray uppercase tracking-wide mb-3",children:d("inventory.color")}),r.jsx(Yce,{formData:b,updateField:be,recentColors:D,onColorUsed:ze,catalogColors:$})]}),r.jsxs("div",{children:[r.jsx("h3",{className:"text-sm font-semibold text-bambu-gray uppercase tracking-wide mb-3",children:d("inventory.additional")}),r.jsx(Xce,{formData:b,updateField:be,spoolCatalog:ue,currencySymbol:s,availableCategories:Ce,globalLowStockThreshold:Xe,spoolmanMode:l})]}),p&&n&&!l&&r.jsx("div",{children:r.jsx(Vit,{spoolId:n.id})})]}):r.jsx(Qce,{formData:b,updateField:be,printersWithCalibrations:Y,selectedProfiles:O,setSelectedProfiles:ie,expandedPrinters:U,setExpandedPrinters:G})}),r.jsxs("div",{className:"flex gap-2 p-4 border-t border-bambu-dark-tertiary flex-shrink-0",children:[p&&r.jsxs("div",{className:"flex gap-2 mr-auto",children:[r.jsxs(Me,{variant:"secondary",onClick:()=>Ke.mutate(),disabled:$e||!n?.tag_uid,children:[r.jsx($m,{className:"w-4 h-4"}),d("inventory.clearRfid","Clear RFID Tag")]}),r.jsxs(Me,{variant:"secondary",onClick:()=>Ue.mutate(),disabled:$e||!st,children:[r.jsx(iu,{className:"w-4 h-4"}),d("inventory.unassignSpool","Unassign")]})]}),r.jsxs("div",{className:"flex gap-2 ml-auto",children:[r.jsx(Me,{variant:"secondary",onClick:e,children:d("common.cancel")}),r.jsx(Me,{onClick:Ae,disabled:$e,children:$e?r.jsxs(r.Fragment,{children:[r.jsx(ut,{className:"w-4 h-4 animate-spin"}),d("common.saving")]}):r.jsxs(r.Fragment,{children:[r.jsx(us,{className:"w-4 h-4"}),d(p?"common.save":f?"inventory.copySpool":"inventory.addSpool")]})})]})]})]})]})}function Wit({isOpen:t,onClose:e,columns:n,defaultColumns:a,onSave:i}){const{t:s}=kt(),[o,l]=v.useState(n),[c,d]=v.useState(null),u=v.useRef(null);if(v.useEffect(()=>{t&&l(n.map(C=>({...C})))},[t,n]),v.useEffect(()=>{if(!t)return;const C=P=>{P.key==="Escape"&&e()};return window.addEventListener("keydown",C),()=>window.removeEventListener("keydown",C)},[t,e]),!t)return null;const m=C=>{l(P=>P.map((T,A)=>A===C?{...T,visible:!T.visible}:T))},p=(C,P)=>{P<0||P>=o.length||l(T=>{const A=[...T],[F]=A.splice(C,1);return A.splice(P,0,F),A})},f=(C,P)=>{u.current=P,d(P),C.dataTransfer.effectAllowed="move"},b=(C,P)=>{C.preventDefault(),C.dataTransfer.dropEffect="move";const T=u.current;T!==null&&T!==P&&(p(T,P),u.current=P,d(P))},w=C=>{C.preventDefault()},g=()=>{u.current=null,d(null)},x=()=>{l(a.map(C=>({...C})))},_=()=>{i(o),e()},N=o.filter(C=>C.visible).length;return r.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",onClick:e,children:r.jsx(Ct,{className:"w-full max-w-md max-h-[80vh] flex flex-col",onClick:C=>C.stopPropagation(),children:r.jsxs(At,{className:"p-6 flex flex-col min-h-0",children:[r.jsx("h3",{className:"text-lg font-semibold text-white mb-2",children:s("inventory.configureColumns")}),r.jsxs("p",{className:"text-sm text-bambu-gray mb-4",children:[s("inventory.configureColumnsDesc"),r.jsxs("span",{className:"ml-2 text-bambu-gray/60",children:["(",N," ",s("inventory.of")," ",o.length," ",s("inventory.visible"),")"]})]}),r.jsx("div",{className:"space-y-1 overflow-y-auto flex-1 min-h-0 pr-1",children:o.map((C,P)=>r.jsxs("div",{className:`flex items-center gap-2 p-2 rounded-lg border transition-colors ${c===P?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary bg-bambu-dark-tertiary/50"} ${C.visible?"":"opacity-50"}`,draggable:!0,onDragStart:T=>f(T,P),onDragOver:T=>b(T,P),onDrop:w,onDragEnd:g,children:[r.jsx("div",{className:"cursor-grab text-bambu-gray/50 hover:text-bambu-gray",children:r.jsx(Ph,{className:"w-4 h-4"})}),r.jsx("span",{className:"flex-1 font-medium text-sm text-white",children:C.label}),r.jsxs("div",{className:"flex items-center gap-0.5",children:[r.jsx("button",{onClick:()=>p(P,P-1),disabled:P===0,className:"p-1 rounded text-bambu-gray hover:bg-bambu-dark-secondary disabled:opacity-30 disabled:cursor-not-allowed",title:s("inventory.moveUp"),children:r.jsx(tl,{className:"w-4 h-4"})}),r.jsx("button",{onClick:()=>p(P,P+1),disabled:P===o.length-1,className:"p-1 rounded text-bambu-gray hover:bg-bambu-dark-secondary disabled:opacity-30 disabled:cursor-not-allowed",title:s("inventory.moveDown"),children:r.jsx(Ln,{className:"w-4 h-4"})})]}),r.jsx("button",{onClick:()=>m(P),className:`p-1.5 rounded transition-colors ${C.visible?"text-bambu-green hover:bg-bambu-green/10":"text-bambu-gray/50 hover:bg-bambu-dark-secondary"}`,title:C.visible?s("inventory.hideColumn"):s("inventory.showColumn"),children:C.visible?r.jsx(Dl,{className:"w-4 h-4"}):r.jsx(sb,{className:"w-4 h-4"})})]},C.id))}),r.jsxs("div",{className:"flex items-center gap-3 mt-4 pt-4 border-t border-bambu-dark-tertiary",children:[r.jsxs(Me,{variant:"secondary",onClick:x,className:"mr-auto",children:[r.jsx(gs,{className:"w-4 h-4"}),s("inventory.reset")]}),r.jsx(Me,{variant:"secondary",onClick:e,children:s("inventory.cancel")}),r.jsx(Me,{onClick:_,children:s("inventory.applyChanges")})]})]})})})}const Kit=[{value:"ams_30x15",i18nKey:"ams",fallbackLabel:"AMS holder (30 × 15 mm)",fallbackHint:"Single label per page; fits the popular AMS filament label holder."},{value:"box_40x30",i18nKey:"box40x30",fallbackLabel:"Box label (40 × 30 mm)",fallbackHint:"Single label per page; common DK/Brother roll size, good for filament-bag and storage-bin labels."},{value:"box_62x29",i18nKey:"box",fallbackLabel:"Box label (62 × 29 mm)",fallbackHint:"Single label per page; sized for Brother PT/QL and Dymo small labels."},{value:"avery_l7160",i18nKey:"averyL7160",fallbackLabel:"Avery L7160 — A4 sheet (38.1 × 63.5 mm × 21)",fallbackHint:"EU sheet stock; 21 labels per A4 page."},{value:"avery_5160",i18nKey:"avery5160",fallbackLabel:"Avery 5160 — US Letter sheet (25.4 × 66.7 mm × 30)",fallbackHint:"US sheet stock; 30 labels per Letter page."}];function Yit(t){const e=window.URL.createObjectURL(t);if(!window.open(e,"_blank","noopener,noreferrer")){const a=document.createElement("a");a.href=e,a.download="bambuddy-labels.pdf",document.body.appendChild(a),a.click(),document.body.removeChild(a)}setTimeout(()=>window.URL.revokeObjectURL(e),6e4)}function Xit(t){if(!t)return{backgroundColor:"#808080"};const e=t.replace(/^#/,"").slice(0,6);return e.length===6?{backgroundColor:`#${e}`}:{backgroundColor:"#808080"}}function Qit(t){const e=t.color_name??`${t.material}${t.subtype?` ${t.subtype}`:""}`,n=t.brand?` · ${t.brand}`:"";return`${e}${n}`}function Zit(t){return[t.color_name,t.material,t.subtype,t.brand,`#${t.id}`].filter(Boolean).join(" ").toLowerCase()}function Jit({isOpen:t,onClose:e,availableSpools:n,initialSelectedIds:a,spoolmanMode:i}){const{t:s}=kt(),{showToast:o}=rn(),[l,c]=v.useState(null),[d,u]=v.useState(new Set),[m,p]=v.useState(""),[f,b]=v.useState("");v.useEffect(()=>{if(t){const M=new Set(n.map(z=>z.id));u(new Set(a.filter(z=>M.has(z)))),p(""),b(""),c(null)}},[t]);const w=v.useMemo(()=>[...n].sort((M,z)=>M.id-z.id),[n]),g=v.useMemo(()=>{const M=new Set;for(const z of w)z.material&&M.add(z.material.toUpperCase());return[...M].sort()},[w]),x=v.useMemo(()=>{const M=m.trim().toLowerCase();return w.filter(z=>!(f&&(z.material||"").toUpperCase()!==f||M&&!Zit(z).includes(M)))},[w,m,f]),_=x.length>0&&x.every(M=>d.has(M.id));if(!t)return null;const N=d.size,C=N===0;function P(M){u(z=>{const I=new Set(z);return I.has(M)?I.delete(M):I.add(M),I})}function T(){u(M=>{const z=new Set(M);for(const I of x)z.add(I.id);return z})}function A(){u(M=>{const z=new Set(M);for(const I of x)z.delete(I.id);return z})}function F(){u(new Set)}async function S(M){if(C||l)return;const z=[...d].sort((I,H)=>I-H);c(M);try{const I=i?await se.printSpoolmanSpoolLabels({spool_ids:z,template:M}):await se.printSpoolLabels({spool_ids:z,template:M});Yit(I),e()}catch(I){const H=I instanceof Error?I.message:String(I);o(s("inventory.labels.error","Could not generate labels: {{msg}}",{msg:H}),"error")}finally{c(null)}}return r.jsxs("div",{className:"fixed inset-0 z-50 flex items-start sm:items-center justify-center p-4 overflow-y-auto",children:[r.jsx("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-sm",onClick:e}),r.jsxs("div",{className:"relative w-full max-w-3xl bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl max-h-[90vh] overflow-hidden flex flex-col my-auto",children:[r.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(pr,{className:"w-5 h-5 text-bambu-green"}),r.jsx("h2",{className:"text-lg font-semibold text-white",children:s("inventory.labels.title","Print spool labels")}),N>0&&r.jsxs("span",{className:"text-sm text-bambu-gray",children:["(",s("inventory.labels.selectedCount","{{count}} selected",{count:N}),")"]})]}),r.jsx("button",{onClick:e,className:"p-1 text-bambu-gray hover:text-white rounded transition-colors","aria-label":s("common.close","Close"),children:r.jsx(Bt,{className:"w-5 h-5"})})]}),r.jsxs("div",{className:"p-4 space-y-2 border-b border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"relative",children:[r.jsx(Sr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"}),r.jsx("input",{type:"search",value:m,onChange:M=>p(M.target.value),placeholder:s("inventory.labels.searchPlaceholder","Search name, brand, or #ID"),className:"w-full pl-9 pr-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray focus:outline-none focus:border-bambu-green"})]}),g.length>1&&r.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[r.jsx("span",{className:"text-xs text-bambu-gray mr-1",children:s("inventory.labels.filterByMaterial","Material:")}),r.jsx("button",{type:"button",onClick:()=>b(""),className:`px-2 py-0.5 text-xs rounded-full border transition ${f===""?"bg-bambu-green text-bambu-dark border-bambu-green":"bg-bambu-dark text-bambu-gray border-bambu-dark-tertiary hover:border-bambu-gray"}`,children:s("inventory.labels.allMaterials","All")}),g.map(M=>r.jsx("button",{type:"button",onClick:()=>b(M),className:`px-2 py-0.5 text-xs rounded-full border transition ${f===M?"bg-bambu-green text-bambu-dark border-bambu-green":"bg-bambu-dark text-bambu-gray border-bambu-dark-tertiary hover:border-bambu-gray"}`,children:M},M))]})]}),r.jsxs("div",{className:"px-4 pt-3 pb-2 flex items-center justify-between gap-3 flex-wrap",children:[r.jsx("span",{className:"text-sm text-bambu-gray",children:s("inventory.labels.pickSpools","Pick which spools to print labels for:")}),r.jsxs("div",{className:"flex items-center gap-3 text-xs",children:[r.jsx("button",{type:"button",onClick:_?A:T,disabled:x.length===0,className:"text-bambu-green hover:underline disabled:opacity-50 disabled:no-underline disabled:cursor-not-allowed",children:_?s("inventory.labels.deselectVisible","Deselect visible"):s("inventory.labels.selectVisible","Select all visible ({{count}})",{count:x.length})}),r.jsx("button",{type:"button",onClick:F,disabled:N===0,className:"text-bambu-gray hover:text-white hover:underline disabled:opacity-50 disabled:no-underline disabled:cursor-not-allowed",children:s("inventory.labels.clearAll","Clear all")})]})]}),r.jsx("div",{className:"flex-1 overflow-y-auto px-2 pb-2 min-h-0",children:x.length===0?r.jsx("div",{className:"text-center text-sm text-bambu-gray py-6",children:w.length===0?s("inventory.labels.noSpoolsToShow","No spools to show. Adjust your filter and try again."):s("inventory.labels.noMatches","No spools match the current search or filter.")}):r.jsx("ul",{className:"space-y-0.5",children:x.map(M=>{const z=d.has(M.id);return r.jsx("li",{children:r.jsxs("label",{className:"flex items-center gap-3 px-2 py-1.5 rounded hover:bg-bambu-dark-tertiary/50 cursor-pointer",children:[z?r.jsx(bs,{className:"w-4 h-4 text-bambu-green shrink-0"}):r.jsx(so,{className:"w-4 h-4 text-bambu-gray shrink-0"}),r.jsx("input",{type:"checkbox",checked:z,onChange:()=>P(M.id),className:"sr-only"}),r.jsx("span",{className:"w-4 h-4 rounded border border-black/20 shrink-0",style:Xit(M.rgba)}),r.jsx("span",{className:"flex-1 min-w-0 truncate text-sm text-white",children:Qit(M)}),r.jsxs("span",{className:"text-xs font-mono text-bambu-gray shrink-0",children:["#",M.id]})]})},M.id)})})}),r.jsx("div",{className:"px-3 pt-2 pb-2 grid grid-cols-1 sm:grid-cols-2 gap-2 border-t border-bambu-dark-tertiary",children:Kit.map(M=>{const z=l===M.value,I=s(`inventory.labels.templates.${M.i18nKey}.label`,M.fallbackLabel),H=s(`inventory.labels.templates.${M.i18nKey}.hint`,M.fallbackHint);return r.jsxs("button",{disabled:C||l!==null,onClick:()=>S(M.value),title:`${I} — ${H}`,className:"w-full text-left p-2.5 rounded-lg border border-bambu-dark-tertiary bg-bambu-dark hover:border-bambu-green hover:bg-bambu-green/10 disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:border-bambu-dark-tertiary disabled:hover:bg-bambu-dark transition flex items-center gap-3",children:[r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsx("div",{className:"font-medium text-white text-sm truncate",children:I}),r.jsx("div",{className:"text-xs text-bambu-gray mt-0.5 truncate",children:H})]}),z&&r.jsx(ut,{className:"w-4 h-4 animate-spin text-bambu-green shrink-0"})]},M.value)})}),r.jsx("div",{className:"flex justify-end gap-2 px-5 py-2 border-t border-bambu-dark-tertiary",children:r.jsx(Me,{variant:"secondary",onClick:e,disabled:l!==null,children:s("common.cancel","Cancel")})})]})]})}function yQ(t){return`${t.material}|${t.subtype||""}|${t.brand||""}|${t.color_name||""}|${t.rgba||""}|${t.extra_colors||""}|${t.effect_type||""}|${t.label_weight}`}const Zce="bambuddy-inventory-columns",HN=[{id:"id",label:"#",visible:!0},{id:"added_time",label:"Added",visible:!0},{id:"encode_time",label:"Encoded",visible:!1},{id:"last_used_time",label:"Last Used",visible:!1},{id:"rgba",label:"Color",visible:!0},{id:"material",label:"Material",visible:!0},{id:"subtype",label:"Subtype",visible:!0},{id:"color_name",label:"Color Name",visible:!1},{id:"brand",label:"Brand",visible:!0},{id:"slicer_filament",label:"Slicer Filament",visible:!1},{id:"location",label:"Location",visible:!0},{id:"storage_location",label:"Storage Location",visible:!1},{id:"label_weight",label:"Label",visible:!0},{id:"net",label:"Net",visible:!0},{id:"gross",label:"Gross",visible:!1},{id:"added_full",label:"Full",visible:!1},{id:"used",label:"Used",visible:!1},{id:"printed_total",label:"Printed Total",visible:!1},{id:"printed_since_weight",label:"Printed Since Weight",visible:!1},{id:"note",label:"Note",visible:!1},{id:"pa_k",label:"PA(K)",visible:!0},{id:"tag_id",label:"Tag ID",visible:!1},{id:"data_origin",label:"Data Origin",visible:!1},{id:"tag_type",label:"Linked Tag Type",visible:!1},{id:"stock",label:"Stock",visible:!1},{id:"remaining",label:"Remaining",visible:!0},{id:"spool_name",label:"Spool",visible:!1},{id:"cost_per_kg",label:"Cost/kg",visible:!1},{id:"weight_check",label:"Weight Check",visible:!1}];function est(){try{const t=localStorage.getItem(Zce);if(t){const e=JSON.parse(t),n=new Set(HN.map(o=>o.id)),a=new Set(e.map(o=>o.id)),i=e.filter(o=>n.has(o.id)),s=HN.filter(o=>!a.has(o.id));return[...i,...s]}}catch{}return HN.map(t=>({...t}))}function tst(t){try{localStorage.setItem(Zce,JSON.stringify(t))}catch{}}function au(t,e=!1){return e&&t>=1e3?`${(t/1e3).toFixed(1)}kg`:`${Math.round(t)}g`}const nst={PLA:"bg-green-500/20 text-green-400",ABS:"bg-red-500/20 text-red-400",PETG:"bg-blue-500/20 text-blue-400",TPU:"bg-purple-500/20 text-purple-400",ASA:"bg-orange-500/20 text-orange-400",PA:"bg-yellow-500/20 text-yellow-400",PC:"bg-cyan-500/20 text-cyan-400",PET:"bg-sky-500/20 text-sky-400"};function gF(t,e="system"){if(!t)return"-";const n=Xn(t);return n?YF(n,e):"-"}const rst={id:()=>"#",added_time:()=>"Added",encode_time:()=>"Encoded",last_used_time:()=>"Last Used",rgba:t=>t("inventory.color"),material:t=>t("inventory.material"),subtype:t=>t("inventory.subtype"),color_name:t=>t("inventory.colorName"),brand:t=>t("inventory.brand"),slicer_filament:t=>t("inventory.slicerFilament"),location:()=>"Location",storage_location:t=>t("inventory.storageLocation"),label_weight:t=>t("inventory.labelWeight"),net:t=>t("inventory.net"),gross:()=>"Gross",added_full:()=>"Full",used:t=>t("inventory.weightUsed"),printed_total:()=>"Printed Total",printed_since_weight:()=>"Printed Since Weight",note:t=>t("inventory.note"),pa_k:()=>"PA(K)",tag_id:()=>"Tag ID",data_origin:()=>"Data Origin",tag_type:()=>"Linked Tag Type",stock:t=>t("inventory.stock"),remaining:t=>t("inventory.remaining"),spool_name:t=>t("inventory.spoolName"),cost_per_kg:t=>t("inventory.costPerKg"),weight_check:t=>t("inventory.weightCheck")},XI={id:({spool:t})=>r.jsx("span",{className:"text-sm font-medium text-white",children:t.id}),added_time:({spool:t,dateFormat:e})=>r.jsx("span",{className:"text-sm text-bambu-gray",children:gF(t.created_at,e)}),encode_time:({spool:t,dateFormat:e})=>r.jsx("span",{className:"text-sm text-bambu-gray",children:gF(t.encode_time,e)}),last_used_time:({spool:t,dateFormat:e})=>r.jsx("span",{className:"text-sm text-bambu-gray",children:t.last_used?gF(t.last_used,e):"Never"}),rgba:({spool:t})=>r.jsx("div",{className:"flex items-center justify-center",children:r.jsx(rU,{rgba:t.rgba,extraColors:t.extra_colors,effectType:t.effect_type,effectSize:"table",subtype:t.subtype})}),material:({spool:t})=>r.jsx("span",{className:"text-sm text-white",children:t.material}),subtype:({spool:t})=>r.jsx("span",{className:"text-sm text-bambu-gray",children:t.subtype||"-"}),color_name:({spool:t})=>r.jsx("span",{className:"text-sm text-bambu-gray",children:PT(t.color_name,t.rgba)||"-"}),brand:({spool:t})=>r.jsx("span",{className:"text-sm text-bambu-gray",children:t.brand||"-"}),slicer_filament:({spool:t})=>r.jsx("span",{className:"text-sm text-bambu-gray",title:t.slicer_filament||void 0,children:t.slicer_filament_name||t.slicer_filament||"-"}),location:({spool:t,assignmentMap:e})=>{const n=e[t.id];if(!n)return r.jsx("span",{className:"text-sm text-bambu-gray",children:"-"});const a=n.printer_name||`Printer ${n.printer_id}`,i=n.ams_id===254||n.ams_id===255,s=!i&&n.ams_id>=128,o=c_(n.ams_id,n.tray_id,s,i);return r.jsxs("span",{className:"inline-flex items-center px-1.5 py-0.5 rounded text-xs font-medium bg-purple-500/20 text-purple-400",children:[a," ",o,n.ams_label?` (${n.ams_label})`:""]})},storage_location:({spool:t})=>t.storage_location?r.jsx("span",{className:"inline-flex items-center px-1.5 py-0.5 rounded text-xs font-medium bg-blue-500/20 text-blue-400",children:t.storage_location}):r.jsx("span",{className:"text-sm text-bambu-gray",children:"-"}),label_weight:({spool:t})=>r.jsx("span",{className:"text-sm text-white",children:au(t.label_weight)}),net:({remaining:t})=>r.jsx("span",{className:"text-sm text-white",children:au(t)}),gross:({spool:t,remaining:e})=>r.jsx("span",{className:"text-sm text-bambu-gray",children:au(e+t.core_weight)}),added_full:({spool:t})=>r.jsx("span",{className:"text-sm text-bambu-gray",children:t.added_full==null?"-":t.added_full?"Yes":"No"}),used:({spool:t})=>r.jsx("span",{className:"text-sm text-bambu-gray",children:t.weight_used>0?au(t.weight_used):"-"}),printed_total:()=>r.jsx("span",{className:"text-sm text-bambu-gray/50",children:"-"}),printed_since_weight:()=>r.jsx("span",{className:"text-sm text-bambu-gray/50",children:"-"}),note:({spool:t})=>r.jsx("span",{className:"text-sm text-bambu-gray max-w-[150px] truncate block",title:t.note||void 0,children:t.note||"-"}),pa_k:({spool:t})=>(t.k_profiles?.length??0)===0?r.jsx("span",{className:"text-sm text-bambu-gray",children:"-"}):r.jsx("span",{className:"inline-flex items-center px-1.5 py-0.5 rounded text-xs font-medium bg-bambu-green/20 text-bambu-green",children:"K"}),tag_id:({spool:t})=>{const e=t.tag_uid||t.tray_uuid;return e?r.jsx("span",{className:"text-sm text-bambu-gray font-mono",title:e,children:e.length>12?`${e.slice(0,6)}...${e.slice(-4)}`:e}):r.jsx("span",{className:"text-sm text-bambu-gray/50",children:"-"})},data_origin:({spool:t})=>r.jsx("span",{className:"text-sm text-bambu-gray",children:t.data_origin||"-"}),tag_type:({spool:t})=>r.jsx("span",{className:"text-sm text-bambu-gray",children:t.tag_type||"-"}),stock:({spool:t,t:e})=>t.slicer_filament?r.jsx("span",{className:"text-sm text-bambu-gray",children:"-"}):r.jsx("span",{className:"inline-flex items-center px-1.5 py-0.5 rounded text-xs font-medium bg-amber-500/20 text-amber-400",children:e("inventory.stock")}),remaining:({remaining:t,pct:e})=>r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("div",{className:"flex-1 h-2 bg-bambu-dark-tertiary rounded-full overflow-hidden",children:r.jsx("div",{className:`h-full rounded-full ${e>50?"bg-bambu-green":e>20?"bg-yellow-500":"bg-red-500"}`,style:{width:`${Math.min(e,100)}%`}})}),r.jsxs("span",{className:"text-xs text-bambu-gray min-w-[40px] text-right",children:[Math.round(t),"g"]})]}),spool_name:({spool:t,catalogMap:e})=>{const n=t.core_weight_catalog_id!=null?e[t.core_weight_catalog_id]:void 0;return r.jsx("span",{className:"text-sm text-bambu-gray",children:n?.name||"-"})},cost_per_kg:({spool:t,currencySymbol:e})=>r.jsx("span",{className:"text-sm text-bambu-gray",children:t.cost_per_kg!=null?`${e}${t.cost_per_kg.toFixed(2)}`:"-"}),weight_check:({spool:t,onSyncWeight:e})=>{const n=t.last_scale_weight;if(n==null)return r.jsx("span",{className:"text-sm text-bambu-gray/50",title:"No scale measurement",children:"-"});const a=t.core_weight||0,i=Math.max(0,t.label_weight-t.weight_used)+a;let s,o;n0?`+${Math.round(s)}`:`${Math.round(s)}`,c=o?`Scale: ${Math.round(n)}g +`),N=new Blob([_],{type:"text/csv"}),C=URL.createObjectURL(N),P=document.createElement("a");P.href=C,P.download=`shopping-list-${new Date().toISOString().slice(0,10)}.csv`,P.click(),setTimeout(()=>URL.revokeObjectURL(C),100)}return r.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg overflow-hidden border border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"flex items-center justify-between px-4 py-3 border-b border-bambu-dark-tertiary bg-bambu-dark-tertiary/30",children:[r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx(lb,{className:"w-4 h-4 text-bambu-green"}),r.jsx("h3",{className:"text-sm font-semibold text-white",children:l("forecast.shoppingList")}),r.jsx("span",{className:"text-xs text-bambu-gray",children:l("forecast.shoppingListItems",{count:t.length})}),t.length>0&&r.jsxs("div",{className:"flex bg-bambu-dark-tertiary rounded-md p-0.5 ml-1",children:[r.jsxs("button",{onClick:()=>u("list"),className:`flex items-center gap-1.5 px-2 py-0.5 text-xs font-medium rounded transition-colors ${d==="list"?"bg-bambu-dark-secondary text-white shadow":"text-bambu-gray hover:text-white"}`,children:[r.jsx(Br,{className:"w-3 h-3"}),l("forecast.listView")]}),r.jsxs("button",{onClick:()=>u("logistics"),className:`flex items-center gap-1.5 px-2 py-0.5 text-xs font-medium rounded transition-colors ${d==="logistics"?"bg-bambu-dark-secondary text-white shadow":"text-bambu-gray hover:text-white"}`,children:[r.jsx(Hfe,{className:"w-3 h-3"}),l("forecast.logisticsView"),b.length>0&&r.jsx("span",{className:"w-3.5 h-3.5 rounded-full bg-red-500 text-white text-[9px] font-bold flex items-center justify-center",children:b.length})]})]})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[t.length>0&&r.jsxs(r.Fragment,{children:[r.jsxs("button",{onClick:w,className:"flex items-center gap-1.5 text-xs text-bambu-gray hover:text-white transition-colors px-2 py-1 rounded border border-bambu-dark-tertiary hover:bg-bambu-dark-tertiary",children:[r.jsx(Yr,{className:"w-3 h-3"}),l("forecast.downloadCsv")]}),a&&r.jsx("button",{onClick:o,className:"text-xs text-red-400 hover:text-red-300 transition-colors px-2 py-1 rounded border border-red-500/20 hover:bg-red-500/10",children:l("forecast.clearAll")})]}),r.jsx("button",{onClick:i,className:"p-1 text-bambu-gray hover:text-white transition-colors",children:r.jsx(Bt,{className:"w-4 h-4"})})]})]}),t.length===0?r.jsxs("div",{className:"flex flex-col items-center py-8 text-bambu-gray",children:[r.jsx(Br,{className:"w-8 h-8 mb-2 opacity-30"}),r.jsx("p",{className:"text-sm",children:l("forecast.shoppingListEmpty")})]}):d==="list"?r.jsx("div",{className:"overflow-x-auto",children:r.jsxs("table",{className:"w-full",children:[r.jsx("thead",{children:r.jsxs("tr",{className:"border-b border-bambu-dark-tertiary bg-bambu-dark-tertiary/20",children:[r.jsx("th",{className:"px-4 py-2 text-left text-xs font-medium text-bambu-gray uppercase tracking-wide",children:l("forecast.qty")}),r.jsx("th",{className:"px-4 py-2 text-left text-xs font-medium text-bambu-gray uppercase tracking-wide",children:l("forecast.material")}),r.jsx("th",{className:"px-4 py-2 text-left text-xs font-medium text-bambu-gray uppercase tracking-wide",children:l("forecast.weight")}),r.jsx("th",{className:"px-4 py-2 text-left text-xs font-medium text-bambu-gray uppercase tracking-wide",children:l("forecast.leadTime")}),r.jsx("th",{className:"px-4 py-2 text-left text-xs font-medium text-bambu-gray uppercase tracking-wide",children:l("forecast.expectedRestock")}),r.jsx("th",{className:"px-4 py-2 text-left text-xs font-medium text-bambu-gray uppercase tracking-wide",children:l("forecast.status")}),r.jsx("th",{className:"px-4 py-2 text-left text-xs font-medium text-bambu-gray uppercase tracking-wide",children:l("forecast.note")}),r.jsx("th",{className:"px-4 py-2 text-right text-xs font-medium text-bambu-gray uppercase tracking-wide",children:l("forecast.actions")})]})}),r.jsx("tbody",{className:"divide-y divide-bambu-dark-tertiary",children:t.map(g=>{const x=[g.brand,g.material,g.subtype].filter(Boolean).join(" "),_=b.some(z=>z.item.id===g.id),N=p.get(ww(g.material,g.subtype,g.brand))??null,C=N&&N.totalSpools>0?N.totalLabelG/N.totalSpools:1e3,P=Math.round(g.quantity_spools*C),T=N?.effectiveLeadTimeDays??n??0,A=T>0?Um(new Date,T):null,F=g.status==="purchased"||g.status==="received",S=g.status==="received",M=m.isPending;return r.jsxs("tr",{className:`hover:bg-bambu-dark-tertiary/30 transition-colors ${_&&!F?"bg-red-500/5":""}`,children:[r.jsx("td",{className:"px-4 py-2.5",children:r.jsxs("span",{className:"text-sm font-semibold text-bambu-green",children:[g.quantity_spools,"×"]})}),r.jsx("td",{className:"px-4 py-2.5",children:r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("span",{className:"text-sm text-white",children:x}),_&&!F&&r.jsx(Nn,{className:"w-3.5 h-3.5 text-red-400 flex-shrink-0","aria-label":l("forecast.stockBreakBefore")})]})}),r.jsx("td",{className:"px-4 py-2.5",children:r.jsx("span",{className:"text-sm text-white",children:P>=1e3?`${(P/1e3).toFixed(1)}kg`:`${P}g`})}),r.jsx("td",{className:"px-4 py-2.5",children:r.jsx("span",{className:"text-sm text-bambu-gray",children:T>0?`${T}d`:"—"})}),r.jsx("td",{className:"px-4 py-2.5",children:r.jsx("span",{className:"text-sm text-bambu-gray",children:A?wS(A):"—"})}),r.jsx("td",{className:"px-4 py-2.5",children:r.jsx("span",{className:`inline-flex items-center px-2 py-0.5 rounded text-xs font-medium ${S?"bg-bambu-green/20 text-bambu-green":F?"bg-blue-400/20 text-blue-400":"bg-bambu-dark-tertiary text-bambu-gray"}`,children:l(S?"forecast.received":F?"forecast.purchased":"forecast.pending")})}),r.jsx("td",{className:"px-4 py-2.5",children:r.jsx("span",{className:"text-xs text-bambu-gray",children:g.note||"—"})}),r.jsx("td",{className:"px-4 py-2.5",children:r.jsx("div",{className:"flex items-center justify-end gap-1",children:a&&r.jsxs(r.Fragment,{children:[r.jsx("button",{onClick:()=>m.mutate({id:g.id,status:F?"pending":"purchased"}),disabled:M||S,title:l(F?"forecast.resetToPending":"forecast.markPurchased"),className:`p-1 rounded transition-colors disabled:opacity-30 ${F?"text-blue-400 hover:text-bambu-gray":"text-bambu-gray hover:text-blue-400"}`,children:F?r.jsx(gs,{className:"w-3.5 h-3.5"}):r.jsx(Tge,{className:"w-3.5 h-3.5"})}),r.jsx("button",{onClick:()=>m.mutate({id:g.id,status:"received",item:g,avgSpoolG:C}),disabled:M||!F||S,title:l("forecast.markReceived"),className:"p-1 rounded transition-colors text-bambu-gray hover:text-bambu-green disabled:opacity-30",children:r.jsx(Axe,{className:"w-3.5 h-3.5"})}),r.jsx("button",{onClick:()=>s(g.id),className:"p-1 text-bambu-gray hover:text-red-400 transition-colors",title:l("forecast.remove"),children:r.jsx(Jt,{className:"w-3.5 h-3.5"})})]})})})]},g.id)})})]})}):r.jsx("div",{className:"divide-y divide-bambu-dark-tertiary",children:f.filter(({item:g})=>g.status!=="received").map(({item:g,forecast:x})=>r.jsx(Eit,{item:g,forecast:x,globalLeadTime:n,canWrite:a,onRemove:()=>s(g.id)},g.id))})]})}function Eit({item:t,forecast:e,globalLeadTime:n,canWrite:a,onRemove:i}){const{t:s}=kt(),o=[t.brand,t.material,t.subtype].filter(Boolean).join(" "),l=v.useMemo(()=>{if(!e||e.dailyRateG===null||e.dailyRateG<=0)return null;const u=e.dailyRateG,m=e.effectiveLeadTimeDays,p=e.totalSpools>0?e.totalLabelG/e.totalSpools:1e3,f=t.quantity_spools*p,b=Math.max(0,e.totalRemainingG-u*m),w=b+f,g=Math.ceil(w/u),x=Math.min(m+g+5,365),_=[];for(let N=0;N<=x;N++){const C=Sw(Um(new Date,N));if(N===m)_.push({day:N,label:C,stock:Math.round(b),rop:Math.round(e.reorderPointG),safetyStock:Math.round(e.safetyStockG)}),_.push({day:N,label:C,stock:Math.round(w),rop:Math.round(e.reorderPointG),safetyStock:Math.round(e.safetyStockG),arrival:!0});else{const P=N{if(!e||e.dailyRateG===null||e.dailyRateG<=0)return null;const u=Math.floor(e.totalRemainingG/e.dailyRateG);return uu>=1e3?`${(u/1e3).toFixed(1)}kg`:`${u}g`,width:44}),r.jsx(nu,{contentStyle:{background:"#1a1a2e",border:"1px solid #374151",borderRadius:8,fontSize:11},labelStyle:{color:"#9CA3AF"},formatter:(u,m)=>typeof u!="number"?"":m==="stock"?`${u}g — ${s("forecast.stock")}`:m==="rop"?`${u}g — ${s("forecast.reorderPoint")}`:m==="safetyStock"?`${u}g — ${s("forecast.safetyMarginLabel")}`:`${u}`}),r.jsx(DA,{type:"linear",dataKey:"stock",stroke:"#1DB954",strokeWidth:2,fill:`url(#cart-post-${t.id})`,dot:!1,activeDot:{r:3}}),e.reorderPointG>0&&r.jsx(ru,{y:e.reorderPointG,stroke:"#F59E0B",strokeDasharray:"5 3",strokeOpacity:.8,label:{value:"ROP",position:"insideTopRight",fill:"#F59E0B",fontSize:9}}),e.safetyStockG>0&&r.jsx(ru,{y:e.safetyStockG,stroke:"#6B7280",strokeDasharray:"3 3",strokeOpacity:.6,label:{value:"SS",position:"insideTopRight",fill:"#6B7280",fontSize:9}}),r.jsx(ru,{x:Sw(Um(new Date,l.lt)),stroke:"#3B82F6",strokeWidth:1.5,strokeDasharray:"4 3",strokeOpacity:.9,label:{value:`+${l.arrivalG>=1e3?`${(l.arrivalG/1e3).toFixed(1)}kg`:`${Math.round(l.arrivalG)}g`} arrives (d${l.lt})`,position:"insideTopLeft",fill:"#3B82F6",fontSize:9}}),c!==null&&r.jsx(ru,{x:Sw(Um(new Date,c)),stroke:"#EF4444",strokeWidth:1.5,strokeOpacity:.9,label:{value:"OUT",position:"insideTopLeft",fill:"#EF4444",fontSize:9}})]})}),r.jsxs("div",{className:"flex flex-wrap items-center gap-3 mt-2 text-[10px] text-bambu-gray",children:[r.jsxs("span",{className:"flex items-center gap-1",children:[r.jsx("span",{className:"inline-block w-4 border-t-2 border-yellow-400 border-dashed"})," ",s("forecast.ropLabel")]}),r.jsxs("span",{className:"flex items-center gap-1",children:[r.jsx("span",{className:"inline-block w-4 border-t border-bambu-gray border-dashed"})," ",s("forecast.safetyStockLegend")]}),r.jsxs("span",{className:"flex items-center gap-1",children:[r.jsx("span",{className:"inline-block w-4 border-t-2 border-blue-400 border-dashed"})," ",s("forecast.stockArrivalLegend")]}),d&&r.jsxs("span",{className:"flex items-center gap-1 text-red-400",children:[r.jsx("span",{className:"inline-block w-4 border-t-2 border-red-400"})," ",s("forecast.stockoutLegend")]})]})]}):null]})}function Dit({forecast:t,onClose:e,onAdd:n}){const{t:a}=kt(),i=[t.group.brand,t.group.material,t.group.subtype].filter(Boolean).join(" "),[s,o]=v.useState("qty"),[l,c]=v.useState("1"),[d,u]=v.useState("30"),[m,p]=v.useState(""),f=v.useMemo(()=>{if(!t.dailyRateG||t.dailyRateG<=0)return null;const g=t.dailyRateG*Number(d),x=t.group.spools.length>0?t.group.spools.reduce((_,N)=>_+N.label_weight,0)/t.group.spools.length:1e3;return Math.ceil(g/x)},[t,d]),b=s==="qty"?parseInt(l,10)||1:f??1;function w(g){g.preventDefault(),n({material:t.group.material,subtype:t.group.subtype,brand:t.group.brand,quantity_spools:b,note:m||null})}return r.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm p-4",children:r.jsxs("div",{className:"bg-bambu-dark-secondary rounded-2xl border border-bambu-dark-tertiary w-full max-w-sm shadow-2xl",children:[r.jsxs("div",{className:"flex items-center justify-between px-5 pt-5 pb-4 border-b border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(lb,{className:"w-5 h-5 text-bambu-green"}),r.jsx("h2",{className:"text-base font-semibold text-white",children:a("forecast.addToCartTitle")})]}),r.jsx("button",{onClick:e,className:"p-1 text-bambu-gray hover:text-white transition-colors",children:r.jsx(Bt,{className:"w-5 h-5"})})]}),r.jsxs("form",{onSubmit:w,className:"p-5 space-y-4",children:[r.jsx("div",{className:"text-sm text-bambu-gray",children:i}),r.jsxs("div",{className:"flex bg-bambu-dark-tertiary rounded-lg p-0.5",children:[r.jsx("button",{type:"button",onClick:()=>o("qty"),className:`flex-1 py-1.5 text-xs font-medium rounded-md transition-colors ${s==="qty"?"bg-bambu-dark-secondary text-white shadow":"text-bambu-gray hover:text-white"}`,children:a("forecast.byQuantity")}),r.jsx("button",{type:"button",onClick:()=>o("duration"),className:`flex-1 py-1.5 text-xs font-medium rounded-md transition-colors ${s==="duration"?"bg-bambu-dark-secondary text-white shadow":"text-bambu-gray hover:text-white"}`,children:a("forecast.byDuration")})]}),s==="qty"?r.jsxs("div",{className:"space-y-1.5",children:[r.jsx("label",{className:"text-xs text-bambu-gray",children:a("forecast.numberOfSpools")}),r.jsx("input",{type:"number",min:1,max:99,value:l,onChange:g=>c(g.target.value),className:"w-full px-3 py-2 bg-bambu-dark-tertiary border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:outline-none focus:border-bambu-green",autoFocus:!0})]}):r.jsxs("div",{className:"space-y-2",children:[r.jsxs("div",{className:"space-y-1.5",children:[r.jsx("label",{className:"text-xs text-bambu-gray",children:a("forecast.lastHowManyDays")}),r.jsx("input",{type:"number",min:1,max:365,value:d,onChange:g=>u(g.target.value),className:"w-full px-3 py-2 bg-bambu-dark-tertiary border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:outline-none focus:border-bambu-green",autoFocus:!0})]}),t.dailyRateG!==null?r.jsxs("div",{className:"flex items-center gap-2 px-3 py-2 bg-bambu-dark-tertiary/50 rounded-lg",children:[r.jsx("span",{className:"text-xs text-bambu-gray",children:"≈"}),r.jsx("span",{className:"text-sm font-semibold text-bambu-green",children:a("forecast.spoolCount",{count:f??0})}),r.jsxs("span",{className:"text-xs text-bambu-gray",children:["at ",t.dailyRateG.toFixed(1),"g/day"]})]}):r.jsx("div",{className:"text-xs text-yellow-400 px-1",children:a("forecast.noUsageQty")})]}),r.jsxs("div",{className:"space-y-1.5",children:[r.jsx("label",{className:"text-xs text-bambu-gray",children:a("forecast.noteOptional")}),r.jsx("input",{type:"text",maxLength:200,value:m,onChange:g=>p(g.target.value),placeholder:a("forecast.notePlaceholder"),className:"w-full px-3 py-2 bg-bambu-dark-tertiary border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/40 focus:outline-none focus:border-bambu-green"})]}),r.jsxs("div",{className:"flex items-center gap-3 pt-1",children:[r.jsx("button",{type:"submit",className:"flex-1 py-2 bg-bambu-green text-white text-sm font-medium rounded-lg hover:bg-bambu-green/80 transition-colors",children:a("forecast.addNSpools",{count:b})}),r.jsx("button",{type:"button",onClick:e,className:"px-4 py-2 text-sm text-bambu-gray hover:text-white border border-bambu-dark-tertiary rounded-lg transition-colors",children:a("forecast.cancel")})]})]})]})})}const YI={material:"",subtype:"",brand:"",color_name:"",rgba:"808080FF",extra_colors:"",effect_type:"",label_weight:1e3,core_weight:250,core_weight_catalog_id:null,weight_used:0,slicer_filament:"",note:"",cost_per_kg:null,category:"",low_stock_threshold_pct:null,storage_location:"",spoolman_filament_id:null},Fit=new Set(["material","subtype","brand","rgba","color_name","label_weight"]);function zce(t,e=!1,n=!1){const a={};return e||n?(!t.material&&!t.spoolman_filament_id&&(a.material="Material is required"),{isValid:Object.keys(a).length===0,errors:a}):(t.slicer_filament||(a.slicer_filament="Slicer preset is required"),t.material||(a.material="Material is required"),t.brand||(a.brand="Brand is required"),t.subtype||(a.subtype="Subtype is required"),{isValid:Object.keys(a).length===0,errors:a})}const Uce=["PLA","PETG","ABS","TPU","ASA","PC","PA","PVA","HIPS","PA-CF","PETG-CF","PLA-CF"],Lit=["Bambu","PolyLite","PolyTerra","eSUN","Overture","Fiberon","SUNLU","Inland","Hatchbox","Generic"],_w=["Basic","Matte","Silk","Silk+","Tough","Tough+","HF","High Flow","Engineering","Galaxy","Glow","Marble","Metal","Rainbow","Sparkle","Wood","Translucent","Transparent","Clear","Lite","Pro","Plus","Max","Super","Ultra","Flex","Soft","Hard","Strong","Impact","Heat Resistant","UV Resistant","ESD","Conductive","Magnetic","Gradient","Dual Color","Tri Color","Multicolor"],Bce=[{name:"Black",hex:"000000"},{name:"White",hex:"FFFFFF"},{name:"Gray",hex:"808080"},{name:"Red",hex:"FF0000"},{name:"Orange",hex:"FFA500"},{name:"Yellow",hex:"FFFF00"},{name:"Green",hex:"00AE42"},{name:"Blue",hex:"0066FF"},{name:"Purple",hex:"8B00FF"},{name:"Pink",hex:"FF69B4"},{name:"Brown",hex:"8B4513"},{name:"Silver",hex:"C0C0C0"}],Rit=[{name:"Dark Red",hex:"8B0000"},{name:"Crimson",hex:"DC143C"},{name:"Coral",hex:"FF7F50"},{name:"Salmon",hex:"FA8072"},{name:"Dark Orange",hex:"FF8C00"},{name:"Peach",hex:"FFDAB9"},{name:"Gold",hex:"FFD700"},{name:"Khaki",hex:"F0E68C"},{name:"Lemon",hex:"FFF44F"},{name:"Lime",hex:"32CD32"},{name:"Forest Green",hex:"228B22"},{name:"Olive",hex:"808000"},{name:"Mint",hex:"98FF98"},{name:"Teal",hex:"008080"},{name:"Navy",hex:"000080"},{name:"Sky Blue",hex:"87CEEB"},{name:"Royal Blue",hex:"4169E1"},{name:"Cyan",hex:"00FFFF"},{name:"Turquoise",hex:"40E0D0"},{name:"Violet",hex:"EE82EE"},{name:"Magenta",hex:"FF00FF"},{name:"Indigo",hex:"4B0082"},{name:"Lavender",hex:"E6E6FA"},{name:"Plum",hex:"DDA0DD"},{name:"Hot Pink",hex:"FF69B4"},{name:"Rose",hex:"FF007F"},{name:"Blush",hex:"FFB6C1"},{name:"Chocolate",hex:"D2691E"},{name:"Tan",hex:"D2B48C"},{name:"Beige",hex:"F5F5DC"},{name:"Maroon",hex:"800000"},{name:"Dark Gray",hex:"404040"},{name:"Light Gray",hex:"D3D3D3"},{name:"Charcoal",hex:"36454F"},{name:"Ivory",hex:"FFFFF0"},{name:"Bambu Green",hex:"00AE42"},{name:"Jade White",hex:"E8E8E8"},{name:"Titan Gray",hex:"5A5A5A"}],bQ=[...Bce,...Rit],Hce="bambuddy-recent-colors",Iit=8,Oit=[{code:"GFL00",name:"Bambu PLA Basic",displayName:"Bambu PLA Basic",isCustom:!1,allCodes:["GFL00"]},{code:"GFL01",name:"Bambu PLA Matte",displayName:"Bambu PLA Matte",isCustom:!1,allCodes:["GFL01"]},{code:"GFL05",name:"Generic PLA",displayName:"Generic PLA",isCustom:!1,allCodes:["GFL05"]},{code:"GFG00",name:"Bambu PETG Basic",displayName:"Bambu PETG Basic",isCustom:!1,allCodes:["GFG00"]},{code:"GFG05",name:"Generic PETG",displayName:"Generic PETG",isCustom:!1,allCodes:["GFG05"]},{code:"GFB00",name:"Bambu ABS Basic",displayName:"Bambu ABS Basic",isCustom:!1,allCodes:["GFB00"]},{code:"GFB05",name:"Generic ABS",displayName:"Generic ABS",isCustom:!1,allCodes:["GFB05"]},{code:"GFA00",name:"Bambu ASA Basic",displayName:"Bambu ASA Basic",isCustom:!1,allCodes:["GFA00"]},{code:"GFU00",name:"Bambu TPU 95A",displayName:"Bambu TPU 95A",isCustom:!1,allCodes:["GFU00"]},{code:"GFU05",name:"Generic TPU",displayName:"Generic TPU",isCustom:!1,allCodes:["GFU05"]},{code:"GFC00",name:"Bambu PC Basic",displayName:"Bambu PC Basic",isCustom:!1,allCodes:["GFC00"]},{code:"GFN00",name:"Bambu PA Basic",displayName:"Bambu PA Basic",isCustom:!1,allCodes:["GFN00"]},{code:"GFN05",name:"Generic PA",displayName:"Generic PA",isCustom:!1,allCodes:["GFN05"]},{code:"GFS00",name:"Bambu PLA-CF",displayName:"Bambu PLA-CF",isCustom:!1,allCodes:["GFS00"]},{code:"GFT00",name:"Bambu PETG-CF",displayName:"Bambu PETG-CF",isCustom:!1,allCodes:["GFT00"]},{code:"GFNC0",name:"Bambu PA-CF",displayName:"Bambu PA-CF",isCustom:!1,allCodes:["GFNC0"]},{code:"GFV00",name:"Bambu PVA",displayName:"Bambu PVA",isCustom:!1,allCodes:["GFV00"]}];function Jh(t){let e=t.replace(/@.*$/,"").trim();e=e.replace(/\(Custom\)/i,"").trim(),e=e.replace(/^[#*]+\s*/,"").trim();const n=["PLA-CF","PETG-CF","ABS-GF","ASA-CF","PA-CF","PAHT-CF","PA6-CF","PA6-GF","PPA-CF","PPA-GF","PET-CF","PPS-CF","PC-CF","PC-ABS","ABS-GF","PCTG","PETG","PLA","ABS","ASA","PC","PA","TPU","PVA","HIPS","BVOH","PPS","PEEK","PEI"];let a="",i=-1;for(const c of n){const d=e.toUpperCase().indexOf(c.toUpperCase());if(d!==-1){a=c,i=d;break}}let s="";i>0&&(s=e.substring(0,i).trim(),s=s.replace(/[-_\s]+$/,""));let o="";i!==-1&&a&&(o=e.substring(i+a.length).trim(),o=o.replace(/^[-_\s]+/,""));let l="";for(const c of _w)if(o.toLowerCase().includes(c.toLowerCase())){l=c;break}if(!l&&s)for(const c of _w){const d=new RegExp(`\\s+${c}$`,"i");if(d.test(s)){l=c,s=s.replace(d,"").trim();break}}return{brand:s,material:a,variant:l}}function qce(t,e){const n=new Set(Lit);for(const a of t){const{brand:i}=Jh(a.name);i&&i.length>1&&n.add(i)}if(e)for(const a of e)if(a.filament_vendor&&a.filament_vendor.length>1)n.add(a.filament_vendor);else{const{brand:i}=Jh(a.name);i&&i.length>1&&n.add(i)}return Array.from(n).sort((a,i)=>a.localeCompare(i))}function zit(t){const e=t.filter(a=>a.preset_type==="filament");return e.length===0?[]:e.map(a=>{const i=a.filament_type||String(a.id),s=Array.from(new Set([i,String(a.id)]));return{code:i,name:a.name,displayName:a.name,isCustom:!1,allCodes:s}}).sort((a,i)=>a.displayName.localeCompare(i.displayName))}function $ce(t,e,n,a){const i=[],s=[],o=new Set;for(const u of t)if(u.is_custom){const m=u.name.toUpperCase();(e.size===0||Array.from(e).some(f=>m.includes(f))||!m.includes("@"))&&(i.push({code:u.setting_id,name:u.name,displayName:`${u.name} (Custom)`,isCustom:!0,allCodes:[u.setting_id]}),o.add(u.setting_id))}else s.push({code:u.setting_id,name:u.name,displayName:u.name,isCustom:!1,allCodes:[u.setting_id]}),o.add(u.setting_id);const l=n&&n.length>0?zit(n):[],c=[];if(a&&a.length>0)for(const u of a){const m=u.filament_id.startsWith("GF")?"GFS"+u.filament_id.slice(2):u.filament_id;o.has(u.filament_id)||o.has(m)||c.push({code:u.filament_id,name:u.name,displayName:u.name,isCustom:!1,allCodes:[u.filament_id,m]})}const d=[...i,...s,...l,...c];return d.length===0?Oit:d.sort((u,m)=>u.displayName.localeCompare(m.displayName))}function Vce(t,e){if(!t)return;let n=e.find(a=>a.code===t);if(n||(n=e.find(a=>a.allCodes.includes(t))),!n){const a=t.toLowerCase();n=e.find(i=>i.code.toLowerCase()===a||i.allCodes.some(s=>s.toLowerCase()===a))}return n}function Gce(){try{const t=localStorage.getItem(Hce);if(t)return JSON.parse(t)}catch{}return[]}function Wce(t,e){const n=e.filter(i=>i.hex.toUpperCase()!==t.hex.toUpperCase()),a=[t,...n].slice(0,Iit);try{localStorage.setItem(Hce,JSON.stringify(a))}catch{}return a}function fF(t,e){if(!e.material)return!1;const a=(t.name||"").replace(/^High Flow[_\s]+/i,"").replace(/^Standard[_\s]+/i,"").replace(/^HF[_\s]+/i,"").replace(/^S[_\s]+/i,"").trim(),i=Jh(a);return!(!(i.material.toUpperCase()===e.material.toUpperCase())||e.brand&&!(i.brand.toLowerCase().includes(e.brand.toLowerCase())||e.brand.toLowerCase().includes(i.brand.toLowerCase()))||e.subtype&&!(i.variant.toLowerCase().includes(e.subtype.toLowerCase())||e.subtype.toLowerCase().includes(i.variant.toLowerCase())||a.toLowerCase().includes(e.subtype.toLowerCase())))}function Kce({formData:t,updateField:e,cloudAuthenticated:n,loadingCloudPresets:a,presetInputValue:i,setPresetInputValue:s,selectedPresetOption:o,filamentOptions:l,availableBrands:c,availableMaterials:d,quickAdd:u,quantity:m,onQuantityChange:p,errors:f}){const{t:b}=kt(),[w,g]=v.useState(!1),[x,_]=v.useState(!1),[N,C]=v.useState(!1),[P,T]=v.useState(!1),[A,F]=v.useState(""),[S,M]=v.useState(""),[z,I]=v.useState(""),[H,R]=v.useState(String(t.label_weight)),[Z,re]=v.useState(!1),J=v.useRef(null),de=v.useRef(null),me=v.useRef(null),ue=v.useRef(null);v.useEffect(()=>{const $=K=>{J.current&&!J.current.contains(K.target)&&g(!1),ue.current&&!ue.current.contains(K.target)&&T(!1),de.current&&!de.current.contains(K.target)&&_(!1),me.current&&!me.current.contains(K.target)&&C(!1)};return document.addEventListener("mousedown",$),()=>document.removeEventListener("mousedown",$)},[]);const W=v.useMemo(()=>{if(!i)return l;const $=i.toLowerCase();return l.filter(K=>K.displayName.toLowerCase().includes($)||K.code.toLowerCase().includes($))},[l,i]),ae=v.useMemo(()=>{if(!A)return c;const $=A.toLowerCase();return c.filter(D=>D.toLowerCase().includes($)).sort((D,j)=>{const B=D.toLowerCase()===$,X=j.toLowerCase()===$;return B&&!X?-1:!B&&X?1:D.localeCompare(j)})},[c,A]),pe=v.useMemo(()=>{if(!S)return _w;const $=S.toLowerCase();return _w.filter(K=>K.toLowerCase().includes($))},[S]),ye=v.useMemo(()=>{if(!z)return d;const $=z.toLowerCase();return d.filter(D=>D.toLowerCase().includes($)).sort((D,j)=>{const B=D.toLowerCase()===$,X=j.toLowerCase()===$;return B&&!X?-1:!B&&X?1:D.localeCompare(j)})},[z,d]);v.useEffect(()=>{Z||R(String(t.label_weight))},[t.label_weight,Z]);const Te=$=>{e("slicer_filament",$.code),s($.displayName),g(!1);const K=Jh($.name);K.material&&e("material",K.material),K.brand&&e("brand",K.brand),K.variant&&e("subtype",K.variant)};return r.jsxs("div",{className:"space-y-4",children:[!u&&r.jsx("div",{className:"flex items-center gap-2 text-xs text-bambu-gray",children:a?r.jsxs(r.Fragment,{children:[r.jsx(ut,{className:"w-3 h-3 animate-spin"})," ",b("inventory.loadingPresets")]}):n?r.jsxs(r.Fragment,{children:[r.jsx(Hh,{className:"w-3 h-3 text-bambu-green"})," ",b("inventory.cloudConnected")]}):r.jsxs(r.Fragment,{children:[r.jsx(UF,{className:"w-3 h-3"})," ",b("inventory.cloudNotConnected")]})}),!u&&r.jsxs("div",{children:[r.jsxs("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:[b("inventory.slicerPreset")," *"]}),r.jsxs("div",{className:"relative",ref:J,children:[r.jsx(Sr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50 pointer-events-none"}),r.jsx("input",{type:"text",className:"w-full pl-9 pr-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green",placeholder:b("inventory.searchPresets"),value:i,onChange:$=>{s($.target.value),g(!0)},onFocus:()=>{g(!0),s("")}}),w&&r.jsx("div",{className:"absolute z-50 w-full mt-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-lg max-h-64 overflow-y-auto",children:W.length===0?r.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:b("inventory.noPresetsFound")}):W.map($=>r.jsx("button",{type:"button",className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary truncate ${o?.code===$.code?"bg-bambu-green/10 text-bambu-green":"text-white"}`,onClick:()=>Te($),children:$.displayName},`${$.code}::${$.name}`))})]}),o&&r.jsxs("div",{className:"mt-1 text-xs text-bambu-gray",children:[b("inventory.selectedPreset"),": ",r.jsx("span",{className:"font-mono text-bambu-green",children:o.code})]}),f?.slicer_filament&&r.jsx("p",{className:"mt-1 text-xs text-red-400",children:f.slicer_filament})]}),r.jsxs("div",{children:[r.jsxs("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:[b("inventory.material")," *"]}),r.jsxs("div",{className:"relative",ref:ue,children:[r.jsx("input",{type:"text",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green",placeholder:b("inventory.selectMaterial"),value:P?z:t.material,onChange:$=>{I($.target.value),T(!0)},onFocus:()=>{T(!0),I("")}}),r.jsx(Ln,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50 pointer-events-none"}),P&&r.jsxs("div",{className:"absolute z-50 w-full mt-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-lg max-h-48 overflow-y-auto",children:[ye.length===0?r.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:b("inventory.noResults")}):ye.map($=>r.jsx("button",{type:"button",className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary ${t.material===$?"bg-bambu-green/10 text-bambu-green":"text-white"}`,onClick:()=>{e("material",$),T(!1),I("")},children:$},$)),z&&!ye.includes(z)&&r.jsx("button",{type:"button",className:"w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary text-bambu-green border-t border-bambu-dark-tertiary",onClick:()=>{e("material",z),T(!1),I("")},children:b("inventory.useCustomMaterial",{material:z})})]})]}),f?.material&&r.jsx("p",{className:"mt-1 text-xs text-red-400",children:f.material})]}),r.jsxs("div",{children:[r.jsxs("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:[b("inventory.brand"),!u&&" *"]}),r.jsxs("div",{className:"relative",ref:de,children:[r.jsx("input",{type:"text",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green",placeholder:b("inventory.searchBrand"),value:x?A:t.brand,onChange:$=>{F($.target.value),_(!0)},onFocus:()=>{_(!0),F("")}}),r.jsx(Ln,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50 pointer-events-none"}),x&&r.jsxs("div",{className:"absolute z-50 w-full mt-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-lg max-h-48 overflow-y-auto",children:[ae.length===0?r.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:b("inventory.noResults")}):ae.map($=>r.jsx("button",{type:"button",className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary ${t.brand===$?"bg-bambu-green/10 text-bambu-green":"text-white"}`,onClick:()=>{e("brand",$),_(!1),F("")},children:$},$)),A&&!ae.includes(A)&&r.jsx("button",{type:"button",className:"w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary text-bambu-green border-t border-bambu-dark-tertiary",onClick:()=>{e("brand",A),_(!1),F("")},children:b("inventory.useCustomBrand",{brand:A})})]})]}),f?.brand&&r.jsx("p",{className:"mt-1 text-xs text-red-400",children:f.brand})]}),r.jsxs("div",{children:[r.jsxs("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:[b("inventory.subtype"),!u&&" *"]}),r.jsxs("div",{className:"relative",ref:me,children:[r.jsx("input",{type:"text",value:N?S:t.subtype,onChange:$=>{M($.target.value),C(!0)},onFocus:()=>{C(!0),M("")},placeholder:"Basic, Matte, Silk...",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green"}),r.jsx(Ln,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50 pointer-events-none"}),N&&r.jsxs("div",{className:"absolute z-50 w-full mt-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-lg max-h-48 overflow-y-auto",children:[pe.length===0?r.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:b("inventory.noResults")}):pe.map($=>r.jsx("button",{type:"button",className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary ${t.subtype===$?"bg-bambu-green/10 text-bambu-green":"text-white"}`,onClick:()=>{e("subtype",$),C(!1),M("")},children:$},$)),S&&!_w.some($=>$.toLowerCase()===S.toLowerCase().trim())&&r.jsx("button",{type:"button",className:"w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary text-bambu-green border-t border-bambu-dark-tertiary",onClick:()=>{e("subtype",S),C(!1),M("")},children:b("inventory.useCustomBrand",{brand:S})})]})]}),f?.subtype&&r.jsx("p",{className:"mt-1 text-xs text-red-400",children:f.subtype})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:b("inventory.labelWeight")}),r.jsxs("div",{className:"relative",children:[r.jsx("input",{type:"number",className:"w-full px-3 py-2 pr-7 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:outline-none focus:border-bambu-green",value:H,min:0,onFocus:()=>re(!0),onChange:$=>R($.target.value),onBlur:()=>{re(!1);const $=H.trim(),K=Number($);if(!$||!Number.isFinite(K)||K<0){R(String(t.label_weight));return}const D=Math.round(K);e("label_weight",D),R(String(D))}}),r.jsx("span",{className:"absolute right-2 top-1/2 -translate-y-1/2 text-xs text-bambu-gray",children:"g"})]})]}),u&&r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:b("inventory.quantity")}),r.jsx("input",{type:"number",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:outline-none focus:border-bambu-green",value:m,min:1,max:100,onChange:$=>{const K=Math.max(1,Math.min(100,parseInt($.target.value)||1));p(K)}})]})]})}function Uit(t){const e=t.split(/[\s,]+/).map(i=>i.trim().replace(/^#/,"")).filter(Boolean),n=[],a=[];for(const i of e)(i.length===6||i.length===8)&&/^[0-9a-fA-F]+$/.test(i)?n.push(i.toLowerCase()):a.push(i);return{value:n.join(","),invalid:a}}function Yce({formData:t,updateField:e,recentColors:n,onColorUsed:a,catalogColors:i}){const{t:s}=kt(),[o,l]=v.useState(!1),[c,d]=v.useState(""),u=t.rgba.replace("#","").substring(0,6),m=F=>u.toUpperCase()===F.toUpperCase(),p=(F,S)=>{e("rgba",F.toUpperCase()+"FF"),e("color_name",S),a({name:S,hex:F})},f=v.useMemo(()=>{if(i.length===0)return[];const F=t.brand?.trim(),S=t.material?.toLowerCase().trim(),M=t.subtype?.toLowerCase().trim();if(!F&&!S)return[];const z=F?F.toLowerCase().split(/[\s\-_]+/).filter(R=>R.length>=2):[],I=R=>{if(z.length===0)return!0;const Z=R.toLowerCase();return z.some(re=>Z.includes(re))};if(F&&!S){const R=i.filter(Z=>I(Z.manufacturer));if(R.length>0)return R.map(Z=>({name:Z.color_name,hex:Z.hex_color.replace("#","").substring(0,6),manufacturer:Z.manufacturer,material:typeof Z.material=="string"?Z.material:void 0}))}const H=S&&M?`${S} ${M}`:"";if(H){const R=i.filter(re=>I(re.manufacturer)&&re.material?.toLowerCase()===H);if(R.length>0)return R.map(re=>({name:re.color_name,hex:re.hex_color.replace("#","").substring(0,6),manufacturer:re.manufacturer,material:typeof re.material=="string"?re.material:void 0}));const Z=H.replace(/\+$/,"");if(Z!==H){const re=i.filter(J=>I(J.manufacturer)&&J.material?.toLowerCase()===Z);if(re.length>0)return re.map(J=>({name:J.color_name,hex:J.hex_color.replace("#","").substring(0,6),manufacturer:J.manufacturer,material:typeof J.material=="string"?J.material:void 0}))}}if(S){const R=i.filter(Z=>I(Z.manufacturer)&&(!Z.material||Z.material.toLowerCase().startsWith(S)));if(R.length>0)return R.map(Z=>({name:Z.color_name,hex:Z.hex_color.replace("#","").substring(0,6),manufacturer:Z.manufacturer,material:typeof Z.material=="string"?Z.material:void 0}))}return[]},[i,t.brand,t.material,t.subtype]),b=v.useMemo(()=>{if(!c)return f;if(f.length===0)return[];const F=c.toLowerCase();return f.filter(M=>M.name.toLowerCase().includes(F)||(M.manufacturer?.toLowerCase().includes(F)??!1)||(M.material?.toLowerCase().includes(F)??!1))},[c,f]),w=f.length>0,g=v.useMemo(()=>c?bQ.filter(F=>F.name.toLowerCase().includes(c.toLowerCase())):o?bQ:Bce,[c,o]),[x,_]=v.useState(t.extra_colors),[N,C]=v.useState([]),P=v.useRef(t.extra_colors);v.useEffect(()=>{t.extra_colors!==P.current&&(_(t.extra_colors),C([]),P.current=t.extra_colors)},[t.extra_colors]);const T=v.useMemo(()=>rj({rgba:t.rgba,extraColors:t.extra_colors,effectType:t.effect_type,subtype:t.subtype,effectSize:"bar"}),[t.rgba,t.extra_colors,t.effect_type,t.subtype]),A=F=>{if(_(F),!F.trim()){C([]),P.current="",e("extra_colors","");return}const{value:S,invalid:M}=Uit(F);C(M),P.current=S,e("extra_colors",S)};return r.jsxs("div",{className:"space-y-3",children:[r.jsx("div",{className:"h-10 rounded-lg border border-bambu-dark-tertiary",style:T,"data-testid":"color-preview-banner"}),n.length>0&&r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-bambu-gray shrink-0",children:[r.jsx(Zn,{className:"w-3 h-3"}),r.jsx("span",{children:s("inventory.recentColors")})]}),r.jsx("div",{className:"flex flex-wrap gap-1.5",children:n.map(F=>r.jsx("button",{type:"button",onClick:()=>p(F.hex,F.name),className:`w-6 h-6 rounded border-2 transition-all hover:scale-110 ${m(F.hex)?"border-bambu-green ring-1 ring-bambu-green/30 scale-110":"border-bambu-dark-tertiary"}`,style:{backgroundColor:`#${F.hex}`},title:F.name},F.hex))})]}),r.jsxs("div",{className:"relative",children:[r.jsx(Sr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50 pointer-events-none"}),r.jsx("input",{type:"text",className:"w-full pl-9 pr-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green",placeholder:s("inventory.searchColors"),value:c,onChange:F=>d(F.target.value)})]}),w?r.jsxs("div",{className:"space-y-1.5",children:[r.jsx("span",{className:"text-xs text-bambu-gray",children:c?s("inventory.searchResults"):`${t.brand}${t.material?` ${t.material}`:""}`}),r.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[b.map(F=>r.jsx("button",{type:"button",onClick:()=>p(F.hex,F.name),className:`w-6 h-6 rounded border-2 transition-all hover:scale-110 hover:z-20 relative group ${m(F.hex)?"border-bambu-green ring-1 ring-bambu-green/30 scale-110":"border-bambu-dark-tertiary"}`,style:{backgroundColor:`#${F.hex}`},title:F.manufacturer&&F.material?`${F.name} (${F.manufacturer} — ${F.material})`:F.manufacturer?`${F.name} (${F.manufacturer})`:F.name,children:r.jsx("span",{className:"absolute -bottom-7 left-1/2 -translate-x-1/2 px-2 py-0.5 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-xs whitespace-nowrap opacity-0 group-hover:opacity-100 transition-opacity pointer-events-none z-20 shadow-lg text-white",children:F.manufacturer&&F.material?`${F.name} (${F.manufacturer} — ${F.material})`:F.manufacturer?`${F.name} (${F.manufacturer})`:F.name})},`${F.hex}-${F.name}-${F.manufacturer??""}`)),b.length===0&&r.jsx("p",{className:"text-sm text-bambu-gray py-1",children:s("inventory.noColorsFound")})]})]}):r.jsxs("div",{className:"space-y-1.5",children:[r.jsxs("div",{className:"flex items-center justify-between text-xs text-bambu-gray",children:[r.jsx("span",{children:s(c?"inventory.searchResults":o?"inventory.allColors":"inventory.commonColors")}),!c&&r.jsx("button",{type:"button",onClick:()=>l(!o),className:"flex items-center gap-1 hover:text-white transition-colors",children:o?r.jsxs(r.Fragment,{children:[s("inventory.showLess")," ",r.jsx(tl,{className:"w-3 h-3"})]}):r.jsxs(r.Fragment,{children:[s("inventory.showAll")," ",r.jsx(Ln,{className:"w-3 h-3"})]})})]}),r.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[g.map(F=>r.jsx("button",{type:"button",onClick:()=>p(F.hex,F.name),className:`w-6 h-6 rounded border-2 transition-all hover:scale-110 hover:z-20 relative group ${m(F.hex)?"border-bambu-green ring-1 ring-bambu-green/30 scale-110":"border-bambu-dark-tertiary"}`,style:{backgroundColor:`#${F.hex}`},title:F.name,children:r.jsx("span",{className:"absolute -bottom-7 left-1/2 -translate-x-1/2 px-2 py-0.5 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-xs whitespace-nowrap opacity-0 group-hover:opacity-100 transition-opacity pointer-events-none z-20 shadow-lg text-white",children:F.name})},F.hex)),g.length===0&&r.jsx("p",{className:"text-sm text-bambu-gray py-1",children:s("inventory.noColorsFound")})]})]}),r.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:s("inventory.colorName")}),r.jsx("input",{type:"text",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green",placeholder:s("inventory.colorNamePlaceholder"),value:t.color_name,onChange:F=>e("color_name",F.target.value)})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:s("inventory.hexColor")}),r.jsxs("div",{className:"flex gap-2",children:[r.jsxs("div",{className:"relative flex-1",children:[r.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-bambu-gray",children:"#"}),r.jsx("input",{type:"text",className:"w-full pl-7 pr-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm font-mono uppercase focus:outline-none focus:border-bambu-green",placeholder:"RRGGBB",value:u.toUpperCase(),onChange:F=>{const S=F.target.value.replace("#","").replace(/[^0-9A-Fa-f]/g,"").toUpperCase();if(S.length>8)return;const M=S.length===8?S:S.length===7?S.substring(0,6)+"FF":S.padEnd(6,"0")+"FF";e("rgba",M)}})]}),r.jsx("input",{type:"color",className:"w-11 h-[38px] rounded-lg cursor-pointer border border-bambu-dark-tertiary shrink-0 bg-transparent",value:`#${u}`,onChange:F=>{const S=F.target.value.replace("#","").toUpperCase();e("rgba",S+"FF")},title:s("inventory.pickColor")})]})]})]}),r.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3 pt-2 border-t border-bambu-dark-tertiary/50",children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:s("inventory.extraColorsLabel")}),r.jsx("input",{type:"text",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm font-mono placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green",placeholder:s("inventory.extraColorsPlaceholder"),value:x,onChange:F=>A(F.target.value),"data-testid":"extra-colors-input"}),N.length>0&&r.jsx("p",{className:"text-xs text-red-400 mt-1",children:s("inventory.extraColorsInvalid",{tokens:N.join(", ")})}),!N.length&&r.jsx("p",{className:"text-xs text-bambu-gray/70 mt-1",children:s("inventory.extraColorsHint")})]}),r.jsxs("div",{children:[r.jsxs("label",{className:"block text-sm font-medium text-bambu-gray mb-1 flex items-center gap-1.5",children:[r.jsx(Dg,{className:"w-3.5 h-3.5"}),s("inventory.colorEffectLabel")]}),r.jsxs("div",{className:"flex gap-2 items-stretch",children:[r.jsx("select",{className:"flex-1 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:outline-none focus:border-bambu-green",value:t.effect_type,onChange:F=>e("effect_type",F.target.value),"data-testid":"effect-type-select",children:WI.map(F=>r.jsx("option",{value:F.value,children:s(F.labelKey)},F.value||"none"))}),r.jsx(rU,{rgba:t.rgba,extraColors:t.extra_colors,effectType:t.effect_type,subtype:t.subtype,effectSize:"preview",className:"w-10 h-10",shape:"square"})]})]})]})]})}function Bit({catalog:t,value:e,onChange:n,catalogId:a,onCatalogIdChange:i}){const{t:s}=kt(),[o,l]=v.useState(!1),[c,d]=v.useState(""),u=v.useRef(null),m=v.useRef(null);v.useEffect(()=>{const w=g=>{u.current&&!u.current.contains(g.target)&&l(!1)};return document.addEventListener("mousedown",w),()=>document.removeEventListener("mousedown",w)},[]),v.useEffect(()=>{if(t.length===0)return;const w=t.filter(g=>g.weight===e);if(a){const g=t.find(x=>x.id===a);if(g&&g.weight===e)return}w.length===1?i(w[0].id):w.length===0&&a!==null&&i(null)},[e,t,a,i]);const p=v.useMemo(()=>{if(!c)return t;const w=c.toLowerCase();return t.filter(g=>g.name.toLowerCase().includes(w)||g.weight.toString().includes(w))},[t,c]),f=v.useMemo(()=>t.filter(w=>w.weight===e),[t,e]),b=v.useMemo(()=>{if(o)return c;if(a){const w=t.find(g=>g.id===a);if(w)return w.name}return f.length>0?f[0].name:""},[o,c,a,t,f]);return r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:r.jsxs("span",{className:"flex items-center gap-2",children:[r.jsx(FZ,{className:"w-3.5 h-3.5 text-bambu-gray"}),s("inventory.coreWeight")]})}),r.jsxs("div",{className:"flex gap-2 items-center",children:[r.jsxs("div",{className:"flex-1 min-w-0 relative",ref:u,children:[r.jsx("input",{ref:m,type:"text",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green",placeholder:s("inventory.searchSpoolWeight"),value:b,onFocus:()=>{l(!0),d("")},onChange:w=>{d(w.target.value),l(!0)}}),o&&r.jsx("div",{className:"absolute z-50 w-full mt-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-lg max-h-64 overflow-y-auto",children:p.length===0?r.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:s("inventory.noResults")}):p.map(w=>r.jsxs("button",{type:"button",className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex justify-between items-center ${(a?w.id===a:w.weight===e)?"bg-bambu-green/10 text-bambu-green":"text-white"}`,onClick:()=>{i(w.id),n(w.weight),l(!1),d("")},children:[r.jsx("span",{className:"truncate",children:w.name}),r.jsxs("span",{className:"font-mono text-xs text-bambu-gray ml-2 shrink-0",children:[w.weight,"g"]})]},w.id))})]}),r.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[r.jsx("input",{type:"number",className:"w-16 px-2 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm text-center font-mono focus:outline-none focus:border-bambu-green",value:e,min:0,max:2e3,onChange:w=>{const g=parseInt(w.target.value);!isNaN(g)&&g>=0&&n(g)}}),r.jsx("span",{className:"text-bambu-gray text-sm",children:"g"})]})]})]})}function Xce({formData:t,updateField:e,spoolCatalog:n,currencySymbol:a,availableCategories:i,globalLowStockThreshold:s,spoolmanMode:o=!1}){const{t:l}=kt(),{showToast:c}=rn(),[d,u]=v.useState(""),[m,p]=v.useState(!1),[f,b]=v.useState(""),[w,g]=v.useState(!1),x=Math.max(0,t.label_weight-t.weight_used),_=t.core_weight+x;return v.useEffect(()=>{m||u(String(_))},[m,_]),v.useEffect(()=>{w||b(String(x))},[w,x]),r.jsxs("div",{className:"space-y-4",children:[o?r.jsx("p",{className:"text-xs text-bambu-gray px-1",children:l("inventory.spoolWeightManagedBySpoolman")}):r.jsx(Bit,{catalog:n,value:t.core_weight,onChange:N=>e("core_weight",N),catalogId:t.core_weight_catalog_id,onCatalogIdChange:N=>e("core_weight_catalog_id",N)}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:l("inventory.currentWeight")}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsxs("div",{className:"relative flex-1",children:[r.jsx("input",{type:"number",value:f,min:0,max:t.label_weight,onFocus:()=>g(!0),onChange:N=>{b(N.target.value)},onBlur:()=>{g(!1);const N=f.trim(),C=Number(N);if(!N||!Number.isFinite(C)||C<0||C>t.label_weight){b(String(x));return}const P=Math.round(C);e("weight_used",Math.max(0,t.label_weight-P)),b(String(P))},className:"w-full px-3 py-2 pr-7 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:outline-none focus:border-bambu-green"}),r.jsx("span",{className:"absolute right-2 top-1/2 -translate-y-1/2 text-xs text-bambu-gray",children:"g"})]}),r.jsxs("span",{className:"text-xs text-bambu-gray shrink-0",children:["/ ",t.label_weight,"g"]})]})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:l("inventory.measuredWeight")}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsxs("div",{className:"relative flex-1",children:[r.jsx("input",{type:"number",value:d,min:0,onFocus:()=>p(!0),onChange:N=>{u(N.target.value)},onBlur:()=>{p(!1);const N=d.trim(),C=Number(N),P=t.core_weight,T=t.core_weight+t.label_weight;if(!N||!Number.isFinite(C)||CT){c(l("inventory.measuredWeightError",{min:P,max:T}),"error"),u(String(_));return}const A=Math.round(C),F=Math.max(0,Math.min(t.label_weight,A-t.core_weight));e("weight_used",Math.max(0,t.label_weight-F)),u(String(A))},className:"w-full px-3 py-2 pr-7 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:outline-none focus:border-bambu-green"}),r.jsx("span",{className:"absolute right-2 top-1/2 -translate-y-1/2 text-xs text-bambu-gray",children:"g"})]}),r.jsxs("span",{className:"text-xs text-bambu-gray shrink-0",children:["/ ",t.core_weight+t.label_weight,"g"]})]})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:l("inventory.costPerKg","Cost per kg")}),r.jsx("div",{className:"flex items-center gap-2",children:r.jsxs("div",{className:"relative flex-1",children:[r.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-bambu-gray text-sm pointer-events-none",children:a}),r.jsx("input",{type:"number",value:t.cost_per_kg??"",min:0,step:.01,placeholder:"0.00",onChange:N=>{const C=N.target.value===""?null:parseFloat(N.target.value);e("cost_per_kg",C)},style:{paddingLeft:`${Math.max(2,a.length*.6+1)}rem`},className:"w-full py-2 pr-3 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:outline-none focus:border-bambu-green"})]})})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",htmlFor:"spool-category",children:l("inventory.category")}),r.jsx("input",{id:"spool-category",type:"text",list:"spool-category-options",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green",placeholder:l("inventory.categoryPlaceholder"),value:t.category,maxLength:50,onChange:N=>e("category",N.target.value)}),i.length>0&&r.jsx("datalist",{id:"spool-category-options",children:i.map(N=>r.jsx("option",{value:N},N))})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",htmlFor:"spool-low-stock-threshold",children:l("inventory.lowStockThresholdOverride")}),r.jsx("div",{className:"flex items-center gap-2",children:r.jsxs("div",{className:"relative flex-1",children:[r.jsx("input",{id:"spool-low-stock-threshold",type:"number",className:"w-full px-3 py-2 pr-8 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green",placeholder:String(s),value:t.low_stock_threshold_pct??"",min:1,max:99,step:1,onChange:N=>{const C=N.target.value;if(C===""){e("low_stock_threshold_pct",null);return}const P=Number(C);Number.isFinite(P)&&e("low_stock_threshold_pct",Math.min(99,Math.max(1,Math.round(P))))}}),r.jsx("span",{className:"absolute right-3 top-1/2 -translate-y-1/2 text-xs text-bambu-gray pointer-events-none",children:"%"})]})}),r.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:l("inventory.lowStockThresholdOverrideHelp",{global:s})})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:l("inventory.note")}),r.jsx("textarea",{className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green resize-none min-h-[80px]",placeholder:l("inventory.notePlaceholder"),value:t.note,onChange:N=>e("note",N.target.value)})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:l("inventory.storageLocation")}),r.jsx("input",{type:"text",maxLength:255,className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green",placeholder:l("inventory.storageLocationPlaceholder"),value:t.storage_location,onChange:N=>e("storage_location",N.target.value)})]})]})}function Hit({filaments:t,isLoading:e,selectedId:n,onSelect:a}){const{t:i}=kt(),[s,o]=v.useState(!1),[l,c]=v.useState(""),d=v.useRef(null),u=v.useRef(null),m=v.useMemo(()=>t.find(g=>g.id===n)??null,[t,n]);v.useEffect(()=>{const g=x=>{d.current&&!d.current.contains(x.target)&&(o(!1),c(""))};return document.addEventListener("mousedown",g),()=>document.removeEventListener("mousedown",g)},[]);const p=v.useMemo(()=>{const g=l.toLowerCase().trim();return g?t.filter(x=>x.name.toLowerCase().includes(g)||(x.material?.toLowerCase().includes(g)??!1)||(x.vendor?.name.toLowerCase().includes(g)??!1)||(x.color_name?.toLowerCase().includes(g)??!1)):t},[t,l]);v.useEffect(()=>{s&&u.current?.focus()},[s]);const f=()=>{o(!0),c("")},b=g=>{a(g),o(!1),c("")},w=g=>g?`#${g.replace("#","")}`:"#808080";return r.jsxs("div",{ref:d,className:"relative",children:[r.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:i("inventory.pickFromSpoolmanCatalog")}),r.jsxs("button",{type:"button",onClick:f,className:"w-full flex items-center gap-2 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-left focus:outline-none focus:border-bambu-green hover:border-bambu-gray transition-colors",children:[e?r.jsx(ut,{className:"w-4 h-4 text-bambu-gray animate-spin shrink-0"}):m?r.jsxs(r.Fragment,{children:[r.jsx("span",{className:"w-4 h-4 rounded-full shrink-0 border border-white/20",style:{backgroundColor:w(m.color_hex)},"aria-label":i("inventory.spoolmanFilamentColorSwatch")}),r.jsxs("span",{className:"text-white text-sm truncate flex-1",children:[m.vendor?.name?`${m.vendor.name} — `:"",m.name]})]}):r.jsxs(r.Fragment,{children:[r.jsx(Br,{className:"w-4 h-4 text-bambu-gray shrink-0"}),r.jsx("span",{className:"text-bambu-gray text-sm flex-1",children:i("inventory.spoolmanFilamentCatalog")})]}),r.jsx(Ln,{className:"w-4 h-4 text-bambu-gray shrink-0 ml-auto"})]}),s&&r.jsxs("div",{className:"absolute z-50 w-full mt-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl",children:[r.jsx("div",{className:"p-2 border-b border-bambu-dark-tertiary",children:r.jsx("input",{ref:u,type:"text",value:l,onChange:g=>c(g.target.value),placeholder:i("inventory.pickFromSpoolmanCatalog"),className:"w-full px-2 py-1.5 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-sm placeholder-bambu-gray focus:outline-none focus:border-bambu-green"})}),r.jsx("ul",{className:"max-h-56 overflow-y-auto py-1",children:e?r.jsxs("li",{className:"flex items-center justify-center gap-2 py-4 text-bambu-gray text-sm",children:[r.jsx(ut,{className:"w-4 h-4 animate-spin"}),r.jsx("span",{children:i("common.loading","Loading…")})]}):p.length===0?r.jsx("li",{className:"py-4 text-center text-bambu-gray text-sm",children:i("inventory.noSpoolmanFilaments")}):p.map(g=>r.jsx("li",{children:r.jsxs("button",{type:"button",onClick:()=>b(g),className:`w-full flex items-center gap-2 px-3 py-2 text-left hover:bg-bambu-dark-tertiary transition-colors ${g.id===n?"bg-bambu-dark-tertiary":""}`,children:[r.jsx("span",{className:"w-4 h-4 rounded-full shrink-0 border border-white/20",style:{backgroundColor:w(g.color_hex)},"aria-label":i("inventory.spoolmanFilamentColorSwatch")}),r.jsxs("span",{className:"flex-1 min-w-0",children:[r.jsxs("span",{className:"block text-white text-sm truncate",children:[g.vendor?.name?`${g.vendor.name} — `:"",g.name]}),r.jsxs("span",{className:"block text-bambu-gray text-xs truncate",children:[[g.material,g.color_name].filter(Boolean).join(" · "),g.weight?` · ${g.weight}g`:""]})]})]})},g.id))})]})]})}function Qce({formData:t,printersWithCalibrations:e,selectedProfiles:n,setSelectedProfiles:a,expandedPrinters:i,setExpandedPrinters:s}){const{t:o}=kt(),l=p=>{s(f=>{const b=new Set(f);return b.has(p)?b.delete(p):b.add(p),b})},c=(p,f,b)=>{const w=`${p}:${f}:${b??"null"}`,g=`${p}:${b??"null"}`;a(x=>{const _=new Set(x);if(_.has(w))_.delete(w);else{for(const N of Array.from(_)){const C=N.split(":");`${C[0]}:${C[2]}`===g&&_.delete(N)}_.add(w)}return _})},d=()=>{const p=new Set;for(const{printer:f,calibrations:b}of e){if(!f.connected)continue;const w=b.filter(x=>fF(x,t)),g=new Map;for(const x of w){const _=`${x.extruder_id??"null"}`;g.has(_)||g.set(_,[]),g.get(_).push(x)}for(const[x,_]of g)if(_.length>0){const C=[..._].sort((P,T)=>T.k_value-P.k_value)[0];p.add(`${f.id}:${C.cali_idx}:${x}`)}}a(p)};if(!t.material)return r.jsx("div",{className:"p-6 bg-bambu-dark rounded-lg text-center",children:r.jsx("p",{className:"text-bambu-gray",children:o("inventory.selectMaterialFirst")})});if(e.length===0)return r.jsx("div",{className:"p-6 bg-bambu-dark rounded-lg text-center",children:r.jsx("p",{className:"text-bambu-gray",children:o("inventory.noPrintersConfigured")})});const u=e.reduce((p,{printer:f,calibrations:b})=>f.connected?p+b.filter(w=>fF(w,t)).length:p,0),m=(p,f)=>{const b=`${p.id}:${f.cali_idx}:${f.extruder_id??"null"}`,w=n.has(b);return r.jsxs("label",{className:`flex items-center gap-3 p-3 rounded-lg cursor-pointer transition-all border ${w?"bg-bambu-green/10 border-bambu-green/30":"bg-bambu-dark border-transparent hover:bg-bambu-dark/80"}`,children:[r.jsx("input",{type:"checkbox",checked:w,onChange:()=>c(String(p.id),f.cali_idx,f.extruder_id),className:"w-4 h-4 rounded border-bambu-dark-tertiary text-bambu-green focus:ring-bambu-green"}),r.jsx("div",{className:"flex-1 min-w-0",children:r.jsx("span",{className:`text-sm font-medium ${w?"text-bambu-green":"text-white"}`,children:f.name||f.filament_id})}),r.jsx("div",{className:"flex items-center gap-2 shrink-0",children:r.jsxs("span",{className:"text-xs font-mono px-2 py-0.5 rounded bg-bambu-dark text-bambu-gray",children:["K=",f.k_value.toFixed(3)]})})]},`${f.cali_idx}-${f.extruder_id}`)};return r.jsxs("div",{className:"space-y-4",children:[r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("p",{className:"text-xs text-bambu-gray",children:[o("inventory.matchingFilter"),": ",t.brand||o("inventory.anyBrand")," / ",t.material," / ",t.subtype||o("inventory.anyVariant")]}),u>0&&r.jsxs("button",{type:"button",onClick:d,className:"flex items-center gap-1.5 px-2 py-1 text-xs bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-bambu-gray hover:text-white hover:border-bambu-green transition-colors",children:[r.jsx(Dg,{className:"w-3.5 h-3.5"}),o("inventory.autoSelect")," (",u,")"]})]}),r.jsx("div",{className:"space-y-3",children:e.map(({printer:p,calibrations:f})=>{const b=i.has(String(p.id)),w=f.filter(C=>fF(C,t)),g=w.length,x=w.some(C=>C.extruder_id!==void 0&&C.extruder_id!==null&&C.extruder_id>0),_=w.filter(C=>C.extruder_id===1),N=w.filter(C=>C.extruder_id===0||C.extruder_id===void 0||C.extruder_id===null);return r.jsxs("div",{className:"border border-bambu-dark-tertiary rounded-lg overflow-hidden",children:[r.jsxs("button",{type:"button",onClick:()=>l(String(p.id)),className:"w-full px-4 py-3 flex items-center justify-between bg-bambu-dark-secondary hover:bg-bambu-dark-tertiary transition-colors",children:[r.jsxs("div",{className:"flex items-center gap-3",children:[b?r.jsx(Ln,{className:"w-4 h-4 text-bambu-gray"}):r.jsx(Va,{className:"w-4 h-4 text-bambu-gray"}),r.jsx("span",{className:"font-medium text-white",children:p.name}),g>0?r.jsxs("span",{className:"text-xs px-2 py-0.5 rounded-full bg-bambu-green/20 text-bambu-green",children:[g," ",o(g!==1?"inventory.matches":"inventory.match")]}):r.jsx("span",{className:"text-xs px-2 py-0.5 rounded-full bg-bambu-dark-tertiary text-bambu-gray",children:o("inventory.noMatches")})]}),r.jsx("span",{className:`text-xs px-2 py-1 rounded-full ${p.connected?"bg-green-500/20 text-green-500":"bg-bambu-gray/20 text-bambu-gray"}`,children:p.connected?o("inventory.connected"):o("inventory.offline")})]}),b&&r.jsx("div",{className:"px-4 py-3 space-y-3 bg-bambu-dark border-t border-bambu-dark-tertiary",children:p.connected?g===0?r.jsx("p",{className:"text-sm text-bambu-gray italic py-2",children:o("inventory.noKProfilesMatch")}):x?r.jsxs(r.Fragment,{children:[_.length>0&&r.jsxs("div",{className:"space-y-2",children:[r.jsx("p",{className:"text-xs font-medium text-bambu-gray uppercase tracking-wide",children:o("inventory.leftNozzle")}),r.jsx("div",{className:"space-y-2",children:_.map(C=>m(p,C))})]}),N.length>0&&r.jsxs("div",{className:"space-y-2",children:[r.jsx("p",{className:"text-xs font-medium text-bambu-gray uppercase tracking-wide",children:o("inventory.rightNozzle")}),r.jsx("div",{className:"space-y-2",children:N.map(C=>m(p,C))})]})]}):r.jsx("div",{className:"space-y-2",children:w.map(C=>m(p,C))}):r.jsx("p",{className:"text-sm text-bambu-gray italic py-2",children:o("inventory.printerOffline")})})]},p.id)})}),n.size>0&&r.jsx("div",{className:"p-3 bg-bambu-green/10 border border-bambu-green/30 rounded-lg",children:r.jsxs("p",{className:"text-sm text-white",children:[r.jsx("span",{className:"font-semibold",children:n.size})," ",o("inventory.profilesSelected")]})})]})}function qit(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 $it={completed:"text-bambu-green",failed:"text-red-400",aborted:"text-yellow-400"};function Vit({spoolId:t}){const{t:e}=kt(),n=en(),{showToast:a}=rn(),{data:i,isLoading:s}=We({queryKey:["spool-usage",t],queryFn:()=>se.getSpoolUsageHistory(t)}),o=it({mutationFn:()=>se.clearSpoolUsageHistory(t),onSuccess:()=>{n.invalidateQueries({queryKey:["spool-usage",t]}),a(e("inventory.historyCleared"),"success")}});return s?r.jsx("div",{className:"flex justify-center py-4",children:r.jsx(ut,{className:"w-5 h-5 animate-spin text-bambu-green"})}):!i||i.length===0?r.jsxs("div",{className:"text-center py-4 text-bambu-gray text-sm",children:[r.jsx(Zn,{className:"w-5 h-5 mx-auto mb-2 opacity-50"}),e("inventory.noUsageHistory")]}):r.jsxs("div",{className:"space-y-2",children:[r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsx("h4",{className:"text-sm font-medium text-white",children:e("inventory.usageHistory")}),r.jsxs(Me,{variant:"ghost",size:"sm",onClick:()=>o.mutate(),disabled:o.isPending,className:"text-xs text-bambu-gray hover:text-red-400",children:[r.jsx(Jt,{className:"w-3 h-3 mr-1"}),e("inventory.clearHistory")]})]}),r.jsx("div",{className:"max-h-48 overflow-y-auto space-y-1",children:i.map(l=>r.jsxs("div",{className:"flex items-center justify-between p-2 rounded bg-bambu-dark/50 text-xs",children:[r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsx("span",{className:"text-bambu-gray",children:qit(l.created_at)}),l.print_name&&r.jsx("span",{className:"text-white ml-2 truncate",title:l.print_name,children:l.print_name})]}),r.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0 ml-2",children:[r.jsxs("span",{className:"text-white font-medium",children:[l.weight_used.toFixed(1),"g"]}),r.jsxs("span",{className:"text-bambu-gray",children:["(",l.percent_used,"%)"]}),r.jsx("span",{className:$it[l.status]||"text-bambu-gray",children:l.status})]})]},l.id))})]})}const xQ={tag_uid:null,tray_uuid:null,tag_type:null,data_origin:null};function Git({isOpen:t,onClose:e,spool:n,mode:a,printersWithCalibrations:i=[],currencySymbol:s,onSpoolsCreated:o,spoolmanMode:l=!1,spoolsQueryKey:c=["inventory-spools"]}){const{t:d}=kt(),u=en(),{showToast:m}=rn(),p=a==="edit",f=a==="copy",[b,w]=v.useState(YI),[g,x]=v.useState({}),[_,N]=v.useState("filament"),[C,P]=v.useState(!1),[T,A]=v.useState(!1),[F,S]=v.useState(!1),[M,z]=v.useState(1),[I,H]=v.useState(!1),[R,Z]=v.useState(!1),[re,J]=v.useState([]),[de,me]=v.useState(""),[ue,W]=v.useState([]),[ae,pe]=v.useState([]),[ye,Te]=v.useState([]),[$,K]=v.useState([]),[D,j]=v.useState([]),[B,X]=v.useState([]),[O,ie]=v.useState(new Set),[U,G]=v.useState(new Set),Y=i.length>0?i:B,Q=O.size,{data:oe=[],isLoading:ee,error:ge}=We({queryKey:["spoolman-inventory-filaments"],queryFn:()=>se.getSpoolmanInventoryFilaments(),enabled:l&&t,staleTime:6e4,retry:!1});v.useEffect(()=>{j(Gce())},[]),v.useEffect(()=>{t&&((async()=>{Z(!0);try{const nt=await se.getCloudStatus();if(H(nt.is_authenticated),nt.is_authenticated){const gt=await se.getFilamentPresets();J(gt)}}catch(nt){console.error("Failed to fetch cloud presets:",nt),H(!1)}finally{Z(!1)}})(),l||se.getSpoolCatalog().then(W).catch(console.error),se.getColorCatalog().then(K).catch(console.error),se.getLocalPresets().then(nt=>pe(nt.filament)).catch(console.error),se.getBuiltinFilaments().then(Te).catch(console.error),i.length===0&&(async()=>{try{const nt=await se.getPrinters(),gt=await Promise.all(nt.map(ot=>se.getPrinterStatus(ot.id).catch(()=>null))),yt=[];for(let ot=0;ot({cali_idx:cn.slot_id,filament_id:cn.filament_id,setting_id:cn.setting_id||"",name:cn.name,k_value:parseFloat(cn.k_value)||0,n_coef:parseFloat(cn.n_coef)||0,extruder_id:cn.extruder_id,nozzle_diameter:cn.nozzle_diameter}))}catch{}yt.push({printer:{...Ht,connected:Zt},calibrations:Yt})}X(yt)}catch(nt){console.error("Failed to fetch printer calibrations:",nt)}})())},[t,i.length]);const ce=v.useMemo(()=>$ce(re,new Set,ae,ye),[re,ae,ye]),le=v.useMemo(()=>{const Be=qce(re,ae),nt=$.map(yt=>yt.manufacturer?.trim()).filter(yt=>!!yt),gt=new Set([...Be,...nt]);return Array.from(gt).sort((yt,ot)=>yt.localeCompare(ot))},[re,ae,$]),q=v.useMemo(()=>{const Be=$.map(gt=>gt.material?.trim()).filter(gt=>!!gt),nt=new Set([...Uce,...Be]);return Array.from(nt).sort((gt,yt)=>gt.localeCompare(yt))},[$]),L=v.useMemo(()=>{const Be=[];for(const nt of $){const gt=nt.manufacturer?.trim(),yt=nt.material?.trim();gt&&yt&&Be.push({brand:gt,material:yt})}for(const nt of re){const gt=Jh(nt.name);gt.brand&>.material&&Be.push({brand:gt.brand,material:gt.material})}for(const nt of ae){const gt=Jh(nt.name),yt=nt.filament_vendor?.trim()||gt.brand,ot=gt.material;yt&&ot&&Be.push({brand:yt,material:ot})}return Be},[re,$,ae]),ne=v.useMemo(()=>{const Be=new Map;for(const nt of L){const gt=nt.brand.toLowerCase(),yt=nt.material.toLowerCase();Be.has(gt)||Be.set(gt,new Set),Be.get(gt).add(yt)}return Be},[L]),xe=v.useMemo(()=>{const Be=new Map;for(const nt of L){const gt=nt.brand.toLowerCase(),yt=nt.material.toLowerCase();Be.has(yt)||Be.set(yt,new Set),Be.get(yt).add(gt)}return Be},[L]),we=v.useMemo(()=>{if(!b.material)return le;const Be=b.material.toLowerCase(),nt=xe.get(Be);return!nt||nt.size===0?le:le.filter(gt=>nt.has(gt.toLowerCase()))},[le,b.material,xe]),Ne=v.useMemo(()=>{if(!b.brand)return q;const Be=b.brand.toLowerCase(),nt=ne.get(Be);return!nt||nt.size===0?q:q.filter(gt=>nt.has(gt.toLowerCase()))},[q,b.brand,ne]),ve=v.useMemo(()=>Vce(b.slicer_filament,ce),[b.slicer_filament,ce]);v.useEffect(()=>{if(t){if(n){const Be=n.rgba&&/^[0-9A-Fa-f]{8}$/.test(n.rgba)?n.rgba:"808080FF";if(w({material:n.material||"",subtype:n.subtype||"",brand:n.brand||"",color_name:n.color_name_is_synthesized?"":n.color_name||"",rgba:Be,extra_colors:n.extra_colors||"",effect_type:n.effect_type||"",label_weight:n.label_weight||1e3,core_weight:n.core_weight||250,core_weight_catalog_id:n.core_weight_catalog_id??null,weight_used:f?0:n.weight_used||0,slicer_filament:n.slicer_filament||"",note:n.note||"",cost_per_kg:n.cost_per_kg??null,category:n.category||"",low_stock_threshold_pct:n.low_stock_threshold_pct??null,storage_location:n.storage_location||"",spoolman_filament_id:null}),me(n.slicer_filament_name||n.slicer_filament||""),n.k_profiles&&n.k_profiles.length>0){const nt=new Set;for(const gt of n.k_profiles)gt.cali_idx!==null&>.cali_idx!==void 0&&nt.add(`${gt.printer_id}:${gt.cali_idx}:${gt.extruder??"null"}`);ie(nt)}else ie(new Set)}else w(YI),me(""),ie(new Set),S(!1),z(1);x({}),N("filament"),P(!1),A(!1)}},[t,n,a,f]),v.useEffect(()=>{t&&Y.length>0&&G(new Set(Y.map(Be=>String(Be.printer.id))))},[t,Y]);const be=(Be,nt)=>{const gt=Fit.has(Be);l&>&&b.spoolman_filament_id!==null&&m(d("inventory.spoolmanFilamentUnlinked"),"info"),w(yt=>({...yt,[Be]:nt,...l&>&&yt.spoolman_filament_id!==null?{spoolman_filament_id:null}:{}})),Be==="weight_used"&&P(!0),Be==="storage_location"&&A(!0),g[Be]&&x(yt=>({...yt,[Be]:void 0}))},Ee=Be=>{const nt=Be.material||"",gt=Be.name||"",yt=nt&>.startsWith(nt)?gt.slice(nt.length).trim():gt,ot=(Be.color_hex??"").replace("#","").toUpperCase(),Ht=/^[0-9A-F]{6}$/.test(ot)?ot:"808080";w(Kt=>({...Kt,spoolman_filament_id:Be.id,material:nt,subtype:yt,brand:Be.vendor?.name||"",rgba:`${Ht}FF`,color_name:Be.color_name||"",label_weight:Be.weight??Kt.label_weight})),m(d("inventory.spoolmanFilamentSelected"),"success")},ze=Be=>{j(nt=>Wce(Be,nt))},_e=it({mutationFn:Be=>l?se.createSpoolmanInventorySpool(Be):se.createSpool(Be),onSuccess:async Be=>{Be?.id&&!await fe(Be.id)||(await u.invalidateQueries({queryKey:c}),o&&o([Be]),m(d("inventory.spoolCreated"),"success"),e())},onError:Be=>{Be instanceof _i&&Be.status===503?m(d("inventory.spoolmanUnreachable"),"error"):m(d("inventory.saveFailed"),"error")}}),Oe=it({mutationFn:({data:Be,qty:nt})=>l?se.bulkCreateSpoolmanInventorySpools(Be,nt):se.bulkCreateSpools(Be,nt),onSuccess:async Be=>{const nt=l&&"created"in Be?Be:null,gt=nt?nt.created:Be;if(O.size>0)for(const yt of gt)await fe(yt.id);await u.invalidateQueries({queryKey:c}),o&&o(gt),nt&&nt.failed_count>0?m(d("inventory.spoolsPartiallyCreated",{created:gt.length,total:nt.requested_count}),"warning"):m(d("inventory.spoolsCreated",{count:gt.length}),"success"),e()},onError:Be=>{Be instanceof _i&&Be.status===503?m(d("inventory.spoolmanUnreachable"),"error"):m(d("inventory.saveFailed"),"error")}}),Ie=it({mutationFn:Be=>l?se.updateSpoolmanInventorySpool(n.id,Be):se.updateSpool(n.id,Be),onSuccess:async()=>{n?.id&&!await fe(n.id)||(await u.invalidateQueries({queryKey:c}),m(d("inventory.spoolUpdated"),"success"),e())},onError:Be=>{Be instanceof _i&&Be.status===503?m(d("inventory.spoolmanUnreachable"),"error"):m(d("inventory.saveFailed"),"error")}}),Ke=it({mutationFn:()=>l?se.updateSpoolmanInventorySpool(n.id,xQ):se.updateSpool(n.id,xQ),onSuccess:async()=>{await u.invalidateQueries({queryKey:c}),m(d("inventory.rfidCleared","RFID tag cleared"),"success"),e()},onError:Be=>{Be instanceof _i&&Be.status===503?m(d("inventory.spoolmanUnreachable"),"error"):m(d("inventory.tagClearFailed"),"error")}}),{data:rt}=We({queryKey:["spool-assignments"],queryFn:()=>se.getAssignments(),enabled:t&&p}),st=n?rt?.find(Be=>Be.spool_id===n.id):void 0,{data:Le}=We({queryKey:["inventory-spools"],queryFn:()=>se.getSpools(!0),enabled:t}),{data:tt}=We({queryKey:["settings"],queryFn:se.getSettings,enabled:t}),Ce=(()=>{const Be=new Set;for(const nt of Le??[]){const gt=nt.category?.trim();gt&&Be.add(gt)}return Array.from(Be).sort((nt,gt)=>nt.localeCompare(gt))})(),Xe=tt?.low_stock_threshold??20,Ue=it({mutationFn:()=>{if(!st)throw new Error("No assignment");return se.unassignSpool(st.printer_id,st.ams_id,st.tray_id)},onSuccess:async()=>{await u.invalidateQueries({queryKey:["spool-assignments"]}),m(d("inventory.unassignSuccess","Spool unassigned"),"success"),e()},onError:Be=>{m(Be.message,"error")}}),fe=async Be=>{const nt=l?se.saveSpoolmanKProfiles:se.saveSpoolKProfiles;if(O.size===0)try{return await nt(Be,[]),!0}catch(ot){return console.error("Failed to save K-profiles:",ot),m(d("inventory.kProfileSaveFailed"),"warning"),!1}const gt=[];let yt=0;for(const ot of O){const[Ht,Kt,Zt]=ot.split(":"),Yt=parseInt(Ht),gn=parseInt(Kt),cn=Zt==="null"?0:parseInt(Zt),pt=Y.find(at=>at.printer.id===Yt);if(pt){const at=pt.calibrations.find(vt=>vt.cali_idx===gn);at?gt.push({printer_id:Yt,extruder:cn,nozzle_diameter:at.nozzle_diameter||"0.4",k_value:at.k_value,name:at.name||null,cali_idx:at.cali_idx,setting_id:at.setting_id||null}):yt++}else yt++}if(yt>0)return console.error(`saveKProfiles: ${yt} profile key(s) could not be resolved`,Array.from(O)),m(d("inventory.kProfileSaveFailed"),"warning"),!1;if(gt.length>0)try{return await nt(Be,gt),!0}catch(ot){return console.error("Failed to save K-profiles:",ot),m(d("inventory.kProfileSaveFailed"),"warning"),!1}return!0};if(v.useEffect(()=>{if(!t)return;const Be=nt=>{nt.key==="Escape"&&e()};return document.addEventListener("keydown",Be),()=>document.removeEventListener("keydown",Be)},[t,e]),!t)return null;const Ae=()=>{const Be=zce(b,F,l);if(!Be.isValid){x(Be.errors),(Be.errors.slicer_filament||Be.errors.material||Be.errors.brand||Be.errors.subtype)&&N("filament");return}const nt=ve?.displayName||de||null,gt={material:b.material||null,subtype:b.subtype||null,brand:b.brand||null,color_name:b.color_name||null,rgba:b.rgba||null,extra_colors:b.extra_colors||null,effect_type:b.effect_type||null,label_weight:b.label_weight,...l?{}:{core_weight:b.core_weight,core_weight_catalog_id:b.core_weight_catalog_id},slicer_filament:b.slicer_filament||null,slicer_filament_name:nt,nozzle_temp_min:null,nozzle_temp_max:null,note:b.note||null,cost_per_kg:b.cost_per_kg,category:b.category.trim()||null,low_stock_threshold_pct:b.low_stock_threshold_pct,...l?{spoolman_filament_id:b.spoolman_filament_id}:{}};(!p||C)&&(gt.weight_used=b.weight_used),(!p||T)&&(gt.storage_location=b.storage_location||null),p?Ie.mutate(gt):M>1?Oe.mutate({data:gt,qty:M}):_e.mutate(gt)},$e=_e.isPending||Oe.isPending||Ie.isPending||Ke.isPending||Ue.isPending;return r.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[r.jsx("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-sm",onClick:e}),r.jsxs("div",{className:"relative w-full max-w-xl mx-4 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl max-h-[90vh] flex flex-col",children:[r.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary flex-shrink-0",children:[r.jsx("h2",{className:"text-lg font-semibold text-white",children:d(p?"inventory.editSpool":f?"inventory.copySpool":"inventory.addSpool")}),r.jsx("button",{onClick:e,className:"p-1 text-bambu-gray hover:text-white rounded transition-colors",children:r.jsx(Bt,{className:"w-5 h-5"})})]}),a==="create"&&r.jsxs("div",{className:"flex items-center justify-between px-4 py-2 border-b border-bambu-dark-tertiary flex-shrink-0",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(Nc,{className:"w-4 h-4 text-amber-400"}),r.jsx("span",{className:"text-sm text-white",children:d("inventory.quickAdd")})]}),r.jsx("button",{type:"button",onClick:()=>{S(!F),F||N("filament")},className:`relative inline-flex h-5 w-9 items-center rounded-full transition-colors ${F?"bg-bambu-green":"bg-bambu-dark-tertiary"}`,children:r.jsx("span",{className:`inline-block h-3.5 w-3.5 rounded-full bg-white transition-transform ${F?"translate-x-4":"translate-x-0.5"}`})})]}),r.jsxs("div",{className:"flex border-b border-bambu-dark-tertiary flex-shrink-0",children:[r.jsxs("button",{onClick:()=>N("filament"),className:`flex-1 px-4 py-2.5 text-sm font-medium flex items-center justify-center gap-2 transition-colors ${_==="filament"?"text-bambu-green border-b-2 border-bambu-green":"text-bambu-gray hover:text-white"}`,children:[r.jsx(jS,{className:"w-4 h-4"}),d("inventory.filamentInfoTab")]}),!F&&r.jsxs("button",{onClick:()=>N("pa-profile"),className:`flex-1 px-4 py-2.5 text-sm font-medium flex items-center justify-center gap-2 transition-colors ${_==="pa-profile"?"text-bambu-green border-b-2 border-bambu-green":"text-bambu-gray hover:text-white"}`,children:[r.jsx(yfe,{className:"w-4 h-4"}),d("inventory.paProfileTab"),Q>0&&r.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded-full bg-bambu-green/20 text-bambu-green",children:Q})]})]}),r.jsx("div",{className:"p-4 overflow-y-auto flex-1",style:{scrollbarGutter:"stable"},children:_==="filament"?r.jsxs("div",{className:"space-y-6",children:[l&&!p&&r.jsx("div",{children:ge?r.jsx("p",{className:"text-sm text-red-400 px-1",children:d("inventory.spoolmanCatalogLoadFailed")}):r.jsx(Hit,{filaments:oe,isLoading:ee,selectedId:b.spoolman_filament_id,onSelect:Ee})}),r.jsxs("div",{children:[r.jsx("h3",{className:"text-sm font-semibold text-bambu-gray uppercase tracking-wide mb-3",children:d("inventory.filamentInfo")}),r.jsx(Kce,{formData:b,updateField:be,cloudAuthenticated:I,loadingCloudPresets:R,presetInputValue:de,setPresetInputValue:me,selectedPresetOption:ve,filamentOptions:ce,availableBrands:we,availableMaterials:Ne,quickAdd:F,quantity:M,onQuantityChange:z,errors:g})]}),r.jsxs("div",{children:[r.jsx("h3",{className:"text-sm font-semibold text-bambu-gray uppercase tracking-wide mb-3",children:d("inventory.color")}),r.jsx(Yce,{formData:b,updateField:be,recentColors:D,onColorUsed:ze,catalogColors:$})]}),r.jsxs("div",{children:[r.jsx("h3",{className:"text-sm font-semibold text-bambu-gray uppercase tracking-wide mb-3",children:d("inventory.additional")}),r.jsx(Xce,{formData:b,updateField:be,spoolCatalog:ue,currencySymbol:s,availableCategories:Ce,globalLowStockThreshold:Xe,spoolmanMode:l})]}),p&&n&&!l&&r.jsx("div",{children:r.jsx(Vit,{spoolId:n.id})})]}):r.jsx(Qce,{formData:b,updateField:be,printersWithCalibrations:Y,selectedProfiles:O,setSelectedProfiles:ie,expandedPrinters:U,setExpandedPrinters:G})}),r.jsxs("div",{className:"flex gap-2 p-4 border-t border-bambu-dark-tertiary flex-shrink-0",children:[p&&r.jsxs("div",{className:"flex gap-2 mr-auto",children:[r.jsxs(Me,{variant:"secondary",onClick:()=>Ke.mutate(),disabled:$e||!n?.tag_uid,children:[r.jsx($m,{className:"w-4 h-4"}),d("inventory.clearRfid","Clear RFID Tag")]}),r.jsxs(Me,{variant:"secondary",onClick:()=>Ue.mutate(),disabled:$e||!st,children:[r.jsx(iu,{className:"w-4 h-4"}),d("inventory.unassignSpool","Unassign")]})]}),r.jsxs("div",{className:"flex gap-2 ml-auto",children:[r.jsx(Me,{variant:"secondary",onClick:e,children:d("common.cancel")}),r.jsx(Me,{onClick:Ae,disabled:$e,children:$e?r.jsxs(r.Fragment,{children:[r.jsx(ut,{className:"w-4 h-4 animate-spin"}),d("common.saving")]}):r.jsxs(r.Fragment,{children:[r.jsx(us,{className:"w-4 h-4"}),d(p?"common.save":f?"inventory.copySpool":"inventory.addSpool")]})})]})]})]})]})}function Wit({isOpen:t,onClose:e,columns:n,defaultColumns:a,onSave:i}){const{t:s}=kt(),[o,l]=v.useState(n),[c,d]=v.useState(null),u=v.useRef(null);if(v.useEffect(()=>{t&&l(n.map(C=>({...C})))},[t,n]),v.useEffect(()=>{if(!t)return;const C=P=>{P.key==="Escape"&&e()};return window.addEventListener("keydown",C),()=>window.removeEventListener("keydown",C)},[t,e]),!t)return null;const m=C=>{l(P=>P.map((T,A)=>A===C?{...T,visible:!T.visible}:T))},p=(C,P)=>{P<0||P>=o.length||l(T=>{const A=[...T],[F]=A.splice(C,1);return A.splice(P,0,F),A})},f=(C,P)=>{u.current=P,d(P),C.dataTransfer.effectAllowed="move"},b=(C,P)=>{C.preventDefault(),C.dataTransfer.dropEffect="move";const T=u.current;T!==null&&T!==P&&(p(T,P),u.current=P,d(P))},w=C=>{C.preventDefault()},g=()=>{u.current=null,d(null)},x=()=>{l(a.map(C=>({...C})))},_=()=>{i(o),e()},N=o.filter(C=>C.visible).length;return r.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",onClick:e,children:r.jsx(Ct,{className:"w-full max-w-md max-h-[80vh] flex flex-col",onClick:C=>C.stopPropagation(),children:r.jsxs(At,{className:"p-6 flex flex-col min-h-0",children:[r.jsx("h3",{className:"text-lg font-semibold text-white mb-2",children:s("inventory.configureColumns")}),r.jsxs("p",{className:"text-sm text-bambu-gray mb-4",children:[s("inventory.configureColumnsDesc"),r.jsxs("span",{className:"ml-2 text-bambu-gray/60",children:["(",N," ",s("inventory.of")," ",o.length," ",s("inventory.visible"),")"]})]}),r.jsx("div",{className:"space-y-1 overflow-y-auto flex-1 min-h-0 pr-1",children:o.map((C,P)=>r.jsxs("div",{className:`flex items-center gap-2 p-2 rounded-lg border transition-colors ${c===P?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary bg-bambu-dark-tertiary/50"} ${C.visible?"":"opacity-50"}`,draggable:!0,onDragStart:T=>f(T,P),onDragOver:T=>b(T,P),onDrop:w,onDragEnd:g,children:[r.jsx("div",{className:"cursor-grab text-bambu-gray/50 hover:text-bambu-gray",children:r.jsx(Ph,{className:"w-4 h-4"})}),r.jsx("span",{className:"flex-1 font-medium text-sm text-white",children:C.label}),r.jsxs("div",{className:"flex items-center gap-0.5",children:[r.jsx("button",{onClick:()=>p(P,P-1),disabled:P===0,className:"p-1 rounded text-bambu-gray hover:bg-bambu-dark-secondary disabled:opacity-30 disabled:cursor-not-allowed",title:s("inventory.moveUp"),children:r.jsx(tl,{className:"w-4 h-4"})}),r.jsx("button",{onClick:()=>p(P,P+1),disabled:P===o.length-1,className:"p-1 rounded text-bambu-gray hover:bg-bambu-dark-secondary disabled:opacity-30 disabled:cursor-not-allowed",title:s("inventory.moveDown"),children:r.jsx(Ln,{className:"w-4 h-4"})})]}),r.jsx("button",{onClick:()=>m(P),className:`p-1.5 rounded transition-colors ${C.visible?"text-bambu-green hover:bg-bambu-green/10":"text-bambu-gray/50 hover:bg-bambu-dark-secondary"}`,title:C.visible?s("inventory.hideColumn"):s("inventory.showColumn"),children:C.visible?r.jsx(Dl,{className:"w-4 h-4"}):r.jsx(sb,{className:"w-4 h-4"})})]},C.id))}),r.jsxs("div",{className:"flex items-center gap-3 mt-4 pt-4 border-t border-bambu-dark-tertiary",children:[r.jsxs(Me,{variant:"secondary",onClick:x,className:"mr-auto",children:[r.jsx(gs,{className:"w-4 h-4"}),s("inventory.reset")]}),r.jsx(Me,{variant:"secondary",onClick:e,children:s("inventory.cancel")}),r.jsx(Me,{onClick:_,children:s("inventory.applyChanges")})]})]})})})}const Kit=[{value:"ams_30x15",i18nKey:"ams",fallbackLabel:"AMS holder (30 × 15 mm)",fallbackHint:"Single label per page; fits the popular AMS filament label holder."},{value:"box_40x30",i18nKey:"box40x30",fallbackLabel:"Box label (40 × 30 mm)",fallbackHint:"Single label per page; common DK/Brother roll size, good for filament-bag and storage-bin labels."},{value:"box_62x29",i18nKey:"box",fallbackLabel:"Box label (62 × 29 mm)",fallbackHint:"Single label per page; sized for Brother PT/QL and Dymo small labels."},{value:"avery_l7160",i18nKey:"averyL7160",fallbackLabel:"Avery L7160 — A4 sheet (38.1 × 63.5 mm × 21)",fallbackHint:"EU sheet stock; 21 labels per A4 page."},{value:"avery_5160",i18nKey:"avery5160",fallbackLabel:"Avery 5160 — US Letter sheet (25.4 × 66.7 mm × 30)",fallbackHint:"US sheet stock; 30 labels per Letter page."}];function Yit(t){const e=window.URL.createObjectURL(t);if(!window.open(e,"_blank","noopener,noreferrer")){const a=document.createElement("a");a.href=e,a.download="bambuddy-labels.pdf",document.body.appendChild(a),a.click(),document.body.removeChild(a)}setTimeout(()=>window.URL.revokeObjectURL(e),6e4)}function Xit(t){if(!t)return{backgroundColor:"#808080"};const e=t.replace(/^#/,"").slice(0,6);return e.length===6?{backgroundColor:`#${e}`}:{backgroundColor:"#808080"}}function Qit(t){const e=t.color_name??`${t.material}${t.subtype?` ${t.subtype}`:""}`,n=t.brand?` · ${t.brand}`:"";return`${e}${n}`}function Zit(t){return[t.color_name,t.material,t.subtype,t.brand,`#${t.id}`].filter(Boolean).join(" ").toLowerCase()}function Jit({isOpen:t,onClose:e,availableSpools:n,initialSelectedIds:a,spoolmanMode:i}){const{t:s}=kt(),{showToast:o}=rn(),[l,c]=v.useState(null),[d,u]=v.useState(new Set),[m,p]=v.useState(""),[f,b]=v.useState("");v.useEffect(()=>{if(t){const M=new Set(n.map(z=>z.id));u(new Set(a.filter(z=>M.has(z)))),p(""),b(""),c(null)}},[t]);const w=v.useMemo(()=>[...n].sort((M,z)=>M.id-z.id),[n]),g=v.useMemo(()=>{const M=new Set;for(const z of w)z.material&&M.add(z.material.toUpperCase());return[...M].sort()},[w]),x=v.useMemo(()=>{const M=m.trim().toLowerCase();return w.filter(z=>!(f&&(z.material||"").toUpperCase()!==f||M&&!Zit(z).includes(M)))},[w,m,f]),_=x.length>0&&x.every(M=>d.has(M.id));if(!t)return null;const N=d.size,C=N===0;function P(M){u(z=>{const I=new Set(z);return I.has(M)?I.delete(M):I.add(M),I})}function T(){u(M=>{const z=new Set(M);for(const I of x)z.add(I.id);return z})}function A(){u(M=>{const z=new Set(M);for(const I of x)z.delete(I.id);return z})}function F(){u(new Set)}async function S(M){if(C||l)return;const z=[...d].sort((I,H)=>I-H);c(M);try{const I=i?await se.printSpoolmanSpoolLabels({spool_ids:z,template:M}):await se.printSpoolLabels({spool_ids:z,template:M});Yit(I),e()}catch(I){const H=I instanceof Error?I.message:String(I);o(s("inventory.labels.error","Could not generate labels: {{msg}}",{msg:H}),"error")}finally{c(null)}}return r.jsxs("div",{className:"fixed inset-0 z-50 flex items-start sm:items-center justify-center p-4 overflow-y-auto",children:[r.jsx("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-sm",onClick:e}),r.jsxs("div",{className:"relative w-full max-w-3xl bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl max-h-[90vh] overflow-hidden flex flex-col my-auto",children:[r.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(pr,{className:"w-5 h-5 text-bambu-green"}),r.jsx("h2",{className:"text-lg font-semibold text-white",children:s("inventory.labels.title","Print spool labels")}),N>0&&r.jsxs("span",{className:"text-sm text-bambu-gray",children:["(",s("inventory.labels.selectedCount","{{count}} selected",{count:N}),")"]})]}),r.jsx("button",{onClick:e,className:"p-1 text-bambu-gray hover:text-white rounded transition-colors","aria-label":s("common.close","Close"),children:r.jsx(Bt,{className:"w-5 h-5"})})]}),r.jsxs("div",{className:"p-4 space-y-2 border-b border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"relative",children:[r.jsx(Sr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"}),r.jsx("input",{type:"search",value:m,onChange:M=>p(M.target.value),placeholder:s("inventory.labels.searchPlaceholder","Search name, brand, or #ID"),className:"w-full pl-9 pr-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray focus:outline-none focus:border-bambu-green"})]}),g.length>1&&r.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[r.jsx("span",{className:"text-xs text-bambu-gray mr-1",children:s("inventory.labels.filterByMaterial","Material:")}),r.jsx("button",{type:"button",onClick:()=>b(""),className:`px-2 py-0.5 text-xs rounded-full border transition ${f===""?"bg-bambu-green text-bambu-dark border-bambu-green":"bg-bambu-dark text-bambu-gray border-bambu-dark-tertiary hover:border-bambu-gray"}`,children:s("inventory.labels.allMaterials","All")}),g.map(M=>r.jsx("button",{type:"button",onClick:()=>b(M),className:`px-2 py-0.5 text-xs rounded-full border transition ${f===M?"bg-bambu-green text-bambu-dark border-bambu-green":"bg-bambu-dark text-bambu-gray border-bambu-dark-tertiary hover:border-bambu-gray"}`,children:M},M))]})]}),r.jsxs("div",{className:"px-4 pt-3 pb-2 flex items-center justify-between gap-3 flex-wrap",children:[r.jsx("span",{className:"text-sm text-bambu-gray",children:s("inventory.labels.pickSpools","Pick which spools to print labels for:")}),r.jsxs("div",{className:"flex items-center gap-3 text-xs",children:[r.jsx("button",{type:"button",onClick:_?A:T,disabled:x.length===0,className:"text-bambu-green hover:underline disabled:opacity-50 disabled:no-underline disabled:cursor-not-allowed",children:_?s("inventory.labels.deselectVisible","Deselect visible"):s("inventory.labels.selectVisible","Select all visible ({{count}})",{count:x.length})}),r.jsx("button",{type:"button",onClick:F,disabled:N===0,className:"text-bambu-gray hover:text-white hover:underline disabled:opacity-50 disabled:no-underline disabled:cursor-not-allowed",children:s("inventory.labels.clearAll","Clear all")})]})]}),r.jsx("div",{className:"flex-1 overflow-y-auto px-2 pb-2 min-h-0",children:x.length===0?r.jsx("div",{className:"text-center text-sm text-bambu-gray py-6",children:w.length===0?s("inventory.labels.noSpoolsToShow","No spools to show. Adjust your filter and try again."):s("inventory.labels.noMatches","No spools match the current search or filter.")}):r.jsx("ul",{className:"space-y-0.5",children:x.map(M=>{const z=d.has(M.id);return r.jsx("li",{children:r.jsxs("label",{className:"flex items-center gap-3 px-2 py-1.5 rounded hover:bg-bambu-dark-tertiary/50 cursor-pointer",children:[z?r.jsx(bs,{className:"w-4 h-4 text-bambu-green shrink-0"}):r.jsx(so,{className:"w-4 h-4 text-bambu-gray shrink-0"}),r.jsx("input",{type:"checkbox",checked:z,onChange:()=>P(M.id),className:"sr-only"}),r.jsx("span",{className:"w-4 h-4 rounded border border-black/20 shrink-0",style:Xit(M.rgba)}),r.jsx("span",{className:"flex-1 min-w-0 truncate text-sm text-white",children:Qit(M)}),r.jsxs("span",{className:"text-xs font-mono text-bambu-gray shrink-0",children:["#",M.id]})]})},M.id)})})}),r.jsx("div",{className:"px-3 pt-2 pb-2 grid grid-cols-1 sm:grid-cols-2 gap-2 border-t border-bambu-dark-tertiary",children:Kit.map(M=>{const z=l===M.value,I=s(`inventory.labels.templates.${M.i18nKey}.label`,M.fallbackLabel),H=s(`inventory.labels.templates.${M.i18nKey}.hint`,M.fallbackHint);return r.jsxs("button",{disabled:C||l!==null,onClick:()=>S(M.value),title:`${I} — ${H}`,className:"w-full text-left p-2.5 rounded-lg border border-bambu-dark-tertiary bg-bambu-dark hover:border-bambu-green hover:bg-bambu-green/10 disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:border-bambu-dark-tertiary disabled:hover:bg-bambu-dark transition flex items-center gap-3",children:[r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsx("div",{className:"font-medium text-white text-sm truncate",children:I}),r.jsx("div",{className:"text-xs text-bambu-gray mt-0.5 truncate",children:H})]}),z&&r.jsx(ut,{className:"w-4 h-4 animate-spin text-bambu-green shrink-0"})]},M.value)})}),r.jsx("div",{className:"flex justify-end gap-2 px-5 py-2 border-t border-bambu-dark-tertiary",children:r.jsx(Me,{variant:"secondary",onClick:e,disabled:l!==null,children:s("common.cancel","Cancel")})})]})]})}function yQ(t){return`${t.material}|${t.subtype||""}|${t.brand||""}|${t.color_name||""}|${t.rgba||""}|${t.extra_colors||""}|${t.effect_type||""}|${t.label_weight}`}const Zce="bambuddy-inventory-columns",HN=[{id:"id",label:"#",visible:!0},{id:"added_time",label:"Added",visible:!0},{id:"encode_time",label:"Encoded",visible:!1},{id:"last_used_time",label:"Last Used",visible:!1},{id:"rgba",label:"Color",visible:!0},{id:"material",label:"Material",visible:!0},{id:"subtype",label:"Subtype",visible:!0},{id:"color_name",label:"Color Name",visible:!1},{id:"brand",label:"Brand",visible:!0},{id:"slicer_filament",label:"Slicer Filament",visible:!1},{id:"location",label:"Location",visible:!0},{id:"storage_location",label:"Storage Location",visible:!1},{id:"label_weight",label:"Label",visible:!0},{id:"net",label:"Net",visible:!0},{id:"gross",label:"Gross",visible:!1},{id:"added_full",label:"Full",visible:!1},{id:"used",label:"Used",visible:!1},{id:"printed_total",label:"Printed Total",visible:!1},{id:"printed_since_weight",label:"Printed Since Weight",visible:!1},{id:"note",label:"Note",visible:!1},{id:"pa_k",label:"PA(K)",visible:!0},{id:"tag_id",label:"Tag ID",visible:!1},{id:"data_origin",label:"Data Origin",visible:!1},{id:"tag_type",label:"Linked Tag Type",visible:!1},{id:"stock",label:"Stock",visible:!1},{id:"remaining",label:"Remaining",visible:!0},{id:"spool_name",label:"Spool",visible:!1},{id:"cost_per_kg",label:"Cost/kg",visible:!1},{id:"weight_check",label:"Weight Check",visible:!1}];function est(){try{const t=localStorage.getItem(Zce);if(t){const e=JSON.parse(t),n=new Set(HN.map(o=>o.id)),a=new Set(e.map(o=>o.id)),i=e.filter(o=>n.has(o.id)),s=HN.filter(o=>!a.has(o.id));return[...i,...s]}}catch{}return HN.map(t=>({...t}))}function tst(t){try{localStorage.setItem(Zce,JSON.stringify(t))}catch{}}function au(t,e=!1){return e&&t>=1e3?`${(t/1e3).toFixed(1)}kg`:`${Math.round(t)}g`}const nst={PLA:"bg-green-500/20 text-green-400",ABS:"bg-red-500/20 text-red-400",PETG:"bg-blue-500/20 text-blue-400",TPU:"bg-purple-500/20 text-purple-400",ASA:"bg-orange-500/20 text-orange-400",PA:"bg-yellow-500/20 text-yellow-400",PC:"bg-cyan-500/20 text-cyan-400",PET:"bg-sky-500/20 text-sky-400"};function gF(t,e="system"){if(!t)return"-";const n=Xn(t);return n?YF(n,e):"-"}const rst={id:()=>"#",added_time:()=>"Added",encode_time:()=>"Encoded",last_used_time:()=>"Last Used",rgba:t=>t("inventory.color"),material:t=>t("inventory.material"),subtype:t=>t("inventory.subtype"),color_name:t=>t("inventory.colorName"),brand:t=>t("inventory.brand"),slicer_filament:t=>t("inventory.slicerFilament"),location:()=>"Location",storage_location:t=>t("inventory.storageLocation"),label_weight:t=>t("inventory.labelWeight"),net:t=>t("inventory.net"),gross:()=>"Gross",added_full:()=>"Full",used:t=>t("inventory.weightUsed"),printed_total:()=>"Printed Total",printed_since_weight:()=>"Printed Since Weight",note:t=>t("inventory.note"),pa_k:()=>"PA(K)",tag_id:()=>"Tag ID",data_origin:()=>"Data Origin",tag_type:()=>"Linked Tag Type",stock:t=>t("inventory.stock"),remaining:t=>t("inventory.remaining"),spool_name:t=>t("inventory.spoolName"),cost_per_kg:t=>t("inventory.costPerKg"),weight_check:t=>t("inventory.weightCheck")},XI={id:({spool:t})=>r.jsx("span",{className:"text-sm font-medium text-white",children:t.id}),added_time:({spool:t,dateFormat:e})=>r.jsx("span",{className:"text-sm text-bambu-gray",children:gF(t.created_at,e)}),encode_time:({spool:t,dateFormat:e})=>r.jsx("span",{className:"text-sm text-bambu-gray",children:gF(t.encode_time,e)}),last_used_time:({spool:t,dateFormat:e})=>r.jsx("span",{className:"text-sm text-bambu-gray",children:t.last_used?gF(t.last_used,e):"Never"}),rgba:({spool:t})=>r.jsx("div",{className:"flex items-center justify-center",children:r.jsx(rU,{rgba:t.rgba,extraColors:t.extra_colors,effectType:t.effect_type,effectSize:"table",subtype:t.subtype})}),material:({spool:t})=>r.jsx("span",{className:"text-sm text-white",children:t.material}),subtype:({spool:t})=>r.jsx("span",{className:"text-sm text-bambu-gray",children:t.subtype||"-"}),color_name:({spool:t})=>r.jsx("span",{className:"text-sm text-bambu-gray",children:PT(t.color_name,t.rgba)||"-"}),brand:({spool:t})=>r.jsx("span",{className:"text-sm text-bambu-gray",children:t.brand||"-"}),slicer_filament:({spool:t})=>r.jsx("span",{className:"text-sm text-bambu-gray",title:t.slicer_filament||void 0,children:t.slicer_filament_name||t.slicer_filament||"-"}),location:({spool:t,assignmentMap:e})=>{const n=e[t.id];if(!n)return r.jsx("span",{className:"text-sm text-bambu-gray",children:"-"});const a=n.printer_name||`Printer ${n.printer_id}`,i=n.ams_id===254||n.ams_id===255,s=!i&&n.ams_id>=128,o=c_(n.ams_id,n.tray_id,s,i);return r.jsxs("span",{className:"inline-flex items-center px-1.5 py-0.5 rounded text-xs font-medium bg-purple-500/20 text-purple-400",children:[a," ",o,n.ams_label?` (${n.ams_label})`:""]})},storage_location:({spool:t})=>t.storage_location?r.jsx("span",{className:"inline-flex items-center px-1.5 py-0.5 rounded text-xs font-medium bg-blue-500/20 text-blue-400",children:t.storage_location}):r.jsx("span",{className:"text-sm text-bambu-gray",children:"-"}),label_weight:({spool:t})=>r.jsx("span",{className:"text-sm text-white",children:au(t.label_weight)}),net:({remaining:t})=>r.jsx("span",{className:"text-sm text-white",children:au(t)}),gross:({spool:t,remaining:e})=>r.jsx("span",{className:"text-sm text-bambu-gray",children:au(e+t.core_weight)}),added_full:({spool:t})=>r.jsx("span",{className:"text-sm text-bambu-gray",children:t.added_full==null?"-":t.added_full?"Yes":"No"}),used:({spool:t})=>r.jsx("span",{className:"text-sm text-bambu-gray",children:t.weight_used>0?au(t.weight_used):"-"}),printed_total:()=>r.jsx("span",{className:"text-sm text-bambu-gray/50",children:"-"}),printed_since_weight:()=>r.jsx("span",{className:"text-sm text-bambu-gray/50",children:"-"}),note:({spool:t})=>r.jsx("span",{className:"text-sm text-bambu-gray max-w-[150px] truncate block",title:t.note||void 0,children:t.note||"-"}),pa_k:({spool:t})=>(t.k_profiles?.length??0)===0?r.jsx("span",{className:"text-sm text-bambu-gray",children:"-"}):r.jsx("span",{className:"inline-flex items-center px-1.5 py-0.5 rounded text-xs font-medium bg-bambu-green/20 text-bambu-green",children:"K"}),tag_id:({spool:t})=>{const e=t.tag_uid||t.tray_uuid;return e?r.jsx("span",{className:"text-sm text-bambu-gray font-mono",title:e,children:e.length>12?`${e.slice(0,6)}...${e.slice(-4)}`:e}):r.jsx("span",{className:"text-sm text-bambu-gray/50",children:"-"})},data_origin:({spool:t})=>r.jsx("span",{className:"text-sm text-bambu-gray",children:t.data_origin||"-"}),tag_type:({spool:t})=>r.jsx("span",{className:"text-sm text-bambu-gray",children:t.tag_type||"-"}),stock:({spool:t,t:e})=>t.slicer_filament?r.jsx("span",{className:"text-sm text-bambu-gray",children:"-"}):r.jsx("span",{className:"inline-flex items-center px-1.5 py-0.5 rounded text-xs font-medium bg-amber-500/20 text-amber-400",children:e("inventory.stock")}),remaining:({remaining:t,pct:e})=>r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("div",{className:"flex-1 h-2 bg-bambu-dark-tertiary rounded-full overflow-hidden",children:r.jsx("div",{className:`h-full rounded-full ${e>50?"bg-bambu-green":e>20?"bg-yellow-500":"bg-red-500"}`,style:{width:`${Math.min(e,100)}%`}})}),r.jsxs("span",{className:"text-xs text-bambu-gray min-w-[40px] text-right",children:[Math.round(t),"g"]})]}),spool_name:({spool:t,catalogMap:e})=>{const n=t.core_weight_catalog_id!=null?e[t.core_weight_catalog_id]:void 0;return r.jsx("span",{className:"text-sm text-bambu-gray",children:n?.name||"-"})},cost_per_kg:({spool:t,currencySymbol:e})=>r.jsx("span",{className:"text-sm text-bambu-gray",children:t.cost_per_kg!=null?`${e}${t.cost_per_kg.toFixed(2)}`:"-"}),weight_check:({spool:t,onSyncWeight:e})=>{const n=t.last_scale_weight;if(n==null)return r.jsx("span",{className:"text-sm text-bambu-gray/50",title:"No scale measurement",children:"-"});const a=t.core_weight||0,i=Math.max(0,t.label_weight-t.weight_used)+a;let s,o;n0?`+${Math.round(s)}`:`${Math.round(s)}`,c=o?`Scale: ${Math.round(n)}g Calculated: ${Math.round(i)}g Difference: ${l}g (within tolerance)`:`Scale: ${Math.round(n)}g Calculated: ${Math.round(i)}g diff --git a/static/index.html b/static/index.html index 759ae0dc0..1b65cdfec 100644 --- a/static/index.html +++ b/static/index.html @@ -26,7 +26,7 @@ - +