From 839be41133b590896b4520b3361ced926d1c601d Mon Sep 17 00:00:00 2001 From: maziggy Date: Sat, 21 Feb 2026 08:17:59 +0100 Subject: [PATCH] Fix support bundle leaking personal data (#473) The log sanitizer only used regex patterns, missing arbitrary user-chosen strings (printer names, usernames). Tasmota smart plug credentials were logged verbatim in URLs by httpx. - Make _sanitize_log_content() database-aware: query Printer names/serials, User usernames, and Bambu Cloud email for exact-string replacement (longest-first, skip <3 chars to prevent over-redaction) - Fix serial regex leaking first 3 chars (remove capture group partial redaction), add case-insensitive flag - Move Tasmota credentials from URL-embedded (http://user:pass@host) to httpx auth= parameter so they never appear in logs - Add URL credentials regex as defense-in-depth for user:pass@ in logs - Add 'username' and 'path' to settings sensitive_keys filter (catches smtp_username, slicer_binary_path in support-info.json) --- .pre-commit-config.yaml | 7 -- CHANGELOG.md | 1 + backend/app/api/routes/support.py | 64 ++++++++++++++----- backend/app/services/tasmota.py | 16 ++--- backend/tests/unit/services/test_tasmota.py | 9 +-- .../components/SpoolFormModal.test.tsx | 2 + frontend/src/pages/SystemInfoPage.tsx | 4 +- .../{index-CPHVOZPV.js => index-DeeYbjZC.js} | 2 +- static/index.html | 2 +- 9 files changed, 65 insertions(+), 42 deletions(-) rename static/assets/{index-CPHVOZPV.js => index-DeeYbjZC.js} (99%) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index e343f6aba..1e221321d 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -49,10 +49,3 @@ repos: pass_filenames: false files: ^frontend/src/ types_or: [ts, tsx] - - id: frontend-lint - name: ESLint - entry: bash -c 'cd frontend && npx eslint .' - language: system - pass_filenames: false - files: ^frontend/src/ - types_or: [ts, tsx] diff --git a/CHANGELOG.md b/CHANGELOG.md index 33b85637c..200b2a017 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,7 @@ All notable changes to Bambuddy will be documented in this file. ## [0.2.1b2] - Unreleased ### Fixed +- **Support Bundle Leaking Personal Data** ([#473](https://github.com/maziggy/bambuddy/issues/473)) — The support bundle's log sanitizer only used regex patterns, which can't detect arbitrary user-chosen strings like printer names and usernames. Now queries the database for known sensitive values (printer names, serial numbers, auth usernames, Bambu Cloud email) and does exact-string replacement before the regex pass. Serial number regex no longer leaks the first 3 characters (was using a capture group for partial redaction). Tasmota smart plug credentials embedded in URLs (`http://user:pass@host`) were logged verbatim by httpx; now uses httpx's `auth` parameter for HTTP Basic auth so credentials never appear in the URL. Added `username` and `path` to the settings key filter to redact `smtp_username` and `slicer_binary_path` from the support info JSON. A URL credentials regex provides defense-in-depth for any remaining `user:pass@` patterns in logs. IP addresses are no longer redacted from the bundle as they are needed for connectivity debugging. Updated the frontend privacy disclaimer and wiki documentation to reflect the new behavior. - **Spool Usage Lost When Spool Runs Empty Mid-Print** ([#459](https://github.com/maziggy/bambuddy/issues/459)) — When a spool ran empty during a print and the AMS auto-switched to a backup spool, the `on_ams_change` handler eagerly deleted the empty spool's `SpoolAssignment` record (fingerprint mismatch). When `on_print_complete` later ran, it queried `SpoolAssignment` live from the database, found nothing, and silently dropped usage. Now snapshots all spool assignments at print start into the `PrintSession`, so usage is correctly attributed at completion regardless of mid-print AMS changes. - **K-Profile Response Race Condition Crash** ([#462](https://github.com/maziggy/bambuddy/issues/462)) — An unsolicited or late K-profile MQTT response could crash the MQTT handler with `AttributeError: 'NoneType' object has no attribute 'set'`. The MQTT callback thread checked `self._pending_kprofile_response` (not None) at line 2698, but between that check and the `.set()` call, the asyncio thread's `finally` block in `get_kprofiles()` could clear the attribute to `None` after a timeout — a classic TOCTOU race. Fixed by capturing the event reference in a local variable before the check. - **Queue Stuck on "Busy" for "Any Model" Jobs** ([#435](https://github.com/maziggy/bambuddy/issues/435)) — When a print was queued with "Any [Model]" (e.g., "Any P1S"), it was created with `printer_id=NULL` and `target_model="P1S"`. After the assigned printer finished, the queue widget queried only for items matching `printer_id=X`, missing the next pending model-based item (`printer_id IS NULL`). With no next item found, the "Clear Plate & Start Next" button never appeared, leaving the scheduler stuck reporting "Busy". The queue API now accepts an optional `target_model` parameter; when combined with `printer_id`, it uses OR logic to also return unassigned items whose `target_model` matches the printer's model. The frontend passes the printer's model through to this query. Additionally, the backend now resolves the printer's model server-side from the database when the frontend doesn't provide `target_model` (e.g., when the printer was added without selecting a model), ensuring the OR logic works regardless of whether the client knows the printer's model. diff --git a/backend/app/api/routes/support.py b/backend/app/api/routes/support.py index 30eb32df1..bfa283a5e 100644 --- a/backend/app/api/routes/support.py +++ b/backend/app/api/routes/support.py @@ -512,11 +512,13 @@ async def _collect_support_info() -> dict: "cloud_token", "mqtt_password", "email", + "username", "vapid", "private_key", "public_key", "webhook", "url", + "path", # Filesystem paths may contain usernames "config", # URLs may contain IPs, configs may have embedded secrets } for s in all_settings: @@ -660,17 +662,26 @@ async def _collect_support_info() -> dict: return info -def _sanitize_log_content(content: str) -> str: +def _sanitize_log_content(content: str, sensitive_strings: dict[str, str] | None = None) -> str: """Remove sensitive data from log content.""" - # Replace IP addresses with [IP] - content = re.sub(r"\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b", "[IP]", content) + # First, replace known sensitive values (database-aware exact matching) + # This catches printer names, usernames, and other arbitrary user-chosen strings + # that regex patterns cannot detect + if sensitive_strings: + # Sort by length descending to avoid partial matches (e.g. "My Printer 1" before "My Printer") + for value, label in sorted(sensitive_strings.items(), key=lambda x: len(x[0]), reverse=True): + if len(value) < 3: + continue # Skip very short strings to prevent over-redaction + content = re.sub(re.escape(value), label, content) + + # Replace credentials in URLs (e.g. http://user:pass@host) + content = re.sub(r"(https?://)[^/:@\s]+:[^/@\s]+@", r"\1[CREDENTIALS]@", content) # Replace email addresses content = re.sub(r"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b", "[EMAIL]", content) # Replace Bambu Lab printer serial numbers (format: 00M/01D/01S/01P/03W + alphanumeric, 12-16 chars total) - # These appear in logs as [SERIAL] or in messages - content = re.sub(r"\b(0[0-3][A-Z0-9])[A-Z0-9]{9,13}\b", r"\1[SERIAL]", content) + content = re.sub(r"\b0[0-3][A-Z0-9][A-Z0-9]{9,13}\b", "[SERIAL]", content, flags=re.IGNORECASE) # Replace paths with usernames content = re.sub(r"/home/[^/\s]+/", "/home/[user]/", content) @@ -680,7 +691,7 @@ def _sanitize_log_content(content: str) -> str: return content -def _get_log_content(max_bytes: int = 10 * 1024 * 1024) -> bytes: +def _get_log_content(max_bytes: int = 10 * 1024 * 1024, sensitive_strings: dict[str, str] | None = None) -> bytes: """Get log file content, limited to max_bytes from the end.""" log_file = settings.log_dir / "bambuddy.log" if not log_file.exists(): @@ -698,7 +709,7 @@ def _get_log_content(max_bytes: int = 10 * 1024 * 1024) -> bytes: content = f.read().decode("utf-8", errors="replace") # Sanitize sensitive data - content = _sanitize_log_content(content) + content = _sanitize_log_content(content, sensitive_strings) return content.encode("utf-8") @@ -707,16 +718,39 @@ async def generate_support_bundle( _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_READ), ): """Generate a support bundle ZIP file for issue reporting.""" - # Check if debug logging is enabled + # Check if debug logging is enabled and collect sensitive values for redaction async with async_session() as db: enabled, _enabled_at = await _get_debug_setting(db) - if not enabled: - raise HTTPException( - status_code=400, - detail="Debug logging must be enabled before generating a support bundle. " - "Please enable debug logging, reproduce the issue, then generate the bundle.", - ) + if not enabled: + raise HTTPException( + status_code=400, + detail="Debug logging must be enabled before generating a support bundle. " + "Please enable debug logging, reproduce the issue, then generate the bundle.", + ) + + # Collect known sensitive values for log redaction + sensitive_strings: dict[str, str] = {} + + # Printer names and serial numbers + result = await db.execute(select(Printer.name, Printer.serial_number)) + for name, serial in result.all(): + if name: + sensitive_strings[name] = "[PRINTER]" + if serial: + sensitive_strings[serial] = "[SERIAL]" + + # Auth usernames + result = await db.execute(select(User.username)) + for (username,) in result.all(): + if username: + sensitive_strings[username] = "[USER]" + + # Bambu Cloud email + result = await db.execute(select(Settings.value).where(Settings.key == "bambu_cloud_email")) + cloud_email = result.scalar_one_or_none() + if cloud_email: + sensitive_strings[cloud_email] = "[EMAIL]" # Collect support info support_info = await _collect_support_info() @@ -730,7 +764,7 @@ async def generate_support_bundle( zf.writestr("support-info.json", json.dumps(support_info, indent=2, default=str)) # Add log file - log_content = _get_log_content() + log_content = _get_log_content(sensitive_strings=sensitive_strings) zf.writestr("bambuddy.log", log_content) zip_buffer.seek(0) diff --git a/backend/app/services/tasmota.py b/backend/app/services/tasmota.py index ba1b00e17..188cdd58b 100644 --- a/backend/app/services/tasmota.py +++ b/backend/app/services/tasmota.py @@ -18,19 +18,10 @@ class TasmotaService: def __init__(self, timeout: float = 5.0): self.timeout = timeout - def _build_url( - self, - ip: str, - command: str, - username: str | None = None, - password: str | None = None, - ) -> str: + def _build_url(self, ip: str, command: str) -> str: """Build Tasmota command URL.""" # URL encode the command cmd = command.replace(" ", "%20") - - if username and password: - return f"http://{username}:{password}@{ip}/cm?cmnd={cmd}" return f"http://{ip}/cm?cmnd={cmd}" @staticmethod @@ -53,11 +44,12 @@ class TasmotaService: if not self._validate_ip(ip): logger.warning("Blocked Tasmota request to invalid IP: %s", ip) return None - url = self._build_url(ip, command, username, password) + url = self._build_url(ip, command) + auth = (username, password) if username and password else None try: async with httpx.AsyncClient(timeout=self.timeout) as client: - response = await client.get(url) + response = await client.get(url, auth=auth) response.raise_for_status() return response.json() except httpx.TimeoutException: diff --git a/backend/tests/unit/services/test_tasmota.py b/backend/tests/unit/services/test_tasmota.py index cfb6316f9..5c88943de 100644 --- a/backend/tests/unit/services/test_tasmota.py +++ b/backend/tests/unit/services/test_tasmota.py @@ -38,10 +38,11 @@ class TestTasmotaService: url = service._build_url("192.168.1.100", "Power On") assert url == "http://192.168.1.100/cm?cmnd=Power%20On" - def test_build_url_with_auth(self, service): - """Verify URL includes credentials when provided.""" - url = service._build_url("192.168.1.100", "Power On", username="admin", password="secret") - assert url == "http://admin:secret@192.168.1.100/cm?cmnd=Power%20On" + def test_build_url_never_includes_credentials(self, service): + """Verify URL never contains credentials (they go via httpx auth param).""" + url = service._build_url("192.168.1.100", "Power On") + assert url == "http://192.168.1.100/cm?cmnd=Power%20On" + assert "@" not in url def test_build_url_encodes_special_characters(self, service): """Verify special characters in commands are encoded.""" diff --git a/frontend/src/__tests__/components/SpoolFormModal.test.tsx b/frontend/src/__tests__/components/SpoolFormModal.test.tsx index c356cda03..a72de1ae9 100644 --- a/frontend/src/__tests__/components/SpoolFormModal.test.tsx +++ b/frontend/src/__tests__/components/SpoolFormModal.test.tsx @@ -140,6 +140,8 @@ describe('SpoolFormModal weightTouched', () => { // Change the remaining weight from 700 to 500 (weight_used becomes 1000 - 500 = 500) fireEvent.change(remainingInput, { target: { value: '500' } }); + // Blur triggers updateField('weight_used', ...) which sets weightTouched + fireEvent.blur(remainingInput); // Click Save const saveButton = screen.getByRole('button', { name: /save/i }); diff --git a/frontend/src/pages/SystemInfoPage.tsx b/frontend/src/pages/SystemInfoPage.tsx index e7aef9d1c..40c98beea 100644 --- a/frontend/src/pages/SystemInfoPage.tsx +++ b/frontend/src/pages/SystemInfoPage.tsx @@ -335,7 +335,7 @@ export function SystemInfoPage() {

{t('support.notCollected', 'NOT collected:')}

- {t('support.privacyNote', 'IP addresses in logs are replaced with [IP] and email addresses with [EMAIL].')} + {t('support.privacyNote', 'Email addresses in logs are replaced with [EMAIL], printer names with [PRINTER], and serial numbers with [SERIAL].')}

diff --git a/static/assets/index-CPHVOZPV.js b/static/assets/index-DeeYbjZC.js similarity index 99% rename from static/assets/index-CPHVOZPV.js rename to static/assets/index-DeeYbjZC.js index 4e85bde8f..9d3d97295 100644 --- a/static/assets/index-CPHVOZPV.js +++ b/static/assets/index-DeeYbjZC.js @@ -8683,4 +8683,4 @@ Accuracy: ${t.time_accuracy.toFixed(0)}%`:t.actual_time_seconds?`Actual: ${Qs(t. `)+` `+n+"}"}return String(t)}function RZe({setting:t,onClose:e,onDeleted:n,onDuplicate:r,onEdit:a,hasPermission:s,t:o}){const{showToast:l}=cn(),c=tn(),[u,d]=w.useState(!1),{data:h,isLoading:f}=Je({queryKey:["cloudSettingDetail",t.setting_id],queryFn:()=>ne.getCloudSettingDetail(t.setting_id)}),p=ot({mutationFn:()=>ne.deleteCloudSetting(t.setting_id),onSuccess:()=>{l(o("profiles.presets.toast.deleted")),c.invalidateQueries({queryKey:["cloudSettings"]}),n()},onError:g=>l(g.message,"error")}),x=r0(t.setting_id),v=s4(t.name,h?.setting?.inherits);return i.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:i.jsx(vt,{className:"w-full max-w-3xl max-h-[90vh] flex flex-col overflow-hidden",children:i.jsxs(_t,{className:"p-0 flex flex-col min-h-0 flex-1",children:[i.jsxs("div",{className:"flex-shrink-0 flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("h2",{className:"text-xl font-semibold text-white truncate",children:t.name}),x&&i.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")})]}),i.jsxs("div",{className:"flex items-center gap-2 mt-1 text-sm text-bambu-gray",children:[i.jsx("span",{className:"capitalize",children:o(`profiles.presets.types.${t.type}`)}),v.printer&&i.jsxs(i.Fragment,{children:[i.jsx("span",{children:"•"}),i.jsx("span",{children:v.printer})]})]})]}),i.jsx("button",{onClick:e,className:"p-2 text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary rounded-lg transition-colors",children:i.jsx(Ft,{className:"w-5 h-5"})})]}),i.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto p-4",children:f?i.jsx("div",{className:"flex items-center justify-center py-16",children:i.jsx(it,{className:"w-8 h-8 text-bambu-green animate-spin"})}):h?i.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:eF(h)}):i.jsx("div",{className:"text-center py-16 text-bambu-gray",children:o("profiles.presets.failedToLoadDetails")})}),u?i.jsxs("div",{className:"flex-shrink-0 p-4 border-t border-bambu-dark-tertiary bg-red-500/5",children:[i.jsxs("div",{className:"flex items-center gap-2 mb-3 text-red-400",children:[i.jsx(Tn,{className:"w-5 h-5"}),i.jsx("span",{className:"font-medium",children:o("profiles.presets.deleteConfirm")})]}),i.jsx("p",{className:"text-sm text-bambu-gray mb-4",children:o("profiles.presets.deleteWarning",{name:t.name})}),i.jsxs("div",{className:"flex gap-2",children:[i.jsx(Ce,{variant:"secondary",onClick:()=>d(!1),disabled:p.isPending,className:"flex-1",children:o("common.cancel")}),i.jsxs(Ce,{variant:"danger",onClick:()=>p.mutate(),disabled:p.isPending,className:"flex-1",children:[p.isPending?i.jsx(it,{className:"w-4 h-4 animate-spin"}):i.jsx(Jt,{className:"w-4 h-4"}),o("common.delete")]})]})]}):i.jsx("div",{className:"flex-shrink-0 p-4 border-t border-bambu-dark-tertiary",children:i.jsxs("div",{className:"flex gap-2",children:[i.jsx(Ce,{variant:"secondary",onClick:e,className:"flex-1",children:o("common.close")}),i.jsxs(Ce,{variant:"secondary",onClick:r,disabled:!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.presets.noDuplicatePermission"),children:[i.jsx(Yl,{className:"w-4 h-4"}),o("profiles.presets.duplicate")]}),x&&i.jsxs(i.Fragment,{children:[i.jsxs(Ce,{variant:"secondary",onClick:a,disabled:f||!h||!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.presets.noEditPermission"),children:[i.jsx($a,{className:"w-4 h-4"}),o("common.edit")]}),i.jsx(Ce,{variant:"danger",onClick:()=>d(!0),disabled:!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.presets.noDeletePermission"),children:i.jsx(Jt,{className:"w-4 h-4"})})]})]})})]})})})}function Oie(){try{const t=localStorage.getItem("bambusy_preset_templates");return t?JSON.parse(t):[]}catch{return[]}}function Iie(t){localStorage.setItem("bambusy_preset_templates",JSON.stringify(t))}function FZe({onClose:t,onApply:e,t:n}){const{showToast:r}=cn(),[a,s]=w.useState(Oie),[o,l]=w.useState("all"),[c,u]=w.useState(null),[d,h]=w.useState(""),[f,p]=w.useState(""),[x,v]=w.useState("{}"),[g,y]=w.useState(null),[_,N]=w.useState(null),k=o==="all"?a:a.filter(U=>U.type===o),A=U=>{s(U),Iie(U)},M=U=>{const R=a.filter(V=>V.id!==U);A(R),N(null),r(n("profiles.templates.toast.deleted"))},C=U=>{u(U.id),h(U.name),p(U.description),v(JSON.stringify(U.settings,null,2)),y(null)},j=()=>{if(!(!c||!d.trim()))try{const U=JSON.parse(x),R=a.map(V=>V.id===c?{...V,name:d.trim(),description:f.trim(),settings:U}:V);A(R),u(null),r(n("profiles.templates.toast.updated"))}catch(U){y(U.message)}},P=()=>{u(null),h(""),p(""),v("{}"),y(null)},E=U=>{const R=a.map(V=>V.id===U?{...V,showInModal:!V.showInModal}:V);A(R)},B={filament:{label:n("profiles.presets.types.filament"),icon:IC,color:"text-amber-400"},print:{label:n("profiles.presets.types.process"),icon:ed,color:"text-blue-400"},printer:{label:n("profiles.presets.types.printer"),icon:xr,color:"text-purple-400"}},O=_?a.find(U=>U.id===_):null;return w.useEffect(()=>{const U=R=>{R.key==="Escape"&&(_?N(null):c?P():t())};return window.addEventListener("keydown",U),()=>window.removeEventListener("keydown",U)},[_,c,t]),i.jsxs("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:[O&&i.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-60",children:i.jsx(vt,{className:"w-full max-w-md",children:i.jsxs(_t,{className:"p-6",children:[i.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[i.jsx("div",{className:"p-2 bg-red-500/20 rounded-lg",children:i.jsx(Tn,{className:"w-6 h-6 text-red-400"})}),i.jsxs("div",{children:[i.jsx("h3",{className:"text-lg font-semibold text-white",children:n("profiles.templates.deleteTitle")}),i.jsx("p",{className:"text-sm text-bambu-gray",children:n("profiles.templates.deleteWarning")})]})]}),i.jsx("p",{className:"text-white mb-6",children:n("profiles.templates.deleteConfirm",{name:O.name})}),i.jsxs("div",{className:"flex gap-2",children:[i.jsx(Ce,{variant:"secondary",onClick:()=>N(null),className:"flex-1",children:n("common.cancel")}),i.jsxs(Ce,{onClick:()=>M(_),className:"flex-1 bg-red-500 hover:bg-red-600",children:[i.jsx(Jt,{className:"w-4 h-4"}),n("common.delete")]})]})]})})}),i.jsx(vt,{className:"w-full max-w-2xl max-h-[80vh] flex flex-col",children:i.jsxs(_t,{className:"p-0 flex flex-col h-full",children:[i.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[i.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[i.jsx(lb,{className:"w-5 h-5 text-amber-400"}),n("profiles.templates.title")]}),i.jsx("button",{onClick:t,className:"text-bambu-gray hover:text-white",children:i.jsx(Ft,{className:"w-5 h-5"})})]}),i.jsxs("div",{className:"flex items-center gap-2 p-4 border-b border-bambu-dark-tertiary",children:[i.jsx("span",{className:"text-sm text-bambu-gray",children:n("profiles.templates.typeFilter")}),["all","filament","print","printer"].map(U=>i.jsx("button",{onClick:()=>l(U),className:`px-3 py-1 text-sm rounded-lg transition-colors ${o===U?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:U==="all"?n("common.all"):B[U].label},U))]}),i.jsx("div",{className:"flex-1 overflow-y-auto p-4",children:k.length===0?i.jsxs("div",{className:"text-center py-12 text-bambu-gray",children:[i.jsx(lb,{className:"w-12 h-12 mx-auto mb-4 opacity-30"}),i.jsx("p",{children:n("profiles.templates.noTemplates")}),i.jsx("p",{className:"text-sm mt-1",children:n("profiles.templates.createFirst")})]}):i.jsx("div",{className:"space-y-2",children:k.map(U=>{const R=B[U.type],V=R.icon;return c===U.id?i.jsxs("div",{className:"p-4 bg-bambu-dark rounded-lg border border-bambu-green",children:[i.jsxs("div",{className:"grid grid-cols-2 gap-3 mb-3",children:[i.jsx("input",{type:"text",value:d,onChange:G=>h(G.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}),i.jsx("input",{type:"text",value:f,onChange:G=>p(G.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"})]}),i.jsxs("div",{className:"mb-3",children:[i.jsx("label",{className:"text-xs text-bambu-gray mb-1 block",children:n("profiles.templates.settingsJson")}),i.jsx("textarea",{value:x,onChange:G=>{v(G.target.value),y(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&&i.jsx("p",{className:"text-xs text-red-400 mt-1",children:g})]}),i.jsxs("div",{className:"flex gap-2",children:[i.jsxs(Ce,{size:"sm",onClick:j,disabled:!d.trim(),children:[i.jsx(ps,{className:"w-4 h-4"}),"Save"]}),i.jsx(Ce,{size:"sm",variant:"secondary",onClick:P,children:"Cancel"})]})]},U.id):i.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:[i.jsx(V,{className:`w-5 h-5 ${R.color} flex-shrink-0`}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsx("p",{className:"text-sm font-medium text-white",children:U.name}),i.jsx("p",{className:"text-xs text-bambu-gray truncate",children:U.description})]}),i.jsx("span",{className:"text-xs text-bambu-gray-dark px-2 py-1 bg-bambu-dark-secondary rounded",children:n("profiles.templates.fieldsCount",{count:Object.keys(U.settings).length})}),i.jsx("button",{onClick:()=>E(U.id),className:`p-1 transition-colors ${U.showInModal?"text-bambu-green hover:text-bambu-green/70":"text-bambu-gray hover:text-white"}`,title:U.showInModal?n("profiles.templates.shownInModals"):n("profiles.templates.hiddenInModals"),children:U.showInModal?i.jsx(Ql,{className:"w-4 h-4"}):i.jsx(o0,{className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>e(U),className:"px-3 py-1 text-xs bg-bambu-green/20 text-bambu-green rounded hover:bg-bambu-green/30 transition-colors",children:n("profiles.templates.apply")}),i.jsx("button",{onClick:()=>C(U),className:"p-1 text-bambu-gray hover:text-white",title:n("common.edit"),children:i.jsx($a,{className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>N(U.id),className:"p-1 text-bambu-gray hover:text-red-400",title:n("common.delete"),children:i.jsx(Jt,{className:"w-4 h-4"})})]},U.id)})})})]})})]})}function zie({onClose:t,leftPreset:e,rightPreset:n,leftLabel:r,rightLabel:a,t:s}){const[o,l]=w.useState("changes"),[c,u]=w.useState(""),d=w.useMemo(()=>{const x=new Set([...Object.keys(e),...Object.keys(n)]),v=[];for(const g of x){if(g==="inherits"||g==="version")continue;const y=e[g],_=n[g],N=g in e,k=g in n;let A;!N&&k?A="added":N&&!k?A="removed":JSON.stringify(y)!==JSON.stringify(_)?A="changed":A="same",v.push({key:g,left:y,right:_,status:A})}return v.sort((g,y)=>{const _={changed:0,added:1,removed:2,same:3};return _[g.status]!==_[y.status]?_[g.status]-_[y.status]:g.key.localeCompare(y.key)})},[e,n]),h=w.useMemo(()=>{let x=[...d];if(o==="changes"&&(x=x.filter(v=>v.status!=="same")),c){const v=c.toLowerCase();x=x.filter(g=>g.key.toLowerCase().includes(v)||String(g.left).toLowerCase().includes(v)||String(g.right).toLowerCase().includes(v))}return x},[d,o,c]),f=w.useMemo(()=>({added:d.filter(x=>x.status==="added").length,removed:d.filter(x=>x.status==="removed").length,changed:d.filter(x=>x.status==="changed").length,same:d.filter(x=>x.status==="same").length}),[d]),p=x=>{if(x===void 0)return"—";if(x===null)return"null";if(Array.isArray(x))return x.length===0?"[]":x.length===1?String(x[0]):x.join(", ");if(typeof x=="object")return JSON.stringify(x);const v=String(x);if(v.includes("\\n")||v.length>100){const g=v.split("\\n").length;if(g>1)return`[${g} lines of G-code/script]`;if(v.length>100)return v.substring(0,100)+"…"}return v};return w.useEffect(()=>{const x=v=>{v.key==="Escape"&&t()};return window.addEventListener("keydown",x),()=>window.removeEventListener("keydown",x)},[t]),i.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:i.jsx(vt,{className:"w-full max-w-4xl max-h-[85vh] flex flex-col overflow-hidden",children:i.jsxs(_t,{className:"p-0 flex flex-col min-h-0 flex-1",children:[i.jsxs("div",{className:"flex-shrink-0 flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[i.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[i.jsx($g,{className:"w-5 h-5 text-blue-400"}),s("profiles.diff.title")]}),i.jsx("button",{onClick:t,className:"text-bambu-gray hover:text-white",children:i.jsx(Ft,{className:"w-5 h-5"})})]}),i.jsxs("div",{className:"flex-shrink-0 grid grid-cols-2 gap-4 p-4 border-b border-bambu-dark-tertiary bg-bambu-dark",children:[i.jsxs("div",{className:"text-center",children:[i.jsx("span",{className:"text-sm text-bambu-gray",children:s("profiles.diff.left")}),i.jsx("p",{className:"text-white font-medium truncate",children:r})]}),i.jsxs("div",{className:"text-center",children:[i.jsx("span",{className:"text-sm text-bambu-gray",children:s("profiles.diff.right")}),i.jsx("p",{className:"text-white font-medium truncate",children:a})]})]}),i.jsxs("div",{className:"flex-shrink-0 flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex items-center gap-4 text-sm",children:[i.jsxs("span",{className:"flex items-center gap-1 text-green-400",children:[i.jsx(Xn,{className:"w-3.5 h-3.5"}),f.added," ",s("profiles.diff.added")]}),i.jsxs("span",{className:"flex items-center gap-1 text-red-400",children:[i.jsx(x1,{className:"w-3.5 h-3.5"}),f.removed," ",s("profiles.diff.removed")]}),i.jsxs("span",{className:"flex items-center gap-1 text-amber-400",children:[i.jsx(Qj,{className:"w-3.5 h-3.5"}),f.changed," ",s("profiles.diff.changed")]}),i.jsxs("span",{className:"flex items-center gap-1 text-bambu-gray",children:[i.jsx(LM,{className:"w-3.5 h-3.5"}),f.same," ",s("profiles.diff.same")]})]}),i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsxs("div",{className:"relative",children:[i.jsx(kr,{className:"absolute left-2 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),i.jsx("input",{type:"text",value:c,onChange:x=>u(x.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"})]}),f.same>0&&i.jsxs("div",{className:"flex rounded overflow-hidden border border-bambu-dark-tertiary",children:[i.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")}),i.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")})]})]})]}),i.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto",children:h.length===0?i.jsxs("div",{className:"text-center py-12 text-bambu-gray",children:[i.jsx(LM,{className:"w-12 h-12 mx-auto mb-4 opacity-30"}),i.jsx("p",{children:s(o==="changes"?"profiles.diff.noDifferences":"profiles.diff.noFieldsMatch")})]}):i.jsxs("table",{className:"w-full",children:[i.jsx("thead",{className:"sticky top-0 bg-bambu-dark-secondary",children:i.jsxs("tr",{className:"text-sm text-bambu-gray border-b border-bambu-dark-tertiary",children:[i.jsx("th",{className:"text-left p-3 w-1/3",children:s("profiles.diff.field")}),i.jsx("th",{className:"text-left p-3 w-1/3",children:r}),i.jsx("th",{className:"text-left p-3 w-1/3",children:a})]})}),i.jsx("tbody",{children:h.map(x=>{const v={added:"bg-green-500/10",removed:"bg-red-500/10",changed:"bg-amber-500/10",same:""}[x.status],g={added:i.jsx(Xn,{className:"w-3.5 h-3.5 text-green-400"}),removed:i.jsx(x1,{className:"w-3.5 h-3.5 text-red-400"}),changed:i.jsx(Qj,{className:"w-3.5 h-3.5 text-amber-400"}),same:i.jsx(LM,{className:"w-3.5 h-3.5 text-bambu-gray-dark"})}[x.status];return i.jsxs("tr",{className:`border-b border-bambu-dark-tertiary ${v}`,children:[i.jsx("td",{className:"p-3",children:i.jsxs("div",{className:"flex items-center gap-2",children:[g,i.jsx("span",{className:"text-sm text-white font-mono",children:x.key})]})}),i.jsx("td",{className:"p-3",children:i.jsx("span",{className:`text-sm font-mono break-all ${x.status==="removed"?"text-red-300":x.status==="changed"?"text-white":"text-bambu-gray"}`,children:p(x.left)})}),i.jsx("td",{className:"p-3",children:i.jsx("span",{className:`text-sm font-mono break-all ${x.status==="added"?"text-green-300":x.status==="changed"?"text-white":"text-bambu-gray"}`,children:p(x.right)})})]},x.key)})})]})})]})})})}function LZe({onClose:t,initialData:e,allPresets:n,t:r}){const{showToast:a}=cn(),s=tn(),o=!!e?.setting_id,[l,c]=w.useState("common"),[u,d]=w.useState(e?.type||"filament"),[h,f]=w.useState(e?.name?o?e.name:`${e.name} (Copy)`:""),[p,x]=w.useState(e?.base_id||""),[v,g]=w.useState(""),[y,_]=w.useState(e?.setting||{inherits:""}),[N,k]=w.useState(JSON.stringify(e?.setting||{inherits:""},null,2)),[A,M]=w.useState(null),[C,j]=w.useState(""),[P,E]=w.useState(!1),[B,O]=w.useState(""),[U,R]=w.useState(!1),[V,G]=w.useState(Oie),[z,K]=w.useState(!1),[Y,ae]=w.useState(""),[$,W]=w.useState(""),[ee,J]=w.useState(!0),[ye,me]=w.useState(null),[te,je]=w.useState(!1),ue=w.useMemo(()=>({filament:n.filament,print:n.process,printer:n.printer})[u]||[],[n,u]),oe=w.useMemo(()=>ue.filter(Me=>r0(Me.setting_id)),[ue]),{data:_e}=Je({queryKey:["cloudFields",u],queryFn:()=>ne.getCloudFields(u==="print"?"process":u),staleTime:1e3*60*60}),{data:se}=Je({queryKey:["allPresetDetails",u,oe.map(Me=>Me.setting_id).join(",")],queryFn:async()=>{const Me={};for(let ve=0;ve{try{const Te=await ne.getCloudSettingDetail(nt.setting_id);return{id:nt.setting_id,detail:Te}}catch{return null}}))).forEach(nt=>{nt&&(Me[nt.id]=nt.detail)})}return Me},enabled:oe.length>0,staleTime:1e3*60*10}),{data:Oe,isLoading:q}=Je({queryKey:["cloudSettingDetail",p],queryFn:()=>ne.getCloudSettingDetail(p),enabled:!!p});w.useEffect(()=>{l!=="json"&&k(JSON.stringify(y,null,2))},[y,l]);const X=w.useMemo(()=>({filament:n.filament,print:n.process,printer:n.printer}[u]||[]).filter(xe=>!r0(xe.setting_id)).sort((xe,ve)=>xe.name.localeCompare(ve.name)),[n,u]);w.useEffect(()=>{if(!p)return;const Me=X.find(xe=>xe.setting_id===p);Me&&(g(Me.name),o||(_({inherits:Me.name}),k(JSON.stringify({inherits:Me.name},null,2))))},[p,X,o]);const de=w.useMemo(()=>{const Me=_e?.fields||[],xe=new Set(Me.map(nt=>nt.key)),ve=new Set,He=new Set(["inherits","updated_time","compatible_printers","compatible_prints"]);se&&Object.values(se).forEach(nt=>{nt?.setting&&Object.keys(nt.setting).forEach(Te=>{!xe.has(Te)&&!He.has(Te)&&ve.add(Te)})}),Object.keys(y).forEach(nt=>{!xe.has(nt)&&!He.has(nt)&&ve.add(nt)});const Pe=Array.from(ve).sort().map(nt=>({key:nt,label:nt.replace(/_/g," ").replace(/\b\w/g,Te=>Te.toUpperCase()),type:"text",category:"discovered",description:r("profiles.presets.discoveredFromPresets")}));return[...Me,...Pe]},[_e,se,y,r]),Z=de.filter(Me=>Me.label.toLowerCase().includes(C.toLowerCase())||Me.key.toLowerCase().includes(C.toLowerCase())),ie=()=>{if(B.trim()){const Me=B.trim().toLowerCase().replace(/\s+/g,"_");le(Me,""),O(""),R(!1),a(r("profiles.presets.toast.fieldAdded",{key:Me}))}},le=(Me,xe)=>{_(ve=>{const He={...ve};return xe===""||xe===void 0?delete He[Me]:He[Me]=xe,He})},Fe=Me=>{_(xe=>({...xe,...Me.settings})),me(Me.name),a(r("profiles.templates.toast.applied"))},pe=()=>{if(!Y.trim())return;const Me={...y};if(delete Me.inherits,Object.keys(Me).length===0){a(r("profiles.presets.noOverridesToSave"),"error");return}const xe={id:Date.now().toString(),name:Y.trim(),description:$.trim()||r("profiles.presets.customTemplate"),type:u,settings:Me,showInModal:ee},ve=[...V,xe];G(ve),Iie(ve),K(!1),ae(""),W(""),J(!0),a(r("profiles.templates.toast.created"))},Q=w.useMemo(()=>V.filter(Me=>Me.type===u&&Me.showInModal),[u,V]),L=Me=>{k(Me);try{const xe=JSON.parse(Me);_(xe),M(null)}catch(xe){M(xe.message)}},D=Me=>{Me.preventDefault(),E(!1);const xe=Me.dataTransfer.files[0];if(xe&&xe.name.endsWith(".json")){const ve=new FileReader;ve.onload=He=>{try{const Pe=He.target?.result,nt=JSON.parse(Pe),Te=nt.setting||nt;_(Ge=>({...Ge,...Te})),k(JSON.stringify({...y,...Te},null,2)),a(r("profiles.presets.fileImported"))}catch{a(r("profiles.presets.invalidJsonFile"),"error")}},ve.readAsText(xe)}},H=ot({mutationFn:()=>{const Me={...y},xe=u==="filament"?"filament_settings_id":u==="print"?"print_settings_id":"printer_settings_id";Me[xe]=`"${h}"`;const ve={type:u,name:h,base_id:p,setting:Me};return ne.createCloudSetting(ve)},onSuccess:async()=>{a(r("profiles.presets.toast.created")),await s.refetchQueries({queryKey:["cloudSettings"]}),t()},onError:Me=>a(Me.message,"error")}),he=ot({mutationFn:()=>{if(!e?.setting_id)throw new Error(r("profiles.presets.noSettingId"));return ne.updateCloudSetting(e.setting_id,{name:h,setting:y})},onSuccess:async()=>{a(r("profiles.presets.toast.updated")),s.removeQueries({queryKey:["cloudSettingDetail"]}),await s.refetchQueries({queryKey:["cloudSettings"]}),t()},onError:Me=>a(Me.message,"error")}),be=o?he:H,fe=Oe?.setting?.inherits,ze=fe?X.find(Me=>Me.name===fe):void 0,{data:Ie}=Je({queryKey:["cloudSettingDetail",ze?.setting_id],queryFn:()=>ne.getCloudSettingDetail(ze.setting_id),enabled:!!ze?.setting_id}),qe=w.useMemo(()=>{const Me=Ie?.setting||{},xe=Oe?.setting||{},ve=p&&se?.[p]?.setting?se[p].setting:{};return{...Me,...xe,...ve}},[p,Oe,Ie,se]),tt=Me=>{if(Me==null)return"";if(Array.isArray(Me)){const xe=[...new Set(Me.map(ve=>String(ve)))];return xe.length===1?xe[0]:Me.join(", ")}return String(Me)},Ee=Me=>{const xe=y[Me.key],ve=qe[Me.key],He=tt(ve),Pe=q?r("common.loading"):He||"",nt="w-full px-3 py-1.5 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none";if(Me.type==="boolean"){const Te=xe==="1"||xe===void 0&&ve==="1";return i.jsx("button",{type:"button",onClick:()=>le(Me.key,xe==="1"?"0":"1"),className:`w-8 h-5 rounded-full transition-colors ${Te?"bg-bambu-green":"bg-bambu-dark-tertiary"}`,children:i.jsx("div",{className:`w-4 h-4 rounded-full bg-white shadow transition-transform ${Te?"translate-x-3.5":"translate-x-0.5"}`})})}return Me.type==="select"?i.jsxs("select",{value:xe||"",onChange:Te=>le(Me.key,Te.target.value),className:nt,children:[i.jsx("option",{value:"",children:Pe}),Me.options?.map(Te=>i.jsx("option",{value:Te.value,children:Te.label},Te.value))]}):i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("input",{type:Me.type==="number"?"number":"text",value:xe!==void 0?String(xe):"",onChange:Te=>le(Me.key,Te.target.value),step:Me.step,min:Me.min,max:Me.max,placeholder:Pe,className:nt}),Me.unit&&i.jsx("span",{className:"text-xs text-bambu-gray whitespace-nowrap",children:Me.unit})]})},Se=w.useMemo(()=>Oe?.setting?Oe.setting:{},[Oe]);return i.jsxs("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",onDragOver:Me=>{Me.preventDefault(),E(!0)},onDragLeave:()=>E(!1),onDrop:D,children:[te&&p&&i.jsx(zie,{onClose:()=>je(!1),leftPreset:Se,rightPreset:y,leftLabel:r("profiles.presets.baseLabel",{name:v||p}),rightLabel:r("profiles.presets.currentLabel",{name:h||r("profiles.presets.newPreset")}),t:r}),i.jsx(vt,{className:"w-full max-w-6xl max-h-[90vh] flex flex-col overflow-y-auto",children:i.jsxs(_t,{className:"p-0 flex flex-col h-full",children:[i.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[i.jsxs("div",{children:[i.jsx("h2",{className:"text-xl font-semibold text-white",children:r(o?"profiles.presets.editPreset":e?"profiles.presets.duplicatePreset":"profiles.presets.createNewPreset")}),i.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:r("profiles.presets.customizeSettings")})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[p&&i.jsxs("button",{onClick:()=>je(!0),className:"flex items-center gap-2 px-3 py-2 text-sm text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary rounded-lg transition-colors",title:r("profiles.presets.compareWithBase"),children:[i.jsx($g,{className:"w-4 h-4"}),r("profiles.presets.compare")]}),i.jsx("button",{onClick:t,className:"p-2 text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary rounded-lg transition-colors",children:i.jsx(Ft,{className:"w-5 h-5"})})]})]}),P&&i.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:i.jsxs("div",{className:"text-center",children:[i.jsx(Ra,{className:"w-12 h-12 text-bambu-green mx-auto mb-2"}),i.jsx("p",{className:"text-bambu-green font-medium",children:r("profiles.presets.dropJsonToImport")})]})}),i.jsxs("div",{className:"p-4 border-b border-bambu-dark-tertiary space-y-3",children:[i.jsxs("div",{className:"grid grid-cols-3 gap-4 max-[640px]:grid-cols-1",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("common.type")}),i.jsxs("select",{value:u,onChange:Me=>{d(Me.target.value),x("")},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:[i.jsx("option",{value:"filament",children:r("profiles.presets.types.filament")}),i.jsx("option",{value:"print",children:r("profiles.presets.types.process")}),i.jsx("option",{value:"printer",children:r("profiles.presets.types.printer")})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("profiles.presets.basePreset")}),i.jsxs("select",{value:p,onChange:Me=>x(Me.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:[i.jsx("option",{value:"",children:r("profiles.presets.selectBasePreset")}),X.map(Me=>i.jsx("option",{value:Me.setting_id,children:Me.name},Me.setting_id))]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("profiles.presets.presetName")}),i.jsx("input",{type:"text",value:h,onChange:Me=>f(Me.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",placeholder:r("profiles.presets.myCustomPreset")})]})]}),v&&i.jsx("div",{className:"text-xs text-bambu-gray",children:i.jsxs("p",{className:"flex items-center gap-1",children:[i.jsx(ra,{className:"w-3 h-3 text-bambu-green"}),r("profiles.presets.inheritsFrom")," ",i.jsx("span",{className:"text-white",children:v}),q&&i.jsx(it,{className:"w-3 h-3 animate-spin ml-1"})]})})]}),i.jsxs("div",{className:"flex border-b border-bambu-dark-tertiary max-[640px]:flex-wrap max-[640px]:items-center",children:[i.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:[i.jsx(jB,{className:"w-4 h-4"}),r("profiles.presets.tabs.common")]}),i.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:[i.jsx(HC,{className:"w-4 h-4"}),r("profiles.presets.tabs.allFields")]}),i.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:[i.jsx(nX,{className:"w-4 h-4"}),"JSON",A&&i.jsx(Ba,{className:"w-3 h-3 text-red-400"})]}),i.jsx("div",{className:"flex-1 max-[640px]:hidden"}),i.jsxs("button",{onClick:()=>{const Me={name:h,type:u,base_id:p,setting:y},xe=new Blob([JSON.stringify(Me,null,2)],{type:"application/json"}),ve=URL.createObjectURL(xe),He=document.createElement("a");He.href=ve,He.download=`${h||"preset"}.json`,document.body.appendChild(He),He.click(),document.body.removeChild(He),URL.revokeObjectURL(ve),a(r("profiles.presets.toast.exported"))},className:"flex items-center gap-2 px-4 py-3 text-sm text-bambu-gray hover:text-white transition-colors",title:r("profiles.presets.exportToJson"),children:[i.jsx(ua,{className:"w-4 h-4"}),r("common.download")]}),i.jsxs("button",{onClick:()=>document.getElementById("file-import")?.click(),className:"flex items-center gap-2 px-4 py-3 text-sm text-bambu-gray hover:text-white transition-colors",title:r("profiles.presets.importFromJson"),children:[i.jsx(Ra,{className:"w-4 h-4"}),r("common.upload")]}),i.jsx("input",{id:"file-import",type:"file",accept:".json",className:"hidden",onChange:Me=>{const xe=Me.target.files?.[0];if(xe){const ve=new FileReader;ve.onload=He=>{try{const Pe=JSON.parse(He.target?.result),nt=Pe.setting||Pe;_(Te=>({...Te,...nt})),a(r("profiles.presets.fileImported"))}catch{a(r("profiles.presets.invalidJson"),"error")}},ve.readAsText(xe)}}})]}),i.jsxs("div",{className:"flex-1 p-4",children:[l==="common"&&i.jsxs("div",{className:"space-y-6",children:[i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center justify-between mb-3",children:[i.jsxs("h3",{className:"text-sm font-medium text-white flex items-center gap-2",children:[i.jsx(lb,{className:"w-4 h-4 text-amber-400"}),r("profiles.templates.title")]}),Object.keys(y).filter(Me=>Me!=="inherits").length>0&&i.jsxs("button",{onClick:()=>K(!z),className:"text-xs text-bambu-gray hover:text-white flex items-center gap-1 transition-colors",children:[i.jsx(ps,{className:"w-3 h-3"}),r("profiles.presets.saveAsTemplate")]})]}),z&&i.jsxs("div",{className:"mb-3 p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"grid grid-cols-2 gap-2 mb-2",children:[i.jsx("input",{type:"text",value:Y,onChange:Me=>ae(Me.target.value),placeholder:r("profiles.templates.namePlaceholder"),className:"px-3 py-1.5 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none",autoFocus:!0}),i.jsx("input",{type:"text",value:$,onChange:Me=>W(Me.target.value),placeholder:r("profiles.templates.descriptionPlaceholder"),className:"px-3 py-1.5 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none"})]}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{className:"flex gap-2",children:[i.jsxs(Ce,{size:"sm",onClick:pe,disabled:!Y.trim(),children:[i.jsx(ps,{className:"w-3 h-3"}),r("common.save")]}),i.jsx(Ce,{size:"sm",variant:"secondary",onClick:()=>K(!1),children:r("common.cancel")})]}),i.jsxs("button",{onClick:()=>J(!ee),className:`flex items-center gap-1.5 text-xs transition-colors ${ee?"text-bambu-green":"text-bambu-gray hover:text-white"}`,children:[ee?i.jsx(Ql,{className:"w-3.5 h-3.5"}):i.jsx(o0,{className:"w-3.5 h-3.5"}),r(ee?"profiles.templates.shownInModals":"profiles.templates.hiddenInModals")]})]})]}),ye&&i.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:[i.jsx(ra,{className:"w-4 h-4 text-bambu-green"}),i.jsxs("span",{className:"text-sm text-bambu-green",children:[r("profiles.presets.templateApplied")," ",i.jsx("span",{className:"font-medium",children:ye})]}),i.jsx("button",{onClick:()=>me(null),className:"ml-auto text-bambu-green/70 hover:text-bambu-green",children:i.jsx(Ft,{className:"w-4 h-4"})})]}),i.jsxs("div",{className:"grid grid-cols-3 gap-2",children:[Q.map(Me=>i.jsxs("button",{onClick:()=>Fe(Me),className:"p-3 text-left bg-bambu-dark border border-bambu-dark-tertiary rounded-lg hover:border-bambu-gray-dark transition-colors",children:[i.jsx("p",{className:"text-sm font-medium text-white",children:Me.name}),i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:Me.description})]},Me.id)),Q.length===0&&i.jsx("p",{className:"col-span-3 text-center text-bambu-gray text-sm py-4",children:r("profiles.presets.noTemplatesSelected")})]}),i.jsx("p",{className:"text-xs text-bambu-gray-dark mt-2 text-center",children:r("profiles.presets.manageTemplatesHint")})]}),i.jsxs("div",{children:[i.jsx("h3",{className:"text-sm font-medium text-white mb-3",children:r("profiles.presets.commonSettings")}),i.jsx("div",{className:"grid grid-cols-2 gap-x-6 gap-y-3",children:de.slice(0,10).map(Me=>i.jsxs("div",{className:"flex items-center justify-between gap-4 max-[640px]:flex-col max-[640px]:items-start",children:[i.jsx("label",{className:"text-sm text-bambu-gray flex-shrink-0",children:Me.label}),i.jsx("div",{className:"w-48 max-[640px]:w-full",children:Ee(Me)})]},Me.key))})]}),Object.keys(y).length>1&&i.jsxs("div",{children:[i.jsx("h3",{className:"text-sm font-medium text-white mb-3",children:r("profiles.presets.currentOverrides")}),i.jsx("div",{className:"flex flex-wrap gap-2",children:Object.entries(y).filter(([Me])=>Me!=="inherits").map(([Me,xe])=>i.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-1 bg-bambu-green/10 text-bambu-green text-xs rounded",children:[Me,": ",String(xe).slice(0,20),i.jsx("button",{onClick:()=>le(Me,void 0),className:"hover:text-white",children:i.jsx(Ft,{className:"w-3 h-3"})})]},Me))})]})]}),l==="fields"&&i.jsxs("div",{className:"grid grid-cols-2 gap-6",style:{height:"400px"},children:[i.jsxs("div",{className:"flex flex-col h-full overflow-hidden",children:[i.jsxs("div",{className:"flex items-center justify-between mb-3 flex-shrink-0",children:[i.jsx("h3",{className:"text-sm font-medium text-white",children:r("profiles.presets.availableFields")}),i.jsx("span",{className:"text-xs text-bambu-gray",children:se?r("profiles.templates.fieldsCount",{count:de.length}):r("common.loading")})]}),i.jsxs("div",{className:"relative mb-3 flex-shrink-0",children:[i.jsx(kr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),i.jsx("input",{type:"text",value:C,onChange:Me=>j(Me.target.value),placeholder:r("profiles.presets.searchFieldsPlaceholder"),className:"w-full pl-10 pr-4 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder-bambu-gray-dark focus:border-bambu-green focus:outline-none"})]}),i.jsxs("div",{className:"flex-1 overflow-y-auto space-y-1 pr-2 min-h-0",children:[Z.filter(Me=>!(Me.key in y)).map(Me=>{const xe=qe[Me.key],ve=tt(xe);return i.jsxs("div",{onClick:()=>{_(He=>({...He,[Me.key]:ve||""}))},className:"flex items-center justify-between gap-2 p-2 rounded-lg hover:bg-bambu-dark-tertiary transition-colors cursor-pointer group",children:[i.jsxs("div",{className:"min-w-0 flex-1",children:[i.jsx("p",{className:"text-sm text-white truncate",children:Me.label}),i.jsx("p",{className:"text-xs text-bambu-gray-dark truncate",children:Me.key})]}),i.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[ve&&i.jsxs("span",{className:"text-xs text-bambu-gray bg-bambu-dark px-2 py-0.5 rounded max-w-32 truncate",title:ve,children:[ve.slice(0,20),ve.length>20?"...":""]}),i.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:i.jsx(Xn,{className:"w-4 h-4 text-bambu-gray group-hover:text-bambu-green transition-colors"})})]})]},Me.key)}),Z.filter(Me=>!(Me.key in y)).length===0&&i.jsx("p",{className:"text-center text-bambu-gray py-4 text-sm",children:r(C?"profiles.presets.noMatchingFields":"profiles.presets.allFieldsAdded")})]}),i.jsx("div",{className:"pt-3 mt-3 border-t border-bambu-dark-tertiary flex-shrink-0",children:U?i.jsxs("div",{className:"flex gap-2",children:[i.jsx("input",{type:"text",value:B,onChange:Me=>O(Me.target.value),onKeyDown:Me=>Me.key==="Enter"&&ie(),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}),i.jsx(Ce,{size:"sm",onClick:ie,disabled:!B.trim(),children:i.jsx(Xn,{className:"w-4 h-4"})}),i.jsx(Ce,{size:"sm",variant:"secondary",onClick:()=>{R(!1),O("")},children:i.jsx(Ft,{className:"w-4 h-4"})})]}):i.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:[i.jsx(Xn,{className:"w-4 h-4"}),r("profiles.presets.addCustomField")]})})]}),i.jsxs("div",{className:"flex flex-col h-full overflow-hidden",children:[i.jsxs("div",{className:"flex items-center justify-between mb-3 flex-shrink-0",children:[i.jsx("h3",{className:"text-sm font-medium text-white",children:r("profiles.presets.yourOverrides")}),i.jsx("span",{className:"text-xs text-bambu-gray",children:r("profiles.templates.fieldsCount",{count:Object.keys(y).filter(Me=>Me!=="inherits").length})})]}),i.jsxs("div",{className:"flex-1 overflow-y-auto space-y-2 pr-2 min-h-0",children:[Object.entries(y).filter(([Me])=>Me!=="inherits").map(([Me,xe])=>{const ve=de.find(He=>He.key===Me);return i.jsxs("div",{className:"p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex items-center justify-between mb-2",children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-sm font-medium text-white",children:ve?.label||Me}),i.jsx("p",{className:"text-xs text-bambu-gray-dark",children:Me})]}),i.jsx("button",{onClick:()=>le(Me,void 0),className:"p-1 text-bambu-gray hover:text-red-400 transition-colors",children:i.jsx(Ft,{className:"w-4 h-4"})})]}),ve?Ee(ve):i.jsx("input",{type:"text",value:String(xe),onChange:He=>le(Me,He.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"})]},Me)}),Object.keys(y).filter(Me=>Me!=="inherits").length===0&&i.jsxs("div",{className:"text-center py-8 text-bambu-gray",children:[i.jsx(jB,{className:"w-8 h-8 mx-auto mb-2 opacity-50"}),i.jsx("p",{className:"text-sm",children:r("profiles.presets.noOverridesYet")}),i.jsx("p",{className:"text-xs mt-1",children:r("profiles.presets.clickFieldsToAdd")})]})]}),Object.keys(y).filter(Me=>Me!=="inherits").length>0&&i.jsx("div",{className:"pt-3 mt-3 border-t border-bambu-dark-tertiary flex-shrink-0",children:i.jsxs("button",{onClick:()=>{K(!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:[i.jsx(ps,{className:"w-4 h-4"}),r("profiles.presets.saveAsTemplate")]})})]})]}),l==="json"&&i.jsxs("div",{className:"space-y-2",children:[A&&i.jsxs("div",{className:"flex items-center gap-2 text-red-400 text-sm",children:[i.jsx(Ba,{className:"w-4 h-4"}),A]}),i.jsx("textarea",{value:N,onChange:Me=>L(Me.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 ${A?"border-red-500 focus:border-red-500":"border-bambu-dark-tertiary focus:border-bambu-green"}`,spellCheck:!1}),i.jsx("p",{className:"text-xs text-bambu-gray",children:r("profiles.presets.jsonTip")})]})]}),i.jsxs("div",{className:"p-4 border-t border-bambu-dark-tertiary flex gap-2",children:[i.jsx(Ce,{variant:"secondary",onClick:t,className:"flex-1",children:r("common.cancel")}),i.jsxs(Ce,{onClick:()=>be.mutate(),disabled:be.isPending||!h.trim()||!o&&!p||!!A,className:"flex-1",children:[be.isPending?i.jsx(it,{className:"w-4 h-4 animate-spin"}):o?i.jsx(ps,{className:"w-4 h-4"}):i.jsx(Xn,{className:"w-4 h-4"}),r(o?"common.save":e?"common.duplicate":"common.create")]})]})]})})]})}function OZe({settings:t,lastSyncTime:e,onRefresh:n,isRefreshing:r,printers:a,hasPermission:s,t:o}){const[l,c]=w.useState(""),[u,d]=w.useState("all"),[h,f]=w.useState("all"),[p,x]=w.useState("all"),[v,g]=w.useState("all"),[y,_]=w.useState("all"),[N,k]=w.useState("all"),[A,M]=w.useState(null),[C,j]=w.useState(!1),[P,E]=w.useState(!1),[B,O]=w.useState(null),[U,R]=w.useState(null),[V,G]=w.useState(null),[z,K]=w.useState(!1),[Y,ae]=w.useState([null,null]),[$,W]=w.useState(!1),[ee,J]=w.useState(null),ye=tn(),me=w.useMemo(()=>[...t.filament.map(ie=>({...ie,type:"filament"})),...t.printer.map(ie=>({...ie,type:"printer"})),...t.process.map(ie=>({...ie,type:"process"}))].map(ie=>({...ie,meta:s4(ie.name)})),[t]),te=w.useMemo(()=>{const Z=new Set,ie=new Set,le=new Set;return me.forEach(Fe=>{Fe.meta.nozzle&&Z.add(Fe.meta.nozzle),Fe.meta.filamentType&&ie.add(Fe.meta.filamentType),Fe.meta.layerHeight&&le.add(Fe.meta.layerHeight)}),{printers:a.map(Fe=>({id:Fe.id.toString(),name:Fe.name})),nozzles:Array.from(Z).sort((Fe,pe)=>parseFloat(Fe)-parseFloat(pe)),filaments:Array.from(ie).sort(),layerHeights:Array.from(le).sort((Fe,pe)=>parseFloat(Fe)-parseFloat(pe))}},[me,a]),je=w.useMemo(()=>p==="all"?null:a.find(ie=>ie.id.toString()===p)?.model||null,[p,a]),ue=w.useMemo(()=>me.filter(Z=>u==="all"||Z.type===u).filter(Z=>{if(h==="all")return!0;const ie=r0(Z.setting_id);return h==="custom"?ie:!ie}).filter(Z=>{if(p==="all"||!je)return!0;const ie=Z.meta.printer?.toLowerCase()||"",le=je.toLowerCase();return ie.includes(le)||le.includes(ie)}).filter(Z=>v==="all"||Z.meta.nozzle===v).filter(Z=>y==="all"||Z.meta.filamentType===y).filter(Z=>N==="all"||Z.meta.layerHeight===N).filter(Z=>l===""||Z.name.toLowerCase().includes(l.toLowerCase())).sort((Z,ie)=>Z.name.localeCompare(ie.name)),[me,u,h,p,je,v,y,N,l]),oe=Z=>{if(z){const ie=Y[0]?.setting_id===Z.setting_id,le=Y[1]?.setting_id===Z.setting_id;if(ie)ae([Y[1],null]);else if(le)ae([Y[0],null]);else if(!Y[0])ae([Z,null]);else if(Y[1]){if(Y[0].type!==Z.type)return;ae([Y[0],Z])}else{if(Y[0].type!==Z.type)return;ae([Y[0],Z])}}else M(Z)},_e=Z=>{if(Y[0]?.setting_id===Z.setting_id)return 0;if(Y[1]?.setting_id===Z.setting_id)return 1},se=async Z=>{try{const ie=await ne.getCloudSettingDetail(Z.setting_id),le=Z.type==="process"?"print":Z.type;O({type:le,name:Z.name,base_id:ie.base_id||"GFSA00",setting:ie.setting||{}}),M(null)}catch(ie){console.error("Failed to fetch preset details for duplication:",ie)}},Oe=async Z=>{try{ye.removeQueries({queryKey:["cloudSettingDetail",Z.setting_id]});const ie=await ne.getCloudSettingDetail(Z.setting_id),le=Z.type==="process"?"print":Z.type;R({type:le,name:Z.name,base_id:ie.base_id||"GFSA00",setting:ie.setting||{},setting_id:Z.setting_id}),M(null)}catch(ie){console.error("Failed to fetch preset details for editing:",ie)}},q=()=>{d("all"),f("all"),x("all"),g("all"),_("all"),k("all"),c("")},X=u!=="all"||h!=="all"||p!=="all"||v!=="all"||y!=="all"||N!=="all"||l!=="",de=t.filament.length+t.printer.length+t.process.length;return i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"space-y-4 mb-6",children:[i.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[i.jsxs("div",{className:"relative flex-1",children:[i.jsx(kr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),i.jsx("input",{type:"text",value:l,onChange:Z=>c(Z.target.value),placeholder:o("profiles.cloudView.searchPlaceholder"),className:"w-full pl-10 pr-4 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray-dark focus:border-bambu-green focus:outline-none"})]}),i.jsxs("div",{className:"flex gap-2 max-[550px]:flex-wrap max-[550px]:items-center",children:[i.jsxs(Ce,{variant:z?"primary":"secondary",onClick:()=>{z?(K(!1),ae([null,null])):K(!0)},children:[i.jsx($g,{className:"w-4 h-4"}),o(z?"common.cancel":"profiles.presets.compare")]}),i.jsxs(Ce,{variant:"secondary",onClick:()=>E(!0),disabled:!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.cloudView.noTemplatesPermission"),children:[i.jsx(lb,{className:"w-4 h-4"}),o("profiles.cloudView.templates")]}),i.jsxs(Ce,{variant:"secondary",onClick:n,disabled:r||!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.cloudView.noRefreshPermission"),children:[i.jsx(Cr,{className:`w-4 h-4 ${r?"animate-spin":""}`}),o("profiles.cloudView.refresh")]}),i.jsxs(Ce,{onClick:()=>j(!0),disabled:!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.cloudView.noCreatePermission"),children:[i.jsx(Xn,{className:"w-4 h-4"}),o("profiles.cloudView.newPreset")]})]})]}),i.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[i.jsx(UC,{className:"w-4 h-4 text-bambu-gray"}),i.jsx(Ag,{label:o("profiles.cloudView.filters.type"),value:u,options:[{value:"all",label:o("profiles.cloudView.filters.all"),count:de},{value:"filament",label:o("profiles.cloudView.filters.filament"),count:t.filament.length},{value:"printer",label:o("profiles.cloudView.filters.printer"),count:t.printer.length},{value:"process",label:o("profiles.cloudView.filters.process"),count:t.process.length}],onChange:Z=>d(Z)}),i.jsx(Ag,{label:o("profiles.cloudView.filters.owner"),value:h,options:[{value:"all",label:o("profiles.cloudView.filters.all")},{value:"custom",label:o("profiles.cloudView.filters.myPresets")},{value:"builtin",label:o("profiles.cloudView.filters.builtIn")}],onChange:Z=>f(Z)}),te.printers.length>0&&i.jsx(Ag,{label:o("profiles.cloudView.filters.printer"),value:p,options:[{value:"all",label:o("profiles.cloudView.filters.all")},...te.printers.map(Z=>({value:Z.id,label:Z.name}))],onChange:x}),te.nozzles.length>0&&i.jsx(Ag,{label:o("profiles.cloudView.filters.nozzle"),value:v,options:[{value:"all",label:o("profiles.cloudView.filters.all")},...te.nozzles.map(Z=>({value:Z,label:Z}))],onChange:g}),te.filaments.length>0&&(u==="all"||u==="filament")&&i.jsx(Ag,{label:o("profiles.cloudView.filters.filament"),value:y,options:[{value:"all",label:o("profiles.cloudView.filters.all")},...te.filaments.map(Z=>({value:Z,label:Z}))],onChange:_}),te.layerHeights.length>0&&(u==="all"||u==="process")&&i.jsx(Ag,{label:o("profiles.cloudView.filters.layer"),value:N,options:[{value:"all",label:o("profiles.cloudView.filters.all")},...te.layerHeights.map(Z=>({value:Z,label:Z}))],onChange:k}),X&&i.jsx("button",{onClick:q,className:"px-3 py-2 text-sm text-bambu-gray hover:text-white transition-colors",children:o("profiles.cloudView.clearFilters")})]})]}),z&&i.jsx("div",{className:"mb-4 p-3 bg-blue-500/10 border border-blue-500/30 rounded-lg",children:i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{className:"flex items-center gap-4",children:[i.jsx($g,{className:"w-5 h-5 text-blue-400"}),i.jsx("span",{className:"text-white font-medium",children:o("profiles.cloudView.compareMode")}),i.jsx("span",{className:"text-bambu-gray",children:Y[0]?o("profiles.cloudView.selectAnotherPreset",{type:Y[0].type}):o("profiles.cloudView.clickTwoPresets")})]}),i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:`px-2 py-1 text-sm rounded truncate max-w-[200px] ${Y[0]?"bg-blue-500/30 text-blue-700 dark:text-blue-300":"bg-bambu-dark text-bambu-gray"}`,children:Y[0]?Y[0].name:o("profiles.cloudView.selectFirst")}),i.jsx(Qj,{className:"w-4 h-4 text-bambu-gray"}),i.jsx("span",{className:`px-2 py-1 text-sm rounded truncate max-w-[200px] ${Y[1]?"bg-blue-500/30 text-blue-700 dark:text-blue-300":"bg-bambu-dark text-bambu-gray"}`,children:Y[1]?Y[1].name:o("profiles.cloudView.selectSecond")})]}),Y[0]&&Y[1]&&i.jsxs(Ce,{size:"sm",onClick:async()=>{try{const[Z,ie]=await Promise.all([ne.getCloudSettingDetail(Y[0].setting_id),ne.getCloudSettingDetail(Y[1].setting_id)]);J([Z.setting||{},ie.setting||{}]),W(!0)}catch{}},children:[i.jsx($g,{className:"w-4 h-4"}),o("profiles.cloudView.compareNow")]})]})]})}),i.jsxs("div",{className:"flex flex-wrap items-center gap-4 mb-4 text-sm text-bambu-gray",children:[e&&i.jsxs("div",{className:"flex items-center gap-1",children:[i.jsx(Gn,{className:"w-3 h-3"}),o("profiles.cloudView.lastSynced")," ",gv(e.toISOString(),"system",o)]}),i.jsx("span",{children:o("profiles.cloudView.showingCount",{showing:ue.length,total:de})}),i.jsxs("div",{className:"flex items-center gap-1",children:[i.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-bambu-green"}),i.jsxs("span",{children:["= ",o("profiles.presets.myPreset")]})]})]}),ue.length===0?i.jsxs("div",{className:"text-center py-16",children:[i.jsx(mi,{className:"w-12 h-12 text-bambu-gray-dark mx-auto mb-4"}),i.jsx("p",{className:"text-bambu-gray",children:o("profiles.cloudView.noPresetsFound")}),X&&i.jsx("button",{onClick:q,className:"mt-2 text-sm text-bambu-green hover:text-bambu-green-light",children:o("profiles.cloudView.clearFilters")})]}):i.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-6",children:[i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center gap-2 mb-3 px-1",children:[i.jsx(IC,{className:"w-4 h-4 text-amber-400"}),i.jsx("h3",{className:"text-sm font-medium text-bambu-gray",children:o("profiles.cloudView.columns.filament")}),i.jsxs("span",{className:"text-xs text-bambu-gray-dark",children:["(",ue.filter(Z=>Z.type==="filament").length,")"]})]}),i.jsxs("div",{className:"space-y-1 max-h-[calc(100vh-320px)] overflow-y-auto pr-1",children:[ue.filter(Z=>Z.type==="filament").map(Z=>i.jsx(Aj,{setting:Z,onClick:()=>oe(Z),onDuplicate:()=>se(Z),compareMode:z,isCompareSelected:_e(Z)!==void 0,compareIndex:_e(Z),compareDisabled:z&&!!Y[0]&&Y[0].type!==Z.type,t:o},Z.setting_id)),ue.filter(Z=>Z.type==="filament").length===0&&i.jsx("p",{className:"text-xs text-bambu-gray-dark px-3 py-2",children:o("profiles.cloudView.noFilamentPresets")})]})]}),i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center gap-2 mb-3 px-1",children:[i.jsx(ed,{className:"w-4 h-4 text-blue-400"}),i.jsx("h3",{className:"text-sm font-medium text-bambu-gray",children:o("profiles.cloudView.columns.process")}),i.jsxs("span",{className:"text-xs text-bambu-gray-dark",children:["(",ue.filter(Z=>Z.type==="process").length,")"]})]}),i.jsxs("div",{className:"space-y-1 max-h-[calc(100vh-320px)] overflow-y-auto pr-1",children:[ue.filter(Z=>Z.type==="process").map(Z=>i.jsx(Aj,{setting:Z,onClick:()=>oe(Z),onDuplicate:()=>se(Z),compareMode:z,isCompareSelected:_e(Z)!==void 0,compareIndex:_e(Z),compareDisabled:z&&!!Y[0]&&Y[0].type!==Z.type,t:o},Z.setting_id)),ue.filter(Z=>Z.type==="process").length===0&&i.jsx("p",{className:"text-xs text-bambu-gray-dark px-3 py-2",children:o("profiles.cloudView.noProcessPresets")})]})]}),i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center gap-2 mb-3 px-1",children:[i.jsx(xr,{className:"w-4 h-4 text-purple-400"}),i.jsx("h3",{className:"text-sm font-medium text-bambu-gray",children:o("profiles.cloudView.columns.printer")}),i.jsxs("span",{className:"text-xs text-bambu-gray-dark",children:["(",ue.filter(Z=>Z.type==="printer").length,")"]})]}),i.jsxs("div",{className:"space-y-1 max-h-[calc(100vh-320px)] overflow-y-auto pr-1",children:[ue.filter(Z=>Z.type==="printer").map(Z=>i.jsx(Aj,{setting:Z,onClick:()=>oe(Z),onDuplicate:()=>se(Z),compareMode:z,isCompareSelected:_e(Z)!==void 0,compareIndex:_e(Z),compareDisabled:z&&!!Y[0]&&Y[0].type!==Z.type,t:o},Z.setting_id)),ue.filter(Z=>Z.type==="printer").length===0&&i.jsx("p",{className:"text-xs text-bambu-gray-dark px-3 py-2",children:o("profiles.cloudView.noPrinterPresets")})]})]})]}),A&&i.jsx(RZe,{setting:A,onClose:()=>M(null),onDeleted:()=>M(null),onDuplicate:()=>se(A),onEdit:()=>Oe(A),hasPermission:s,t:o}),(C||B||U||V)&&i.jsx(LZe,{onClose:()=>{j(!1),O(null),R(null),G(null)},initialData:U||B||(V?{type:V.type,name:"",base_id:"",setting:V.setting}:void 0),allPresets:t,t:o}),P&&i.jsx(FZe,{onClose:()=>E(!1),onApply:Z=>{G({type:Z.type,setting:Z.settings}),E(!1)},t:o}),$&&ee&&Y[0]&&Y[1]&&i.jsx(zie,{onClose:()=>{W(!1),J(null)},leftPreset:ee[0],rightPreset:ee[1],leftLabel:Y[0].name,rightLabel:Y[1].name,t:o})]})}function IZe(){const{t}=Ut(),e=tn(),{showToast:n}=cn(),{hasPermission:r}=Or(),[a,s]=w.useState("cloud"),[o,l]=w.useState(),{data:c,isLoading:u}=Je({queryKey:["cloudStatus"],queryFn:ne.getCloudStatus}),{data:d=[]}=Je({queryKey:["printers"],queryFn:ne.getPrinters}),{data:h,isLoading:f,refetch:p,dataUpdatedAt:x}=Je({queryKey:["cloudSettings"],queryFn:()=>ne.getCloudSettings(),enabled:!!c?.is_authenticated,retry:!1,staleTime:1e3*60*5});w.useEffect(()=>{x&&l(new Date(x))},[x]);const v=ot({mutationFn:ne.cloudLogout,onSuccess:()=>{e.invalidateQueries({queryKey:["cloudStatus"]}),e.removeQueries({queryKey:["cloudSettings"]}),n(t("profiles.toast.loggedOut"))}}),g=()=>{e.invalidateQueries({queryKey:["cloudStatus"]})};return u?i.jsx("div",{className:"p-4 md:p-8 flex items-center justify-center min-h-[400px]",children:i.jsx(it,{className:"w-8 h-8 text-bambu-green animate-spin"})}):i.jsxs("div",{className:"p-6 lg:p-8",children:[i.jsxs("div",{className:"mb-6",children:[i.jsx("h1",{className:"text-2xl font-bold text-white",children:t("profiles.title")}),i.jsx("p",{className:"text-bambu-gray",children:t("profiles.subtitle")})]}),i.jsxs("div",{className:"flex border-b border-bambu-dark-tertiary mb-6",children:[i.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 ${a==="cloud"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-white border-transparent"}`,children:[i.jsx(zb,{className:"w-4 h-4"}),t("profiles.tabs.cloud")]}),i.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 ${a==="local"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-white border-transparent"}`,children:[i.jsx(Ub,{className:"w-4 h-4"}),t("profiles.tabs.local")]}),i.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 ${a==="kprofiles"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-white border-transparent"}`,children:[i.jsx(BC,{className:"w-4 h-4"}),t("profiles.tabs.kprofiles")]})]}),a==="cloud"&&i.jsxs(i.Fragment,{children:[c?.is_authenticated&&i.jsxs("div",{className:"flex items-center justify-between p-3 mb-6 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("div",{className:"w-2 h-2 rounded-full bg-bambu-green animate-pulse"}),i.jsxs("span",{className:"text-sm text-bambu-gray",children:[t("profiles.connectedAs")," ",i.jsx("span",{className:"text-white",children:c.email})]})]}),i.jsxs(Ce,{variant:"secondary",size:"sm",onClick:()=>v.mutate(),disabled:v.isPending||!r("cloud:auth"),title:r("cloud:auth")?void 0:t("profiles.noLogoutPermission"),children:[i.jsx(r3,{className:"w-4 h-4"}),t("profiles.logout")]})]}),c?.is_authenticated?f?i.jsx("div",{className:"flex items-center justify-center py-16",children:i.jsx(it,{className:"w-8 h-8 text-bambu-green animate-spin"})}):h?i.jsx(OZe,{settings:h,lastSyncTime:o,onRefresh:()=>p(),isRefreshing:f,printers:d,hasPermission:r,t}):i.jsxs("div",{className:"text-center py-16",children:[i.jsx("p",{className:"text-bambu-gray mb-4",children:t("profiles.failedToLoad")}),i.jsx(Ce,{onClick:()=>p(),children:t("profiles.retry")})]}):i.jsx(jZe,{onSuccess:g,t})]}),a==="local"&&i.jsx(EZe,{}),a==="kprofiles"&&i.jsx(AZe,{}),i.jsx(DZe,{})]})}const Oy={Droplet:IC,Flame:sme,Ruler:Ife,Sparkles:lb,Square:vl,Cable:$de,Wrench:Ef,Calendar:na,Timer:Lu,Cog:Mhe,Fan:rX,Zap:Vh,Wind:fX,Thermometer:XC,Layers:mi,Box:Ja,Target:dX,RefreshCw:Cr,Settings:KC,Filter:UC,CircleDot:uhe};function ov(t){return t&&Oy[t]||Ef}function Tg(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 a=Math.round(t);return n?n("maintenance.days",{count:a}):`${a} days`}if(t<180){const a=Math.round(t/7);return a===1?n?n("maintenance.week"):"1 week":n?n("maintenance.weeks",{count:a}):`${a} weeks`}const r=Math.round(t/30);return r===1?n?n("maintenance.month"):"1 month":n?n("maintenance.months",{count:r}):`${r} months`}else{if(t<1)return`${Math.round(t*60)}m`;if(t<24)return`${t<10?t.toFixed(1):Math.round(t)}h`;const r=t/24;if(r<7)return`${r<2?r.toFixed(1):Math.round(r)}d`;const a=r/7;return a<12?`${a<2?a.toFixed(1):Math.round(a)}w`:`${Math.round(a/4)}mo`}}function Tj(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 zZe(t,e){const n=(e||"").toUpperCase().replace(/[- ]/g,""),r=n.includes("X1"),a=n.includes("P1"),s=n.includes("A1MINI"),o=n.includes("A1")&&!s,l=n.includes("H2D"),c=n.includes("H2C"),u=n.includes("H2S"),d=l||c||u,h=n.includes("P2S");switch(t){case"Lubricate Carbon Rods":return r?"https://wiki.bambulab.com/en/x1/maintenance/basic-maintenance":a?"https://wiki.bambulab.com/en/p1/maintenance/p1p-maintenance":h?"https://wiki.bambulab.com/en/p2s/maintenance/belt-tension":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":d?"https://wiki.bambulab.com/en/h2/maintenance/x-axis-lubrication":null;case"Clean Nozzle/Hotend":return r||a?"https://wiki.bambulab.com/en/x1/troubleshooting/nozzle-clog":s||o?"https://wiki.bambulab.com/en/a1-mini/troubleshooting/nozzle-clog":d?"https://wiki.bambulab.com/en/h2/maintenance/nozzl-cold-pull-maintenance-and-cleaning":h?"https://wiki.bambulab.com/en/p2s/maintenance/cold-pull-maintenance-hotend":"https://wiki.bambulab.com/en/x1/troubleshooting/nozzle-clog";case"Check Belt Tension":return r?"https://wiki.bambulab.com/en/x1/maintenance/belt-tension":a?"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":u?"https://wiki.bambulab.com/en/h2s/maintenance/belt-tension":h?"https://wiki.bambulab.com/en/p2s/maintenance/belt-tension":"https://wiki.bambulab.com/en/x1/maintenance/belt-tension";case"Clean Carbon Rods":return r||a||h?"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":d?"https://wiki.bambulab.com/en/h2/maintenance/x-axis-lubrication":null;case"Clean Build Plate":return"https://wiki.bambulab.com/en/filament-acc/acc/pei-plate-clean-guide";case"Check PTFE Tube":return r||a?"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":u?"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 d?"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 d?"https://wiki.bambulab.com/en/h2/maintenance/x-axis-lubrication":null;default:return null}}function UZe({item:t,onPerform:e,onToggle:n,hasPermission:r,t:a}){const s=ov(t.maintenance_type_icon),o=t.interval_type||"hours",c=(()=>{if(o==="days"){const p=t.days_since_maintenance??0;return Math.max(0,Math.min(100,p/t.interval_hours*100))}return Math.max(0,Math.min(100,(t.interval_hours-t.hours_until_due)/t.interval_hours*100))})(),u=()=>t.enabled?t.is_due?"text-red-400":t.is_warning?"text-amber-400":"text-bambu-green":"text-bambu-gray",d=()=>t.enabled?t.is_due?"bg-red-500":t.is_warning?"bg-amber-500":"bg-bambu-green":"bg-bambu-gray/30",h=()=>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",f=()=>{if(!t.enabled)return a("common.disabled");if(o==="days"){const p=t.days_until_due??0;return t.is_due?a("maintenance.overdueBy",{duration:Tg(Math.abs(p),"days",a)}):t.is_warning?a("maintenance.dueIn",{duration:Tg(p,"days",a)}):a("maintenance.timeLeft",{duration:Tg(p,"days",a)})}else return t.is_due?a("maintenance.overdueBy",{duration:Tg(Math.abs(t.hours_until_due),"hours",a)}):t.is_warning?a("maintenance.dueIn",{duration:Tg(t.hours_until_due,"hours",a)}):a("maintenance.timeLeft",{duration:Tg(t.hours_until_due,"hours",a)})};return i.jsx("div",{className:`rounded-xl border p-4 transition-all ${h()}`,children:i.jsxs("div",{className:"flex items-start gap-3 max-[550px]:flex-wrap",children:[i.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:[i.jsx(s,{className:`w-5 h-5 ${u()}`}),t.enabled&&(t.is_due||t.is_warning)&&i.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`})]}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("h3",{className:`font-medium truncate ${t.enabled?"text-white":"text-bambu-gray"}`,children:t.maintenance_type_name}),o==="days"&&i.jsx("span",{title:a("maintenance.timeBasedInterval"),children:i.jsx(na,{className:"w-3.5 h-3.5 text-bambu-gray shrink-0"})}),(()=>{const p=t.maintenance_type_wiki_url||zZe(t.maintenance_type_name,t.printer_model);return p?i.jsx("a",{href:p,target:"_blank",rel:"noopener noreferrer",className:"text-bambu-gray hover:text-bambu-green transition-colors shrink-0",title:a("maintenance.viewDocumentation"),onClick:x=>x.stopPropagation(),children:i.jsx(Kr,{className:"w-3.5 h-3.5"})}):null})()]}),i.jsx("div",{className:"mt-2 mb-1.5",children:i.jsx("div",{className:"w-full h-1.5 bg-bambu-dark rounded-full overflow-hidden",children:i.jsx("div",{className:`h-full rounded-full transition-all duration-500 ${d()}`,style:{width:`${c}%`}})})}),i.jsxs("div",{className:`text-xs flex items-center gap-1 ${u()}`,children:[t.is_due&&i.jsx(Tn,{className:"w-3 h-3"}),t.is_warning&&!t.is_due&&i.jsx(Gn,{className:"w-3 h-3"}),!t.is_due&&!t.is_warning&&t.enabled&&i.jsx(ra,{className:"w-3 h-3"}),f()]})]}),i.jsxs("div",{className:"flex items-center gap-2 shrink-0 max-[550px]:w-full max-[550px]:justify-end max-[550px]:mt-1",children:[i.jsx("span",{title:r("maintenance:update")?void 0:a("maintenance.noPermissionUpdate"),children:i.jsx(On,{checked:t.enabled,onChange:p=>n(t.id,p),disabled:!r("maintenance:update")})}),i.jsxs(Ce,{size:"sm",variant:t.is_due?"primary":"secondary",onClick:()=>e(t.id),disabled:!t.enabled||!r("maintenance:update"),title:r("maintenance:update")?void 0:a("maintenance.noPermissionPerform"),className:"!px-3",children:[i.jsx(Fo,{className:"w-3.5 h-3.5"}),a("common.reset")]})]})]})})}function BZe({overview:t,onPerform:e,onToggle:n,onSetHours:r,hasPermission:a,t:s}){const[o,l]=w.useState(!1),[c,u]=w.useState(!1),[d,h]=w.useState(t.total_print_hours.toFixed(1)),f=[...t.maintenance_items].sort((v,g)=>v.is_due&&!g.is_due?-1:!v.is_due&&g.is_due?1:v.is_warning&&!g.is_warning?-1:!v.is_warning&&g.is_warning?1:v.maintenance_type_id-g.maintenance_type_id),p=f.find(v=>v.enabled&&(v.is_due||v.is_warning)),x=()=>{const v=parseFloat(d);!isNaN(v)&&v>=0&&(r(t.printer_id,v),u(!1))};return i.jsxs(vt,{className:"overflow-hidden",children:[i.jsxs("div",{className:"p-5",children:[i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{className:"flex items-center gap-4",children:[i.jsx("h2",{className:"text-xl font-semibold text-white",children:t.printer_name}),i.jsxs("div",{className:"flex items-center gap-2",children:[t.due_count>0&&i.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:[i.jsx(Tn,{className:"w-3 h-3"}),s("maintenance.overdueCount",{count:t.due_count})]}),t.warning_count>0&&i.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:[i.jsx(Gn,{className:"w-3 h-3"}),s("maintenance.dueSoonCount",{count:t.warning_count})]}),t.due_count===0&&t.warning_count===0&&i.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:[i.jsx(ra,{className:"w-3 h-3"}),s("maintenance.allGood")]})]})]}),i.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?i.jsx(yl,{className:"w-4 h-4"}):i.jsx(Un,{className:"w-4 h-4"}),s(o?"common.collapse":"common.expand")]})]}),i.jsxs("div",{className:"flex items-center gap-6 mt-4",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("div",{className:"p-2 bg-bambu-dark/50 rounded-lg",children:i.jsx(Lu,{className:"w-4 h-4 text-bambu-gray"})}),c?i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("input",{type:"number",value:d,onChange:v=>h(v.target.value),onKeyDown:v=>{v.key==="Enter"&&x(),v.key==="Escape"&&u(!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}),i.jsx("span",{className:"text-xs text-bambu-gray",children:s("common.hours")}),i.jsx(Ce,{size:"sm",onClick:x,children:s("common.save")}),i.jsx(Ce,{size:"sm",variant:"secondary",onClick:()=>u(!1),children:s("common.cancel")})]}):i.jsxs("button",{onClick:()=>{a("maintenance:update")&&(h(Math.round(t.total_print_hours).toString()),u(!0))},className:`group ${a("maintenance:update")?"":"cursor-not-allowed opacity-60"}`,title:a("maintenance:update")?void 0:s("maintenance.noPermissionEditHours"),children:[i.jsxs("div",{className:`text-sm font-medium text-white ${a("maintenance:update")?"group-hover:text-bambu-green":""} transition-colors flex items-center gap-1`,children:[Math.round(t.total_print_hours)," ",s("common.hours"),i.jsx(Tf,{className:`w-3 h-3 text-bambu-gray ${a("maintenance:update")?"group-hover:text-bambu-green":""}`})]}),i.jsx("div",{className:"text-xs text-bambu-gray",children:s("maintenance.totalPrintTime")})]})]}),i.jsx("div",{className:"w-px h-10 bg-bambu-dark-tertiary"}),p&&i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("div",{className:`p-2 rounded-lg ${p.is_due?"bg-red-500/20":"bg-amber-500/20"}`,children:(()=>{const v=ov(p.maintenance_type_icon);return i.jsx(v,{className:`w-4 h-4 ${p.is_due?"text-red-400":"text-amber-400"}`})})()}),i.jsxs("div",{children:[i.jsx("div",{className:`text-sm font-medium ${p.is_due?"text-red-400":"text-amber-400"}`,children:p.maintenance_type_name}),i.jsx("div",{className:`text-xs ${p.is_due?"text-red-400/70":"text-amber-400/70"}`,children:p.is_due?s("common.overdue"):s("maintenance.dueSoon")})]})]})]})]}),o&&i.jsx(_t,{className:"pt-0 border-t border-bambu-dark-tertiary",children:i.jsx("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-3 pt-4",children:f.map(v=>i.jsx(UZe,{item:v,onPerform:e,onToggle:n,hasPermission:a,t:s},v.id))})})]})}function HZe({overview:t,types:e,onUpdateInterval:n,onAddType:r,onUpdateType:a,onDeleteType:s,onRestoreDefaults:o,isRestoringDefaults:l,onAssignType:c,onRemoveItem:u,hasPermission:d,t:h}){const[f,p]=w.useState(null),[x,v]=w.useState(""),[g,y]=w.useState("hours"),[_,N]=w.useState(!1),[k,A]=w.useState(""),[M,C]=w.useState("100"),[j,P]=w.useState("hours"),[E,B]=w.useState("Wrench"),[O,U]=w.useState(""),[R,V]=w.useState(new Set),[G,z]=w.useState(null),[K,Y]=w.useState(null),ae=w.useMemo(()=>t?t.map(L=>({id:L.printer_id,name:L.printer_name})):[],[t]),$=L=>t?t.filter(D=>D.maintenance_items.some(H=>H.maintenance_type_id===L)).map(D=>({printerId:D.printer_id,printerName:D.printer_name,itemId:D.maintenance_items.find(H=>H.maintenance_type_id===L)?.id})):[],W=L=>{if(!t)return[];const D=new Set($(L).map(H=>H.printerId));return ae.filter(H=>!D.has(H.id))},[ee,J]=w.useState(null),[ye,me]=w.useState(""),[te,je]=w.useState(""),[ue,oe]=w.useState("hours"),[_e,se]=w.useState("Wrench"),[Oe,q]=w.useState(""),X=L=>{J(L),me(L.name),je(L.default_interval_hours.toString()),oe(L.interval_type||"hours"),se(L.icon||"Wrench"),q(L.wiki_url||"")},de=()=>{ee&&ye.trim()&&parseFloat(te)>0&&(a(ee.id,{name:ye.trim(),default_interval_hours:parseFloat(te),interval_type:ue,icon:_e,wiki_url:Oe.trim()||null}),J(null))},Z=(L,D,H)=>{const he=parseFloat(x);if(!isNaN(he)&&he>0){const be=Math.abs(he-D)<.01?null:he;n(L,{custom_interval_hours:be,custom_interval_type:g!==H?g:null})}p(null)},ie=L=>{L.preventDefault(),k.trim()&&parseFloat(M)>0&&R.size>0&&(r({name:k.trim(),default_interval_hours:parseFloat(M),interval_type:j,icon:E,wiki_url:O.trim()||null},Array.from(R)),A(""),C("100"),P("hours"),U(""),V(new Set),N(!1))},le=L=>{V(D=>{const H=new Set(D);return H.has(L)?H.delete(L):H.add(L),H})},Fe=t?.map(L=>({printerId:L.printer_id,printerName:L.printer_name,items:L.maintenance_items.sort((D,H)=>D.maintenance_type_id-H.maintenance_type_id)})).sort((L,D)=>L.printerName.localeCompare(D.printerName))||[],pe=e.filter(L=>L.is_system),Q=e.filter(L=>!L.is_system);return i.jsxs("div",{className:"space-y-8",children:[i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center justify-between mb-4",children:[i.jsxs("div",{children:[i.jsx("h2",{className:"text-lg font-semibold text-white",children:h("maintenance.maintenanceTypes")}),i.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:h("maintenance.maintenanceTypesDescription")})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(Ce,{variant:"secondary",onClick:o,disabled:!d("maintenance:delete")||l,title:d("maintenance:delete")?void 0:h("maintenance.noPermissionDeleteTypes"),children:h("maintenance.restoreDefaults")}),i.jsxs(Ce,{onClick:()=>N(!_),disabled:!d("maintenance:create"),title:d("maintenance:create")?void 0:h("maintenance.noPermissionEditTypes"),children:[i.jsx(Xn,{className:"w-4 h-4"}),h("maintenance.addCustomType")]})]})]}),_&&i.jsx(vt,{className:"mb-6",children:i.jsx(_t,{className:"py-4",children:i.jsxs("form",{onSubmit:ie,children:[i.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4",children:[i.jsxs("div",{className:"lg:col-span-2",children:[i.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:h("common.name")}),i.jsx("input",{type:"text",value:k,onChange:L=>A(L.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:h("maintenance.exampleName"),autoFocus:!0})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:h("maintenance.intervalType")}),i.jsxs("select",{value:j,onChange:L=>{P(L.target.value),L.target.value==="days"?C("30"):C("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:[i.jsx("option",{value:"hours",children:h("maintenance.printHours")}),i.jsx("option",{value:"days",children:h("maintenance.calendarDays")})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:h("maintenance.intervalValue",{type:j==="days"?h("maintenance.calendarDays").toLowerCase():h("common.hours")})}),i.jsx("input",{type:"number",value:M,onChange:L=>C(L.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"})]})]}),i.jsx("div",{className:"mt-4 flex items-end justify-between",children:i.jsxs("div",{children:[i.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:h("maintenance.icon")}),i.jsx("div",{className:"flex gap-1",children:Object.keys(Oy).map(L=>{const D=Oy[L];return i.jsx("button",{type:"button",onClick:()=>B(L),className:`p-2 rounded-lg transition-colors ${E===L?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary"}`,children:i.jsx(D,{className:"w-4 h-4"})},L)})})]})}),i.jsxs("div",{className:"mt-4",children:[i.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:h("maintenance.documentationLink")}),i.jsx("input",{type:"url",value:O,onChange:L=>U(L.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/..."})]}),i.jsxs("div",{className:"mt-4",children:[i.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:h("maintenance.assignToPrinters")}),i.jsx("div",{className:"flex flex-wrap gap-2",children:ae.map(L=>i.jsx("button",{type:"button",onClick:()=>le(L.id),className:`px-3 py-1.5 rounded-lg text-sm transition-colors ${R.has(L.id)?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary"}`,children:L.name},L.id))}),R.size===0&&i.jsx("p",{className:"text-xs text-orange-400 mt-1",children:h("maintenance.selectAtLeastOnePrinter")})]}),i.jsxs("div",{className:"mt-4 flex justify-end gap-2",children:[i.jsx(Ce,{type:"button",variant:"secondary",onClick:()=>{N(!1),V(new Set)},children:h("common.cancel")}),i.jsx(Ce,{type:"submit",disabled:!k.trim()||R.size===0,children:h("maintenance.addType")})]})]})})}),i.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3",children:[pe.map(L=>{const D=ov(L.icon),H=L.interval_type||"hours";return i.jsx("div",{className:"bg-bambu-dark-secondary rounded-xl p-4 border border-bambu-dark-tertiary",children:i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("div",{className:"p-2.5 bg-bambu-dark rounded-lg",children:i.jsx(D,{className:"w-5 h-5 text-bambu-gray"})}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsx("div",{className:"text-sm font-medium text-white truncate",children:L.name}),i.jsxs("div",{className:"text-xs text-bambu-gray mt-0.5 flex items-center gap-1",children:[H==="days"?i.jsx(na,{className:"w-3 h-3"}):i.jsx(Lu,{className:"w-3 h-3"}),Tj(L.default_interval_hours,H,h)]})]}),i.jsx("button",{onClick:()=>{d("maintenance:delete")&&Y(L)},disabled:!d("maintenance:delete"),title:d("maintenance:delete")?void 0:h("maintenance.noPermissionDeleteTypes"),className:`p-2 rounded-lg hover:bg-bambu-dark text-bambu-gray hover:text-red-400 transition-colors ${d("maintenance:delete")?"":"opacity-50 cursor-not-allowed"}`,children:i.jsx(Jt,{className:"w-4 h-4"})})]})},L.id)}),Q.map(L=>{const D=ov(L.icon),H=L.interval_type||"hours";if(ee?.id===L.id)return i.jsx("div",{className:"bg-bambu-dark-secondary rounded-xl p-4 border border-bambu-green",children:i.jsxs("div",{className:"space-y-3",children:[i.jsx("input",{type:"text",value:ye,onChange:Ie=>me(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",placeholder:h("common.name"),autoFocus:!0}),i.jsxs("div",{className:"flex gap-2",children:[i.jsxs("select",{value:ue,onChange:Ie=>oe(Ie.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:[i.jsx("option",{value:"hours",children:h("maintenance.printHours")}),i.jsx("option",{value:"days",children:h("maintenance.calendarDays")})]}),i.jsx("input",{type:"number",value:te,onChange:Ie=>je(Ie.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"})]}),i.jsx("div",{className:"flex flex-wrap gap-1",children:Object.keys(Oy).map(Ie=>{const qe=Oy[Ie];return i.jsx("button",{type:"button",onClick:()=>se(Ie),className:`p-1.5 rounded transition-colors ${_e===Ie?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:i.jsx(qe,{className:"w-3.5 h-3.5"})},Ie)})}),i.jsx("input",{type:"url",value:Oe,onChange:Ie=>q(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",placeholder:h("maintenance.documentationLink")}),i.jsxs("div",{className:"flex gap-2",children:[i.jsx(Ce,{size:"sm",onClick:de,disabled:!ye.trim(),children:h("common.save")}),i.jsx(Ce,{size:"sm",variant:"secondary",onClick:()=>J(null),children:h("common.cancel")})]})]})},L.id);const be=$(L.id),fe=W(L.id),ze=G===L.id;return i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-xl p-4 border border-bambu-green/30",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("div",{className:"p-2.5 bg-bambu-green/20 rounded-lg",children:i.jsx(D,{className:"w-5 h-5 text-bambu-green"})}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"text-sm font-medium text-white truncate",children:L.name}),i.jsx("span",{className:"px-1.5 py-0.5 bg-bambu-green/20 text-bambu-green text-[10px] font-medium rounded",children:h("maintenance.custom")})]}),i.jsxs("div",{className:"text-xs text-bambu-gray mt-0.5 flex items-center gap-1",children:[H==="days"?i.jsx(na,{className:"w-3 h-3"}):i.jsx(Lu,{className:"w-3 h-3"}),Tj(L.default_interval_hours,H,h)]})]}),i.jsxs("button",{onClick:()=>z(ze?null:L.id),className:`px-2 py-1 rounded-lg border transition-colors flex items-center gap-1 ${be.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:h("maintenance.printersAssignedClick",{count:be.length}),children:[i.jsx(xr,{className:"w-3 h-3"}),i.jsx("span",{className:"text-xs font-medium",children:be.length}),i.jsx(Un,{className:`w-3 h-3 transition-transform ${ze?"rotate-180":""}`})]}),i.jsx("button",{onClick:()=>X(L),disabled:!d("maintenance:update"),title:d("maintenance:update")?void 0:h("maintenance.noPermissionEditTypes"),className:`p-2 rounded-lg hover:bg-bambu-dark text-bambu-gray hover:text-white transition-colors ${d("maintenance:update")?"":"opacity-50 cursor-not-allowed"}`,children:i.jsx(Tf,{className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>{confirm(h("maintenance.deleteTypeConfirm",{name:L.name}))&&s(L.id)},disabled:!d("maintenance:delete"),title:d("maintenance:delete")?void 0:h("maintenance.noPermissionDeleteTypes"),className:`p-2 rounded-lg hover:bg-bambu-dark text-bambu-gray hover:text-red-400 transition-colors ${d("maintenance:delete")?"":"opacity-50 cursor-not-allowed"}`,children:i.jsx(Jt,{className:"w-4 h-4"})})]}),ze&&i.jsxs("div",{className:"mt-3 pt-3 border-t border-bambu-dark-tertiary",children:[i.jsx("p",{className:"text-xs text-bambu-gray mb-2",children:h("maintenance.assignedToPrinters")}),be.length===0?i.jsx("p",{className:"text-xs text-orange-400",children:h("maintenance.noPrintersAssigned")}):i.jsx("div",{className:"flex flex-wrap gap-1 mb-2",children:be.map(Ie=>i.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-1 bg-bambu-dark rounded text-xs text-white",children:[Ie.printerName,i.jsx("button",{onClick:()=>Ie.itemId&&u(Ie.itemId),disabled:!d("maintenance:delete"),title:d("maintenance:delete")?h("maintenance.removeFromPrinter"):h("maintenance.noPermissionRemovePrinter"),className:`ml-1 ${d("maintenance:delete")?"hover:text-red-400":"opacity-50 cursor-not-allowed"}`,children:"×"})]},Ie.printerId))}),fe.length>0&&i.jsxs("div",{className:"flex flex-wrap gap-1",children:[i.jsx("span",{className:"text-xs text-bambu-gray mr-1",children:h("maintenance.addPrinterShort")}),fe.map(Ie=>i.jsxs("button",{onClick:()=>c(Ie.id,L.id),disabled:!d("maintenance:create"),title:d("maintenance:create")?void 0:h("maintenance.noPermissionAssignPrinter"),className:`px-2 py-1 bg-bambu-dark rounded text-xs transition-colors ${d("maintenance:create")?"hover:bg-bambu-green/20 text-bambu-gray hover:text-bambu-green":"opacity-50 cursor-not-allowed text-bambu-gray"}`,children:["+ ",Ie.name]},Ie.id))]})]})]},L.id)})]})]}),Fe.length>0&&i.jsxs("div",{children:[i.jsxs("div",{className:"mb-4",children:[i.jsx("h2",{className:"text-lg font-semibold text-white",children:h("maintenance.intervalOverrides")}),i.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:h("maintenance.intervalOverridesDescription")})]}),i.jsx("div",{className:"space-y-4",children:Fe.map(L=>i.jsx(vt,{children:i.jsxs(_t,{className:"py-4",children:[i.jsx("h3",{className:"text-sm font-medium text-white mb-3",children:L.printerName}),i.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-2",children:L.items.map(D=>{const H=ov(D.maintenance_type_icon),he=e.find(qe=>qe.id===D.maintenance_type_id),be=he?.default_interval_hours||D.interval_hours,fe=he?.interval_type||"hours",ze=D.interval_type||"hours",Ie=f===D.id;return i.jsxs("div",{className:"flex items-center gap-2 p-2.5 bg-bambu-dark rounded-lg",children:[i.jsx(H,{className:"w-4 h-4 text-bambu-gray shrink-0"}),i.jsx("span",{className:"text-xs text-bambu-gray flex-1 truncate",children:D.maintenance_type_name}),Ie?i.jsxs("div",{className:"flex items-center gap-1",children:[g==="days"?i.jsx(na,{className:"w-3.5 h-3.5 text-bambu-gray shrink-0"}):i.jsx(Lu,{className:"w-3.5 h-3.5 text-bambu-gray shrink-0"}),i.jsxs("select",{value:g,onChange:qe=>y(qe.target.value),className:"px-1.5 py-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-xs",children:[i.jsx("option",{value:"hours",children:h("maintenance.printHours")}),i.jsx("option",{value:"days",children:h("maintenance.calendarDays")})]}),i.jsx("input",{type:"number",value:x,onChange:qe=>v(qe.target.value),onKeyDown:qe=>{qe.key==="Enter"&&Z(D.id,be,fe),qe.key==="Escape"&&p(null)},className:"w-16 px-2 py-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-xs",min:"1"}),i.jsx(Ce,{size:"sm",onClick:()=>Z(D.id,be,fe),children:"OK"})]}):i.jsxs("button",{onClick:()=>{d("maintenance:update")&&(p(D.id),v(D.interval_hours.toString()),y(ze))},disabled:!d("maintenance:update"),title:d("maintenance:update")?void 0:h("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 ${d("maintenance:update")?"hover:bg-bambu-dark-secondary hover:border-bambu-green":"opacity-50 cursor-not-allowed"}`,children:[ze==="days"?i.jsx(na,{className:"w-3 h-3"}):i.jsx(Lu,{className:"w-3 h-3"}),Tj(D.interval_hours,ze,h),i.jsx(Tf,{className:"w-3 h-3 text-bambu-gray"})]})]},D.id)})})]})},L.printerId))})]}),Fe.length===0&&i.jsx(vt,{children:i.jsxs(_t,{className:"text-center py-12",children:[i.jsx(Gn,{className:"w-12 h-12 mx-auto mb-4 text-bambu-gray/30"}),i.jsx("p",{className:"text-bambu-gray",children:h("common.noPrinters")}),i.jsx("p",{className:"text-sm text-bambu-gray/70 mt-1",children:h("maintenance.intervalOverridesDescription")})]})}),K&&i.jsx(gn,{title:h("maintenance.deleteSystemTypeTitle"),message:h("maintenance.deleteSystemTypeMessage",{name:K.name}),confirmText:h("common.delete"),cancelText:h("common.cancel"),variant:"danger",cancelVariant:"primary",cardClassName:"bg-red-950/70 border border-red-800/70",onConfirm:()=>{s(K.id),Y(null)},onCancel:()=>Y(null)})]})}function $Ze(){const{t}=Ut(),e=tn(),{showToast:n}=cn(),{hasPermission:r}=Or(),[a,s]=w.useState("status"),{data:o,isLoading:l}=Je({queryKey:["maintenanceOverview"],queryFn:ne.getMaintenanceOverview}),{data:c}=Je({queryKey:["maintenanceTypes"],queryFn:ne.getMaintenanceTypes}),u=ot({mutationFn:({id:M,notes:C})=>ne.performMaintenance(M,C),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]}),e.invalidateQueries({queryKey:["maintenanceSummary"]}),n(t("maintenance.maintenanceComplete"))},onError:M=>{n(M.message,"error")}}),d=ot({mutationFn:({id:M,data:C})=>ne.updateMaintenanceItem(M,C),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]})},onError:M=>{n(M.message,"error")}}),h=ot({mutationFn:({id:M,data:C})=>ne.updateMaintenanceType(M,C),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceTypes"]}),e.invalidateQueries({queryKey:["maintenanceOverview"]}),n(t("maintenance.typeUpdated"))},onError:M=>{n(M.message,"error")}}),f=ot({mutationFn:ne.deleteMaintenanceType,onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceTypes"]}),e.invalidateQueries({queryKey:["maintenanceOverview"]}),n(t("maintenance.typeDeleted"))},onError:M=>{n(M.message,"error")}}),p=ot({mutationFn:ne.restoreDefaultMaintenanceTypes,onSuccess:M=>{e.invalidateQueries({queryKey:["maintenanceTypes"]}),e.invalidateQueries({queryKey:["maintenanceOverview"]}),n(t("maintenance.defaultsRestored",{count:M.restored}))},onError:M=>{n(M.message,"error")}}),x=ot({mutationFn:({printerId:M,hours:C})=>ne.setPrinterHours(M,C),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]}),e.invalidateQueries({queryKey:["maintenanceSummary"]}),n(t("maintenance.printHoursUpdated"))},onError:M=>{n(M.message,"error")}}),v=ot({mutationFn:({printerId:M,typeId:C})=>ne.assignMaintenanceType(M,C),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]}),n(t("maintenance.printerAssigned"))},onError:M=>{n(M.message,"error")}}),g=ot({mutationFn:ne.removeMaintenanceItem,onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]}),n(t("maintenance.printerRemoved"))},onError:M=>{n(M.message,"error")}}),y=M=>{u.mutate({id:M})},_=(M,C)=>{d.mutate({id:M,data:{enabled:C}})},N=(M,C)=>{x.mutate({printerId:M,hours:C})};if(l)return i.jsx("div",{className:"p-4 md:p-8 flex justify-center",children:i.jsx(it,{className:"w-8 h-8 text-bambu-green animate-spin"})});const k=o?.reduce((M,C)=>M+C.due_count,0)||0,A=o?.reduce((M,C)=>M+C.warning_count,0)||0;return i.jsxs("div",{className:"p-4 md:p-8",children:[i.jsxs("div",{className:"mb-6",children:[i.jsx("h1",{className:"text-2xl font-bold text-white",children:t("maintenance.title")}),i.jsx("p",{className:"text-bambu-gray text-sm mt-1",children:a==="status"?i.jsxs(i.Fragment,{children:[k>0&&i.jsx("span",{className:"text-red-400",children:t("maintenance.dueCount",{count:k})}),k>0&&A>0&&" · ",A>0&&i.jsx("span",{className:"text-amber-400",children:t("maintenance.warningCount",{count:A})}),k===0&&A===0&&i.jsx("span",{className:"text-bambu-green",children:t("maintenance.allOk")})]}):t("maintenance.configureSettings")})]}),i.jsxs("div",{className:"flex gap-1 mb-6 border-b border-bambu-dark-tertiary",children:[i.jsx("button",{onClick:()=>s("status"),className:`px-4 py-2 text-sm font-medium border-b-2 -mb-px transition-colors ${a==="status"?"text-bambu-green border-bambu-green":"text-bambu-gray border-transparent hover:text-white"}`,children:t("maintenance.statusTab")}),i.jsx("button",{onClick:()=>s("settings"),className:`px-4 py-2 text-sm font-medium border-b-2 -mb-px transition-colors ${a==="settings"?"text-bambu-green border-bambu-green":"text-bambu-gray border-transparent hover:text-white"}`,children:t("maintenance.settingsTab")})]}),a==="status"?i.jsx("div",{className:"space-y-6",children:o&&o.length>0?[...o].sort((M,C)=>{const j=M.due_count*10+M.warning_count,P=C.due_count*10+C.warning_count;return j!==P?P-j:M.printer_name.localeCompare(C.printer_name)}).map(M=>i.jsx(BZe,{overview:M,onPerform:y,onToggle:_,onSetHours:N,hasPermission:r,t},M.printer_id)):i.jsx(vt,{children:i.jsxs(_t,{className:"text-center py-16",children:[i.jsx(Ef,{className:"w-16 h-16 mx-auto mb-4 text-bambu-gray/30"}),i.jsx("p",{className:"text-lg font-medium text-white mb-2",children:t("common.noPrinters")}),i.jsx("p",{className:"text-bambu-gray",children:t("maintenance.configureSettings")})]})})}):i.jsx(HZe,{overview:o,types:c||[],onUpdateInterval:(M,C)=>d.mutate({id:M,data:C}),onAddType:async(M,C)=>{const j=await ne.createMaintenanceType(M);for(const P of C)await ne.assignMaintenanceType(P,j.id);e.invalidateQueries({queryKey:["maintenanceTypes"]}),e.invalidateQueries({queryKey:["maintenanceOverview"]}),n(t("maintenance.typeUpdated"))},onUpdateType:(M,C)=>h.mutate({id:M,data:C}),onDeleteType:M=>f.mutate(M),onRestoreDefaults:()=>p.mutate(),isRestoringDefaults:p.isPending,onAssignType:(M,C)=>v.mutate({printerId:M,typeId:C}),onRemoveItem:M=>g.mutate(M),hasPermission:r,t})]})}const JW=["#ef4444","#f97316","#eab308","#22c55e","#06b6d4","#3b82f6","#8b5cf6","#ec4899","#6b7280"];function Uie({project:t,onClose:e,onSave:n,isLoading:r,t:a}){const[s,o]=w.useState(t?.name||""),[l,c]=w.useState(t?.description||""),[u,d]=w.useState(t?.color||JW[0]),[h,f]=w.useState(t?.target_count?.toString()||""),[p,x]=w.useState(t?.target_parts_count?.toString()||""),[v,g]=w.useState(t?.status||"active"),[y,_]=w.useState(t?.tags||""),[N,k]=w.useState(t?.due_date?.split("T")[0]||""),[A,M]=w.useState(t?.priority||"normal"),C=j=>{j.preventDefault(),n({name:s.trim(),description:l.trim()||void 0,color:u,target_count:h?parseInt(h,10):void 0,target_parts_count:p?parseInt(p,10):void 0,tags:y.trim()||void 0,due_date:N||void 0,priority:A,...t&&{status:v}})};return i.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-md border border-bambu-dark-tertiary",children:[i.jsx("div",{className:"p-4 border-b border-bambu-dark-tertiary",children:i.jsx("h2",{className:"text-lg font-semibold text-white",children:a(t?"projects.editProject":"projects.newProject")})}),i.jsxs("form",{onSubmit:C,className:"p-4 space-y-4",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:a("common.name")}),i.jsx("input",{type:"text",value:s,onChange:j=>o(j.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("projects.namePlaceholder"),required:!0})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:a("common.description")}),i.jsx("textarea",{value:l,onChange:j=>c(j.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:a("projects.descriptionPlaceholder"),rows:2})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:a("projects.color")}),i.jsx("div",{className:"flex gap-2 flex-wrap",children:JW.map(j=>i.jsx("button",{type:"button",onClick:()=>d(j),className:`w-8 h-8 rounded-full transition-transform ${u===j?"ring-2 ring-white ring-offset-2 ring-offset-bambu-dark-secondary scale-110":""}`,style:{backgroundColor:j}},j))})]}),i.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:a("projects.targetPlates")}),i.jsx("input",{type:"number",value:h,onChange:j=>f(j.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("projects.targetPlatesPlaceholder"),min:"1"}),i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:a("projects.targetPlatesHelp")})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:a("projects.targetParts")}),i.jsx("input",{type:"number",value:p,onChange:j=>x(j.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("projects.targetPartsPlaceholder"),min:"1"}),i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:a("projects.targetPartsHelp")})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:a("projects.tagsLabel")}),i.jsx("input",{type:"text",value:y,onChange:j=>_(j.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("projects.tagsPlaceholder")})]}),i.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:a("projects.dueDate")}),i.jsx("input",{type:"date",value:N,onChange:j=>k(j.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"})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:a("projects.priority")}),i.jsxs("select",{value:A,onChange:j=>M(j.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:[i.jsx("option",{value:"low",children:a("projects.priorityLow")}),i.jsx("option",{value:"normal",children:a("projects.priorityNormal")}),i.jsx("option",{value:"high",children:a("projects.priorityHigh")}),i.jsx("option",{value:"urgent",children:a("projects.priorityUrgent")})]})]})]}),t&&i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:a("common.status")}),i.jsxs("select",{value:v,onChange:j=>g(j.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:[i.jsx("option",{value:"active",children:a("projects.statusActive")}),i.jsx("option",{value:"completed",children:a("projects.statusCompleted")}),i.jsx("option",{value:"archived",children:a("projects.statusArchived")})]})]}),i.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[i.jsx(Ce,{type:"button",variant:"secondary",onClick:e,children:a("common.cancel")}),i.jsx(Ce,{type:"submit",disabled:!s.trim()||r,children:r?i.jsx(it,{className:"w-4 h-4 animate-spin"}):a(t?"common.save":"projects.create")})]})]})]})})}function VZe({project:t,onClick:e,onEdit:n,onDelete:r,hasPermission:a,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",u=t.status==="archived",[d,h]=w.useState(!1),p=c?{icon:ob,color:"text-bambu-green",bg:"bg-bambu-green/10"}:u?{icon:js,color:"text-bambu-gray",bg:"bg-bambu-gray/10"}:t.queue_count>0?{icon:Gn,color:"text-blue-400",bg:"bg-blue-400/10"}:{icon:gs,color:"text-bambu-gray",bg:"bg-bambu-gray/10"};return i.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:[i.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`}}),i.jsxs("div",{className:"p-5 pl-6",children:[i.jsxs("div",{className:"flex items-start justify-between mb-4",children:[i.jsxs("div",{className:"flex items-center gap-3 min-w-0 flex-1",children:[i.jsx("div",{className:`p-2 rounded-lg ${p.bg} flex-shrink-0`,children:i.jsx(p.icon,{className:`w-5 h-5 ${p.color}`})}),i.jsxs("div",{className:"min-w-0 flex-1",children:[i.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[i.jsx("h3",{className:"font-semibold text-white truncate",children:t.name}),t.target_parts_count?i.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?i.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?i.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&&i.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")}),u&&i.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&&i.jsx("p",{className:"text-sm text-bambu-gray/70 mt-1 line-clamp-1",children:t.description}),t.archives&&t.archives.length>0&&(()=>{const x=t.archives.map(_=>_.filament_type).filter(Boolean).flatMap(_=>_.split(",").map(N=>N.trim())).filter(Boolean),v=[...new Set(x)],g=t.archives.map(_=>_.filament_color).filter(Boolean).flatMap(_=>_.split(",").map(N=>N.trim())).filter(_=>_.startsWith("#")||/^[0-9A-Fa-f]{6}$/.test(_)),y=[...new Set(g)];return v.length===0&&y.length===0?null:i.jsxs("div",{className:"flex items-center gap-2 mt-1.5",children:[v.slice(0,3).map(_=>i.jsx("span",{className:"text-[10px] px-1.5 py-0.5 bg-bambu-dark text-bambu-gray rounded",children:_},_)),y.length>0&&i.jsxs("div",{className:"flex items-center gap-0.5",children:[y.slice(0,5).map(_=>i.jsx("div",{className:"w-3 h-3 rounded-full border border-white/20",style:{backgroundColor:_.startsWith("#")?_:`#${_}`},title:_},_)),y.length>5&&i.jsxs("span",{className:"text-[10px] text-bambu-gray ml-0.5",children:["+",y.length-5]})]})]})})()]})]}),i.jsxs("div",{className:"relative",onClick:x=>x.stopPropagation(),children:[i.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:()=>h(!d),children:i.jsx(Ah,{className:"w-4 h-4"})}),d&&i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>h(!1)}),i.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:[i.jsxs("button",{className:`w-full px-3 py-2 text-left text-sm flex items-center gap-2 ${a("projects:update")?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{a("projects:update")&&(n(),h(!1))},disabled:!a("projects:update"),title:a("projects:update")?void 0:s("projects.noEditPermission"),children:[i.jsx(Tf,{className:"w-4 h-4"}),s("common.edit")]}),i.jsxs("button",{className:`w-full px-3 py-2 text-left text-sm flex items-center gap-2 ${a("projects:delete")?"text-red-400 hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{a("projects:delete")&&(r(),h(!1))},disabled:!a("projects:delete"),title:a("projects:delete")?void 0:s("projects.noDeletePermission"),children:[i.jsx(Jt,{className:"w-4 h-4"}),s("common.delete")]})]})]})]})]}),i.jsx("div",{className:"mb-4",children:t.target_count||t.target_parts_count?i.jsxs("div",{className:"space-y-3",children:[t.target_count&&i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center justify-between text-xs mb-1",children:[i.jsx("span",{className:"text-bambu-gray",children:s("projects.plates")}),i.jsxs("span",{className:o>=100?"text-bambu-green font-medium":"text-white",children:[t.archive_count," / ",t.target_count]})]}),i.jsx("div",{className:"h-2 bg-bambu-dark/80 rounded-full overflow-hidden backdrop-blur-sm",children:i.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&&i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center justify-between text-xs mb-1",children:[i.jsx("span",{className:"text-bambu-gray",children:s("projects.parts")}),i.jsxs("span",{className:l>=100?"text-bambu-green font-medium":"text-white",children:[t.completed_count," / ",t.target_parts_count]})]}),i.jsx("div",{className:"h-2 bg-bambu-dark/80 rounded-full overflow-hidden backdrop-blur-sm",children:i.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&&i.jsxs("div",{className:"text-xs text-red-400",children:[t.failed_count," ",s("projects.failed")]})]}):t.completed_count>0||t.failed_count>0?i.jsxs("div",{className:"flex items-center gap-4 text-xs",children:[t.completed_count>0&&i.jsxs("div",{className:"flex items-center gap-1.5 text-bambu-gray",children:[i.jsx(js,{className:"w-3.5 h-3.5"}),i.jsxs("span",{children:[t.completed_count," ",s("projects.completed")]})]}),t.failed_count>0&&i.jsxs("div",{className:"flex items-center gap-1.5 text-red-400",children:[i.jsx(Tn,{className:"w-3.5 h-3.5"}),i.jsxs("span",{children:[t.failed_count," ",s("projects.failed")]})]}),t.queue_count>0&&i.jsxs("div",{className:"flex items-center gap-1.5 text-blue-400",children:[i.jsx(Gn,{className:"w-3.5 h-3.5"}),i.jsxs("span",{children:[t.queue_count," ",s("projects.inQueue")]})]})]}):i.jsx("div",{className:"text-xs text-bambu-gray/60 italic",children:s("projects.noPrintsYet")})}),t.archives&&t.archives.length>0&&i.jsxs("div",{className:"mb-4",children:[i.jsx("div",{className:"grid grid-cols-4 gap-1.5",children:t.archives.slice(0,4).map(x=>i.jsxs("div",{className:"relative aspect-square rounded-lg bg-bambu-dark overflow-hidden border border-bambu-dark-tertiary",title:x.print_name||"Unknown",children:[x.thumbnail_path?i.jsx("img",{src:ne.getArchiveThumbnail(x.id),alt:x.print_name||"",className:"w-full h-full object-cover"}):i.jsx("div",{className:"w-full h-full flex items-center justify-center text-bambu-gray/50",children:i.jsx(fi,{className:"w-6 h-6"})}),x.status==="failed"&&i.jsx("div",{className:"absolute inset-0 bg-red-500/40 flex items-center justify-center",children:i.jsx(Tn,{className:"w-4 h-4 text-white"})})]},x.id))}),t.archive_count>4&&i.jsx("p",{className:"text-xs text-bambu-gray mt-1.5 text-center",children:s("common.more",{count:t.archive_count-4})})]}),i.jsxs("div",{className:"flex items-center justify-between pt-3 border-t border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex items-center gap-4 text-xs text-bambu-gray",children:[i.jsxs("div",{className:"flex items-center gap-1.5",title:s("projects.printJobs"),children:[i.jsx(mi,{className:"w-3.5 h-3.5 text-blue-400"}),i.jsxs("span",{children:[t.archive_count," ",s("projects.plates")]})]}),i.jsxs("div",{className:"flex items-center gap-1.5",title:s("projects.partsPrinted"),children:[i.jsx(fi,{className:"w-3.5 h-3.5 text-bambu-green"}),i.jsxs("span",{children:[t.completed_count," ",s("projects.parts")]})]}),t.failed_count>0&&i.jsxs("div",{className:"flex items-center gap-1.5 text-red-400",title:s("projects.failedParts"),children:[i.jsx(Tn,{className:"w-3.5 h-3.5"}),i.jsx("span",{children:t.failed_count})]}),t.queue_count>0&&i.jsxs("div",{className:"flex items-center gap-1.5 text-yellow-400",title:s("projects.inQueue"),children:[i.jsx(n3,{className:"w-3.5 h-3.5"}),i.jsx("span",{children:t.queue_count})]})]}),i.jsx(pi,{className:"w-4 h-4 text-bambu-gray/50 group-hover:text-bambu-gray transition-colors"})]})]})]})}function qZe(){const{t}=Ut(),e=rc(),n=tn(),{showToast:r}=cn(),{hasPermission:a}=Or(),[s,o]=w.useState(!1),[l,c]=w.useState(),[u,d]=w.useState("active"),[h,f]=w.useState(null),{data:p,isLoading:x}=Je({queryKey:["projects",u==="all"?void 0:u],queryFn:()=>ne.getProjects(u==="all"?void 0:u)}),v=ot({mutationFn:U=>ne.createProject(U),onSuccess:()=>{n.invalidateQueries({queryKey:["projects"]}),o(!1),r(t("projects.toast.created"),"success")},onError:U=>{r(U.message,"error")}}),g=ot({mutationFn:({id:U,data:R})=>ne.updateProject(U,R),onSuccess:()=>{n.invalidateQueries({queryKey:["projects"]}),o(!1),c(void 0),r(t("projects.toast.updated"),"success")},onError:U=>{r(U.message,"error")}}),y=ot({mutationFn:U=>ne.deleteProject(U),onSuccess:()=>{f(null),r(t("projects.toast.deleted"),"success"),setTimeout(()=>window.location.reload(),100)},onError:U=>{f(null),r(U.message,"error")}}),_=ot({mutationFn:U=>ne.importProject(U),onSuccess:()=>{n.invalidateQueries({queryKey:["projects"]}),r(t("projects.toast.imported"),"success")},onError:U=>{r(U.message,"error")}}),N=w.useRef(null),k=async()=>{try{const U=await ne.getProjects(),R=await Promise.all(U.map(async K=>await ne.exportProjectJson(K.id))),V=new Blob([JSON.stringify(R,null,2)],{type:"application/json"}),G=URL.createObjectURL(V),z=document.createElement("a");z.href=G,z.download=`bambuddy_projects_${new Date().toISOString().split("T")[0]}.json`,z.click(),URL.revokeObjectURL(G),r(t("projects.toast.exported"),"success")}catch(U){r(U.message,"error")}},A=()=>{N.current?.click()},M=async U=>{const R=U.target.files?.[0];if(R){try{if(R.name.toLowerCase().endsWith(".zip"))await ne.importProjectFile(R),n.invalidateQueries({queryKey:["projects"]}),r(t("projects.toast.imported"),"success");else{const G=await R.text(),z=JSON.parse(G),K=Array.isArray(z)?z:[z];for(const Y of K)await _.mutateAsync(Y);K.length>1&&r(t("projects.toast.multipleImported",{count:K.length}),"success")}}catch(V){r(`${t("projects.toast.importFailed")}: ${V.message}`,"error")}U.target.value=""}},C=U=>{l?g.mutate({id:l.id,data:U}):v.mutate(U)},j=U=>{c(U),o(!0)},P=U=>{e(`/projects/${U.id}`)},E=U=>{f(U)},B=()=>{h!==null&&y.mutate(h)},O=p?.reduce((U,R)=>(U[R.status]=(U[R.status]||0)+1,U.all=(U.all||0)+1,U),{})||{};return i.jsxs("div",{className:"p-4 md:p-8 space-y-8",children:[i.jsx("input",{ref:N,type:"file",accept:".json,.zip",onChange:M,className:"hidden"}),i.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4",children:[i.jsxs("div",{children:[i.jsxs("h1",{className:"text-2xl font-bold text-white flex items-center gap-3",children:[i.jsx("div",{className:"p-2.5 bg-bambu-green/10 rounded-xl",children:i.jsx(gs,{className:"w-6 h-6 text-bambu-green"})}),t("projects.title")]}),i.jsx("p",{className:"text-sm text-bambu-gray mt-2 ml-14",children:t("projects.subtitle")})]}),i.jsxs("div",{className:"flex gap-2",children:[i.jsxs(Ce,{variant:"secondary",onClick:A,disabled:!a("projects:create"),title:a("projects:create")?t("projects.importProject"):t("projects.noImportPermission"),children:[i.jsx(Ra,{className:"w-4 h-4 mr-2"}),t("projects.import")]}),i.jsxs(Ce,{variant:"secondary",onClick:k,disabled:!a("projects:read"),title:a("projects:read")?t("projects.exportAll"):t("projects.noExportPermission"),children:[i.jsx(ua,{className:"w-4 h-4 mr-2"}),t("projects.export")]}),i.jsxs(Ce,{onClick:()=>o(!0),className:"sm:w-auto w-full",disabled:!a("projects:create"),title:a("projects:create")?void 0:t("projects.noCreatePermission"),children:[i.jsx(Xn,{className:"w-4 h-4 mr-2"}),t("projects.newProject")]})]})]}),i.jsx("div",{className:"flex gap-1 p-1 bg-bambu-dark rounded-xl w-fit",children:[{key:"active",label:t("projects.statusActive"),icon:Gn},{key:"completed",label:t("projects.statusCompleted"),icon:ob},{key:"archived",label:t("projects.statusArchived"),icon:js},{key:"all",label:t("common.all"),icon:gs}].map(({key:U,label:R,icon:V})=>i.jsxs("button",{onClick:()=>d(U),className:`flex items-center gap-2 px-4 py-2 text-sm rounded-lg transition-all ${u===U?"bg-bambu-card text-white shadow-sm":"text-bambu-gray hover:text-white"}`,children:[i.jsx(V,{className:"w-4 h-4"}),i.jsx("span",{children:R}),O[U]>0&&i.jsx("span",{className:`text-xs px-1.5 py-0.5 rounded-full ${u===U?"bg-bambu-green/20 text-bambu-green":"bg-bambu-dark-tertiary"}`,children:O[U]})]},U))}),x?i.jsx("div",{className:"flex items-center justify-center py-20",children:i.jsxs("div",{className:"flex flex-col items-center gap-3",children:[i.jsx(it,{className:"w-8 h-8 animate-spin text-bambu-green"}),i.jsx("p",{className:"text-sm text-bambu-gray",children:t("projects.loading")})]})}):p?.length===0?i.jsxs("div",{className:"flex flex-col items-center justify-center py-20 px-4",children:[i.jsx("div",{className:"p-4 bg-bambu-dark rounded-2xl mb-4",children:i.jsx(gs,{className:"w-12 h-12 text-bambu-gray/50"})}),i.jsx("h3",{className:"text-lg font-medium text-white mb-2",children:u==="all"?t("projects.noProjects"):t("projects.noProjectsFiltered",{status:u})}),i.jsx("p",{className:"text-bambu-gray text-center max-w-md mb-6",children:u==="all"?t("projects.createFirst"):t("projects.noProjectsFilteredHelp",{status:u})}),u==="all"&&i.jsxs(Ce,{onClick:()=>o(!0),disabled:!a("projects:create"),title:a("projects:create")?void 0:t("projects.noCreatePermission"),children:[i.jsx(Xn,{className:"w-4 h-4 mr-2"}),t("projects.createFirstButton")]})]}):i.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-8",children:p?.map(U=>i.jsx(VZe,{project:U,onClick:()=>P(U),onEdit:()=>j(U),onDelete:()=>E(U.id),hasPermission:a,t},U.id))}),h!==null&&i.jsx(gn,{title:t("projects.deleteProject"),message:t("projects.deleteConfirm"),confirmText:t("projects.deleteProject"),variant:"danger",onConfirm:B,onCancel:()=>f(null)}),s&&i.jsx(Uie,{project:l,onClose:()=>{o(!1),c(void 0)},onSave:C,isLoading:v.isPending||g.isPending,t})]})}function GZe(t){if(t<1)return`${Math.round(t*60)}m`;const e=Math.floor(t),n=Math.round((t-e)*60);return n>0?`${e}h ${n}m`:`${e}h`}function WZe(t){return t>=1e3?`${(t/1e3).toFixed(2)}kg`:`${Math.round(t)}g`}function KZe({status:t,t:e}){const n={active:"bg-bambu-green/20 text-bambu-green",completed:"bg-blue-500/20 text-blue-400",archived:"bg-bambu-gray/20 text-bambu-gray"},r=n[t]||n.active,a={active:e("projectDetail.status.active"),completed:e("projectDetail.status.completed"),archived:e("projectDetail.status.archived")};return i.jsx("span",{className:`px-2 py-1 rounded text-sm font-medium ${r}`,children:a[t]||t.charAt(0).toUpperCase()+t.slice(1)})}function eK({icon:t,label:e,value:n,subValue:r,hint:a,color:s="text-bambu-gray"}){return i.jsx(vt,{children:i.jsx(_t,{className:"p-4",children:i.jsxs("div",{className:"flex items-center gap-3",title:a,children:[i.jsx("div",{className:`p-2 rounded-lg bg-bambu-dark ${s}`,children:i.jsx(t,{className:"w-5 h-5"})}),i.jsxs("div",{children:[i.jsx("p",{className:"text-sm text-bambu-gray",children:e}),i.jsx("p",{className:"text-xl font-semibold text-white",children:n}),r&&i.jsx("p",{className:"text-xs text-bambu-gray/70",children:r})]})]})})})}function XZe({archives:t,t:e}){return t.length===0?i.jsxs("div",{className:"text-center py-8 text-bambu-gray",children:[i.jsx(fi,{className:"w-12 h-12 mx-auto mb-2 opacity-50"}),i.jsx("p",{children:e("projectDetail.noPrints")})]}):i.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=>i.jsxs(Ks,{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?i.jsx("img",{src:ne.getArchiveThumbnail(n.id),alt:n.print_name||"Print",className:"w-full h-full object-cover"}):i.jsx("div",{className:"w-full h-full flex items-center justify-center text-bambu-gray",children:i.jsx(fi,{className:"w-8 h-8"})}),n.status==="failed"&&i.jsx("div",{className:"absolute inset-0 bg-red-500/30 flex items-center justify-center",children:i.jsx(hi,{className:"w-8 h-8 text-white"})}),n.status==="completed"&&i.jsx("div",{className:"absolute top-1 right-1",children:i.jsx(pr,{className:"w-4 h-4 text-bambu-green"})}),i.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:i.jsx("p",{className:"text-xs text-white truncate",children:n.print_name||"Unknown"})})]},n.id))})}function YZe({priority:t,t:e}){const n={low:{color:"bg-gray-500/20 text-gray-400",label:e("projectDetail.priority.low")},normal:{color:"bg-blue-500/20 text-blue-400",label:e("projectDetail.priority.normal")},high:{color:"bg-orange-500/20 text-orange-400",label:e("projectDetail.priority.high")},urgent:{color:"bg-red-500/20 text-red-400",label:e("projectDetail.priority.urgent")}},{color:r,label:a}=n[t]||n.normal;return i.jsxs("span",{className:`px-2 py-1 rounded text-xs font-medium flex items-center gap-1 ${r}`,children:[t==="urgent"&&i.jsx(Tn,{className:"w-3 h-3"}),a]})}function QZe(t){return t?cb(t,{year:"numeric",month:"short",day:"numeric"}):""}function Mj(t,e){if(!t)return null;const n=di(t);if(!n)return null;const r=new Date,a=Math.ceil((n.getTime()-r.getTime())/(1e3*60*60*24));return a<0?{color:"text-red-400",label:e("projectDetail.dueDate.overdue")}:a===0?{color:"text-orange-400",label:e("projectDetail.dueDate.today")}:a<=3?{color:"text-yellow-400",label:e("projectDetail.dueDate.daysLeft",{count:a})}:{color:"text-bambu-gray",label:e("projectDetail.dueDate.daysLeft",{count:a})}}function ZZe(){const{id:t}=i0(),e=rc(),{t:n}=Ut(),r=tn(),{showToast:a}=cn(),{hasPermission:s}=Or(),[o,l]=w.useState(!1),[c,u]=w.useState(!1),[d,h]=w.useState(""),f=parseInt(t||"0",10),{data:p,isLoading:x,error:v}=Je({queryKey:["project",f],queryFn:()=>ne.getProject(f),enabled:f>0}),{data:g,isLoading:y}=Je({queryKey:["project-archives",f],queryFn:()=>ne.getProjectArchives(f),enabled:f>0}),{data:_,isLoading:N}=Je({queryKey:["project-bom",f],queryFn:()=>ne.getProjectBOM(f),enabled:f>0}),{data:k,isLoading:A}=Je({queryKey:["project-timeline",f],queryFn:()=>ne.getProjectTimeline(f,20),enabled:f>0}),{data:M}=Je({queryKey:["settings"],queryFn:ne.getSettings}),{data:C}=Je({queryKey:["project-folders",f],queryFn:()=>ne.getLibraryFoldersByProject(f),enabled:f>0}),j=rl(M?.currency||"USD"),P=M?.time_format||"system",E=ot({mutationFn:ve=>ne.updateProject(f,ve),onSuccess:()=>{r.invalidateQueries({queryKey:["project",f]}),r.invalidateQueries({queryKey:["projects"]}),l(!1),u(!1),a(n("projectDetail.toast.projectUpdated"),"success")},onError:ve=>{a(ve.message,"error")}}),B=()=>{h(p?.notes||""),u(!0)},O=()=>{E.mutate({notes:d})},U=()=>{u(!1),h("")},[R,V]=w.useState(""),[G,z]=w.useState(1),[K,Y]=w.useState(""),[ae,$]=w.useState(""),[W,ee]=w.useState(""),[J,ye]=w.useState(!1),[me,te]=w.useState(!1),[je,ue]=w.useState(null),[oe,_e]=w.useState(""),[se,Oe]=w.useState(1),[q,X]=w.useState(""),[de,Z]=w.useState(""),[ie,le]=w.useState(""),[Fe,pe]=w.useState({isOpen:!1,title:"",message:"",onConfirm:()=>{}}),Q=ot({mutationFn:ve=>ne.createBOMItem(f,ve),onSuccess:()=>{r.invalidateQueries({queryKey:["project-bom",f]}),r.invalidateQueries({queryKey:["project",f]}),V(""),z(1),Y(""),$(""),ee(""),ye(!1),a(n("projectDetail.toast.partAdded"),"success")},onError:ve=>a(ve.message,"error")}),L=ot({mutationFn:({itemId:ve,data:He})=>ne.updateBOMItem(f,ve,He),onSuccess:()=>{r.invalidateQueries({queryKey:["project-bom",f]}),r.invalidateQueries({queryKey:["project",f]}),ue(null)},onError:ve=>a(ve.message,"error")}),D=ot({mutationFn:ve=>ne.deleteBOMItem(f,ve),onSuccess:()=>{r.invalidateQueries({queryKey:["project-bom",f]}),r.invalidateQueries({queryKey:["project",f]}),a(n("projectDetail.toast.partRemoved"),"success")},onError:ve=>a(ve.message,"error")}),H=ve=>{ve.preventDefault(),R.trim()&&Q.mutate({name:R.trim(),quantity_needed:G,unit_price:K?parseFloat(K):void 0,sourcing_url:ae.trim()||void 0,remarks:W.trim()||void 0})},he=ve=>{const He=ve.is_complete?0:ve.quantity_needed;L.mutate({itemId:ve.id,data:{quantity_acquired:He}})},be=(ve,He)=>{pe({isOpen:!0,title:n("projectDetail.bom.deletePart"),message:n("projectDetail.bom.deleteConfirm",{name:He}),onConfirm:()=>{pe(Pe=>({...Pe,isOpen:!1})),D.mutate(ve)}})},fe=ve=>{ue(ve),_e(ve.name),Oe(ve.quantity_needed),X(ve.unit_price?.toString()||""),Z(ve.sourcing_url||""),le(ve.remarks||"")},ze=ve=>{ve.preventDefault(),!(!je||!oe.trim())&&L.mutate({itemId:je.id,data:{name:oe.trim(),quantity_needed:se,unit_price:q?parseFloat(q):void 0,sourcing_url:de.trim()||void 0,remarks:ie.trim()||void 0}})},Ie=()=>{ue(null)},qe=async()=>{try{const{blob:ve,filename:He}=await ne.exportProjectZip(Number(f)),Pe=URL.createObjectURL(ve),nt=document.createElement("a");nt.href=Pe,nt.download=He||`${p?.name||"project"}_${new Date().toISOString().split("T")[0]}.zip`,nt.click(),URL.revokeObjectURL(Pe),a(n("projectDetail.toast.projectExported"),"success")}catch(ve){a(ve.message,"error")}},tt=ot({mutationFn:()=>ne.createTemplateFromProject(f),onSuccess:()=>{r.invalidateQueries({queryKey:["projects"]}),a(n("projectDetail.toast.templateCreated"),"success")},onError:ve=>a(ve.message,"error")}),Ee=ve=>jf(ve,P,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"});if(x)return i.jsx("div",{className:"flex items-center justify-center py-24",children:i.jsx(it,{className:"w-8 h-8 animate-spin text-bambu-green"})});if(v||!p)return i.jsxs("div",{className:"text-center py-24",children:[i.jsx("p",{className:"text-bambu-gray",children:v?`${n("common.error")}: ${v.message}`:n("projectDetail.notFound")}),i.jsx(Ce,{variant:"secondary",className:"mt-4",onClick:()=>e("/projects"),children:n("projectDetail.backToProjects")})]});const Se=p.stats,Me=Se?.progress_percent??0,xe=Se?.parts_progress_percent??0;return i.jsxs("div",{className:"p-4 md:p-8 space-y-8",children:[i.jsxs("div",{className:"flex items-center gap-2 text-sm text-bambu-gray",children:[i.jsx(Ks,{to:"/projects",className:"hover:text-white transition-colors",children:n("navigation.projects")}),i.jsx(pi,{className:"w-4 h-4"}),i.jsx("span",{className:"text-white",children:p.name})]}),i.jsxs("div",{className:"flex items-start justify-between",children:[i.jsxs("div",{className:"flex items-center gap-4",children:[i.jsx("button",{onClick:()=>e("/projects"),className:"p-2 rounded-lg bg-bambu-card hover:bg-bambu-dark-tertiary transition-colors",children:i.jsx(ZK,{className:"w-5 h-5 text-bambu-gray"})}),i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("div",{className:"w-4 h-4 rounded-full flex-shrink-0",style:{backgroundColor:p.color||"#6b7280"}}),i.jsxs("div",{children:[i.jsx("h1",{className:"text-2xl font-bold text-white",children:p.name}),p.description&&i.jsx("p",{className:"text-bambu-gray mt-1",children:p.description})]})]}),i.jsx(KZe,{status:p.status,t:n})]}),i.jsxs("div",{className:"flex gap-2",children:[i.jsxs(Ce,{variant:"secondary",onClick:qe,disabled:!s("projects:read"),title:s("projects:read")?n("projectDetail.exportProject"):n("projectDetail.noExportPermission"),children:[i.jsx(ua,{className:"w-4 h-4 mr-2"}),n("projectDetail.export")]}),i.jsxs(Ce,{onClick:()=>l(!0),disabled:!s("projects:update"),title:s("projects:update")?void 0:n("projectDetail.noEditPermission"),children:[i.jsx(Tf,{className:"w-4 h-4 mr-2"}),n("common.edit")]})]})]}),(p.target_count||p.target_parts_count)&&i.jsx(vt,{children:i.jsxs(_t,{className:"p-4 space-y-4",children:[p.target_count&&i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center justify-between mb-2",children:[i.jsx("span",{className:"text-sm text-bambu-gray",children:n("projectDetail.progress.platesProgress")}),i.jsxs("span",{className:"text-sm font-medium text-white",children:[Se?.total_archives||0," / ",p.target_count," ",n("projectDetail.progress.printJobs")]})]}),i.jsx("div",{className:"h-3 bg-bambu-dark rounded-full overflow-hidden",children:i.jsx("div",{className:"h-full transition-all duration-500",style:{width:`${Math.min(Me,100)}%`,backgroundColor:Me>=100?"#22c55e":p.color||"#6b7280"}})}),i.jsxs("div",{className:"flex justify-between mt-1",children:[i.jsx("span",{className:"text-xs text-bambu-gray/70",children:n("projectDetail.progress.percentComplete",{percent:Me.toFixed(0)})}),Se?.remaining_prints!=null&&Se.remaining_prints>0&&i.jsx("span",{className:"text-xs text-bambu-gray/70",children:n("projectDetail.progress.remaining",{count:Se.remaining_prints})})]})]}),p.target_parts_count&&i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center justify-between mb-2",children:[i.jsx("span",{className:"text-sm text-bambu-gray",children:n("projectDetail.progress.partsProgress")}),i.jsxs("span",{className:"text-sm font-medium text-white",children:[Se?.completed_prints||0," / ",p.target_parts_count," ",n("projectDetail.progress.parts")]})]}),i.jsx("div",{className:"h-3 bg-bambu-dark rounded-full overflow-hidden",children:i.jsx("div",{className:"h-full transition-all duration-500",style:{width:`${Math.min(xe,100)}%`,backgroundColor:xe>=100?"#22c55e":p.color||"#6b7280"}})}),i.jsxs("div",{className:"flex justify-between mt-1",children:[i.jsx("span",{className:"text-xs text-bambu-gray/70",children:n("projectDetail.progress.percentComplete",{percent:xe.toFixed(0)})}),Se?.remaining_parts!=null&&Se.remaining_parts>0&&i.jsx("span",{className:"text-xs text-bambu-gray/70",children:n("projectDetail.progress.remaining",{count:Se.remaining_parts})})]})]})]})}),Se&&i.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[i.jsx(vt,{children:i.jsx(_t,{className:"p-4",children:i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("div",{className:"p-2 rounded-lg bg-bambu-dark text-bambu-green",children:i.jsx(fi,{className:"w-5 h-5"})}),i.jsxs("div",{children:[i.jsx("p",{className:"text-sm text-bambu-gray",children:n("projectDetail.stats.printJobs")}),i.jsxs("p",{className:"text-xl font-semibold text-white",children:[Se.total_archives," ",i.jsx("span",{className:"text-sm font-normal text-bambu-gray",children:n("projectDetail.stats.total")})]}),Se.failed_prints>0&&i.jsx("p",{className:"text-sm text-status-error",children:n("projectDetail.stats.failed",{count:Se.failed_prints})}),i.jsx("p",{className:"text-sm text-bambu-gray",children:n("projectDetail.stats.partsPrinted",{count:Se.completed_prints})})]})]})})}),i.jsx(eK,{icon:Gn,label:n("projectDetail.stats.printTime"),value:GZe(Se.total_print_time_hours),color:"text-yellow-400"}),i.jsx(eK,{icon:xr,label:n("projectDetail.stats.filamentUsed"),value:WZe(Se.total_filament_grams),color:"text-purple-400"})]}),Se&&(Se.estimated_cost>0||p.budget)&&i.jsx(vt,{children:i.jsxs(_t,{className:"p-4",children:[i.jsx("h2",{className:"text-lg font-semibold text-white mb-3",children:n("projectDetail.cost.title")}),i.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-xs text-bambu-gray uppercase",children:n("projectDetail.cost.filamentCost")}),i.jsxs("p",{className:"text-lg font-semibold text-white",children:[j,Se.estimated_cost.toFixed(2)]})]}),Se.total_energy_kwh>0&&i.jsxs("div",{children:[i.jsx("p",{className:"text-xs text-bambu-gray uppercase",children:n("projectDetail.cost.energy")}),i.jsxs("p",{className:"text-lg font-semibold text-white",children:[Se.total_energy_kwh.toFixed(3)," kWh",Se.total_energy_cost>0&&i.jsxs("span",{className:"text-sm text-bambu-gray ml-1",children:["(",j,Se.total_energy_cost.toFixed(2),")"]})]})]}),p.budget&&i.jsxs(i.Fragment,{children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-xs text-bambu-gray uppercase",children:n("projectDetail.cost.budget")}),i.jsxs("p",{className:"text-lg font-semibold text-white",children:[j,p.budget.toFixed(2)]})]}),i.jsxs("div",{children:[i.jsx("p",{className:"text-xs text-bambu-gray uppercase",children:n("projectDetail.cost.remaining")}),i.jsxs("p",{className:`text-lg font-semibold ${p.budget-Se.estimated_cost>=0?"text-bambu-green":"text-red-400"}`,children:[j,(p.budget-Se.estimated_cost).toFixed(2)]})]})]})]})]})}),p.children&&p.children.length>0&&i.jsx(vt,{children:i.jsxs(_t,{className:"p-4",children:[i.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2 mb-3",children:[i.jsx(hme,{className:"w-5 h-5"}),n("projectDetail.subProjects.title",{count:p.children.length})]}),i.jsx("div",{className:"space-y-2",children:p.children.map(ve=>i.jsxs(Ks,{to:`/projects/${ve.id}`,className:"flex items-center justify-between p-3 bg-bambu-dark rounded-lg hover:bg-bambu-dark-tertiary transition-colors",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("div",{className:"w-3 h-3 rounded-full",style:{backgroundColor:ve.color||"#6b7280"}}),i.jsx("span",{className:"text-white",children:ve.name}),i.jsx("span",{className:`text-xs px-2 py-0.5 rounded ${ve.status==="completed"?"bg-status-ok/20 text-status-ok":ve.status==="archived"?"bg-bambu-gray/20 text-bambu-gray":"bg-blue-500/20 text-blue-400"}`,children:ve.status})]}),ve.progress_percent!==null&&i.jsxs("span",{className:"text-sm text-bambu-gray",children:[ve.progress_percent.toFixed(0),"%"]})]},ve.id))})]})}),p.parent_id&&p.parent_name&&i.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[i.jsx(mi,{className:"w-4 h-4 text-bambu-gray"}),i.jsx("span",{className:"text-bambu-gray",children:n("projectDetail.partOf")}),i.jsx(Ks,{to:`/projects/${p.parent_id}`,className:"text-bambu-green hover:underline",children:p.parent_name})]}),(p.tags||p.due_date||p.priority!=="normal")&&i.jsxs("div",{className:"flex flex-wrap items-center gap-4",children:[p.priority&&p.priority!=="normal"&&i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"text-xs text-bambu-gray uppercase",children:n("projectDetail.priorityLabel")}),i.jsx(YZe,{priority:p.priority,t:n})]}),p.due_date&&i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(na,{className:"w-4 h-4 text-bambu-gray"}),i.jsx("span",{className:"text-sm text-white",children:QZe(p.due_date)}),Mj(p.due_date,n)&&i.jsxs("span",{className:`text-xs ${Mj(p.due_date,n).color}`,children:["(",Mj(p.due_date,n).label,")"]})]}),p.tags&&i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx($h,{className:"w-4 h-4 text-bambu-gray"}),i.jsx("div",{className:"flex flex-wrap gap-1",children:p.tags.split(",").map((ve,He)=>i.jsx("span",{className:"px-2 py-0.5 bg-bambu-dark-tertiary text-bambu-gray text-xs rounded",children:ve.trim()},He))})]})]}),i.jsx(vt,{children:i.jsxs(_t,{className:"p-4",children:[i.jsxs("div",{className:"flex items-center justify-between mb-3",children:[i.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[i.jsx(Ms,{className:"w-5 h-5"}),n("projectDetail.notes.title")]}),c?i.jsxs("div",{className:"flex gap-2",children:[i.jsxs(Ce,{variant:"secondary",size:"sm",onClick:U,disabled:E.isPending,children:[i.jsx(Ft,{className:"w-4 h-4 mr-1"}),n("common.cancel")]}),i.jsxs(Ce,{size:"sm",onClick:O,disabled:E.isPending,children:[E.isPending?i.jsx(it,{className:"w-4 h-4 animate-spin mr-1"}):i.jsx(ps,{className:"w-4 h-4 mr-1"}),n("common.save")]})]}):i.jsxs(Ce,{variant:"secondary",size:"sm",onClick:B,disabled:!s("projects:update"),title:s("projects:update")?void 0:n("projectDetail.notes.noEditPermission"),children:[i.jsx(Tf,{className:"w-4 h-4 mr-1"}),n("common.edit")]})]}),c?i.jsx(KR,{content:d,onChange:h,placeholder:n("projectDetail.notes.placeholder")}):p.notes?i.jsx("div",{className:"prose prose-invert prose-sm max-w-none",dangerouslySetInnerHTML:{__html:p.notes}}):i.jsx("p",{className:"text-bambu-gray/70 text-sm italic",children:n("projectDetail.notes.empty")})]})}),i.jsx(vt,{children:i.jsxs(_t,{className:"p-4",children:[i.jsx("div",{className:"flex items-center justify-between mb-3",children:i.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[i.jsx(Zl,{className:"w-5 h-5"}),n("projectDetail.files.title")]})}),i.jsxs("p",{className:"text-xs text-bambu-gray mb-3",children:[i.jsx(Ks,{to:"/files",className:"text-bambu-green hover:underline",children:n("projectDetail.files.linkFolders")})," ",n("projectDetail.files.forQuickAccess")]}),C&&C.length>0?i.jsx("div",{className:"space-y-2",children:C.map(ve=>i.jsxs(Ks,{to:`/files?folder=${ve.id}`,className:"flex items-center justify-between p-3 bg-bambu-dark rounded-lg hover:bg-bambu-dark-tertiary transition-colors",children:[i.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[i.jsx(Zl,{className:"w-5 h-5 text-bambu-green flex-shrink-0"}),i.jsxs("div",{className:"min-w-0",children:[i.jsx("p",{className:"text-sm text-white truncate",children:ve.name}),i.jsx("p",{className:"text-xs text-bambu-gray",children:n("projectDetail.files.fileCount",{count:ve.file_count})})]})]}),i.jsx(pi,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"})]},ve.id))}):i.jsx("p",{className:"text-bambu-gray/70 text-sm italic",children:n("projectDetail.files.empty")})]})}),i.jsx(vt,{children:i.jsxs(_t,{className:"p-4",children:[i.jsxs("div",{className:"flex items-center justify-between mb-4",children:[i.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[i.jsx(cX,{className:"w-5 h-5"}),n("projectDetail.bom.title"),Se&&Se.bom_total_items>0&&i.jsxs("span",{className:"text-sm font-normal text-bambu-gray",children:["(",n("projectDetail.bom.acquired",{completed:Se.bom_completed_items,total:Se.bom_total_items}),")"]})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[_&&_.some(ve=>ve.is_complete)&&i.jsx("button",{onClick:()=>te(!me),className:`text-xs px-2 py-1 rounded transition-colors ${me?"bg-bambu-green/20 text-bambu-green":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:n(me?"projectDetail.bom.showAll":"projectDetail.bom.hideDone")}),!J&&i.jsxs(Ce,{variant:"secondary",size:"sm",onClick:()=>ye(!0),disabled:!s("projects:update"),title:s("projects:update")?void 0:n("projectDetail.bom.noAddPermission"),children:[i.jsx(Xn,{className:"w-4 h-4 mr-1"}),n("projectDetail.bom.addPart")]})]})]}),J&&i.jsxs("form",{onSubmit:H,className:"bg-bambu-dark rounded-lg p-4 mb-4 space-y-3",children:[i.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[i.jsx("input",{type:"text",value:R,onChange:ve=>V(ve.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}),i.jsxs("div",{className:"flex gap-2",children:[i.jsx("input",{type:"number",value:G,onChange:ve=>z(parseInt(ve.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")}),i.jsx("input",{type:"number",step:"0.01",value:K,onChange:ve=>Y(ve.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:j})})]})]}),i.jsx("input",{type:"url",value:ae,onChange:ve=>$(ve.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")}),i.jsx("input",{type:"text",value:W,onChange:ve=>ee(ve.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")}),i.jsxs("div",{className:"flex justify-end gap-2",children:[i.jsx(Ce,{type:"button",variant:"secondary",size:"sm",onClick:()=>ye(!1),children:n("common.cancel")}),i.jsx(Ce,{type:"submit",size:"sm",disabled:!R.trim()||Q.isPending,children:Q.isPending?i.jsx(it,{className:"w-4 h-4 animate-spin"}):n("projectDetail.bom.addPart")})]})]}),N?i.jsx("div",{className:"flex items-center justify-center py-4",children:i.jsx(it,{className:"w-6 h-6 animate-spin text-bambu-green"})}):_&&_.length>0?i.jsxs("div",{className:"space-y-2",children:[_.filter(ve=>!me||!ve.is_complete).map(ve=>i.jsx("div",{className:`p-3 rounded-lg transition-colors ${ve.is_complete?"bg-status-ok/10":"bg-bambu-dark"}`,children:je?.id===ve.id?i.jsxs("form",{onSubmit:ze,className:"space-y-3",children:[i.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[i.jsx("input",{type:"text",value:oe,onChange:He=>_e(He.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}),i.jsxs("div",{className:"flex gap-2",children:[i.jsx("input",{type:"number",value:se,onChange:He=>Oe(parseInt(He.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")}),i.jsx("input",{type:"number",step:"0.01",value:q,onChange:He=>X(He.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:j})})]})]}),i.jsx("input",{type:"url",value:de,onChange:He=>Z(He.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")}),i.jsx("input",{type:"text",value:ie,onChange:He=>le(He.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")}),i.jsxs("div",{className:"flex justify-end gap-2",children:[i.jsx(Ce,{type:"button",variant:"secondary",size:"sm",onClick:Ie,children:n("common.cancel")}),i.jsx(Ce,{type:"submit",size:"sm",disabled:!oe.trim()||L.isPending,children:L.isPending?i.jsx(it,{className:"w-4 h-4 animate-spin"}):n("common.save")})]})]}):i.jsxs("div",{className:"flex items-start gap-3",children:[i.jsx("button",{onClick:()=>s("projects:update")&&he(ve),disabled:L.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 flex-shrink-0 ${ve.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:ve.is_complete&&i.jsx(pr,{className:"w-3 h-3"})}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsxs("div",{className:"flex items-center justify-between gap-2",children:[i.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[i.jsxs("p",{className:`text-sm font-medium ${ve.is_complete?"text-bambu-gray line-through":"text-white"}`,children:[ve.name,i.jsxs("span",{className:"text-bambu-gray font-normal ml-2",children:["x",ve.quantity_needed]})]}),ve.unit_price!==null&&i.jsxs("span",{className:"text-xs text-bambu-green whitespace-nowrap",children:[j,(ve.unit_price*ve.quantity_needed).toFixed(2)]})]}),i.jsxs("div",{className:"flex items-center gap-1",children:[i.jsx("button",{onClick:()=>s("projects:update")&&fe(ve),disabled:!s("projects:update"),className:`p-1 rounded transition-colors flex-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:i.jsx($a,{className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>s("projects:update")&&be(ve.id,ve.name),disabled:!s("projects:update"),className:`p-1 rounded transition-colors flex-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:i.jsx(Jt,{className:"w-4 h-4"})})]})]}),ve.sourcing_url&&i.jsxs("a",{href:ve.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:He=>He.stopPropagation(),children:[i.jsx(Kr,{className:"w-3 h-3 flex-shrink-0"}),i.jsx("span",{className:"truncate",children:(()=>{try{return new URL(ve.sourcing_url).hostname.replace("www.","")}catch{return ve.sourcing_url}})()})]}),ve.remarks&&i.jsx("p",{className:"mt-1 text-xs text-bambu-gray/80 italic",children:ve.remarks})]})]})},ve.id)),_.some(ve=>ve.unit_price!==null)&&i.jsxs("div",{className:"pt-2 mt-2 border-t border-bambu-dark-tertiary flex justify-between text-sm",children:[i.jsx("span",{className:"text-bambu-gray",children:n("projectDetail.bom.totalCost")}),i.jsxs("span",{className:"text-white font-medium",children:[j,_.reduce((ve,He)=>ve+(He.unit_price||0)*He.quantity_needed,0).toFixed(2)]})]})]}):i.jsx("p",{className:"text-bambu-gray/70 text-sm italic",children:n("projectDetail.bom.empty")})]})}),i.jsx(vt,{children:i.jsxs(_t,{className:"p-4",children:[i.jsx("div",{className:"flex items-center justify-between mb-3",children:i.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[i.jsx(mv,{className:"w-5 h-5"}),n("projectDetail.timeline.title")]})}),A?i.jsx("div",{className:"flex items-center justify-center py-4",children:i.jsx(it,{className:"w-6 h-6 animate-spin text-bambu-green"})}):k&&k.length>0?i.jsx("div",{className:"space-y-3",children:k.slice(0,10).map((ve,He)=>i.jsxs("div",{className:"flex gap-3",children:[i.jsxs("div",{className:`w-8 h-8 rounded-full flex items-center justify-center flex-shrink-0 ${ve.event_type==="print_completed"?"bg-status-ok/20 text-status-ok":ve.event_type==="print_failed"?"bg-status-error/20 text-status-error":ve.event_type==="print_started"?"bg-yellow-500/20 text-yellow-400":"bg-bambu-dark-tertiary text-bambu-gray"}`,children:[ve.event_type==="print_completed"&&i.jsx(pr,{className:"w-4 h-4"}),ve.event_type==="print_failed"&&i.jsx(hi,{className:"w-4 h-4"}),ve.event_type==="print_started"&&i.jsx(xr,{className:"w-4 h-4"}),ve.event_type==="queued"&&i.jsx(n3,{className:"w-4 h-4"}),ve.event_type==="project_created"&&i.jsx(Xn,{className:"w-4 h-4"})]}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsx("p",{className:"text-sm text-white",children:ve.title}),ve.description&&i.jsx("p",{className:"text-xs text-bambu-gray truncate",children:ve.description}),i.jsx("p",{className:"text-xs text-bambu-gray/70",children:Ee(ve.timestamp)})]})]},He))}):i.jsx("p",{className:"text-bambu-gray/70 text-sm italic",children:n("projectDetail.timeline.empty")})]})}),!p.is_template&&i.jsx("div",{className:"flex justify-end",children:i.jsxs(Ce,{variant:"secondary",size:"sm",onClick:()=>tt.mutate(),disabled:tt.isPending||!s("projects:create"),title:s("projects:create")?void 0:n("projectDetail.template.noCreatePermission"),children:[tt.isPending?i.jsx(it,{className:"w-4 h-4 animate-spin mr-2"}):i.jsx(Yl,{className:"w-4 h-4 mr-2"}),n("projectDetail.template.saveAsTemplate")]})}),Se&&(Se.queued_prints>0||Se.in_progress_prints>0)&&i.jsx(vt,{children:i.jsxs(_t,{className:"p-4",children:[i.jsxs("div",{className:"flex items-center justify-between mb-3",children:[i.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[i.jsx(n3,{className:"w-5 h-5"}),n("projectDetail.queue.title")]}),i.jsx(Ks,{to:`/queue?project=${f}`,className:"text-sm text-bambu-green hover:underline",children:n("projectDetail.queue.viewAll")})]}),i.jsxs("div",{className:"flex items-center gap-4 text-sm",children:[Se.in_progress_prints>0&&i.jsx("span",{className:"text-yellow-400",children:n("projectDetail.queue.printing",{count:Se.in_progress_prints})}),Se.queued_prints>0&&i.jsx("span",{className:"text-bambu-gray",children:n("projectDetail.queue.queued",{count:Se.queued_prints})})]})]})}),i.jsxs("div",{children:[i.jsx("div",{className:"flex items-center justify-between mb-4",children:i.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[i.jsx(fi,{className:"w-5 h-5"}),n("projectDetail.prints.title",{count:g?.length||0})]})}),y?i.jsx("div",{className:"flex items-center justify-center py-8",children:i.jsx(it,{className:"w-6 h-6 animate-spin text-bambu-green"})}):i.jsx(XZe,{archives:g||[],t:n})]}),o&&i.jsx(Uie,{t:n,project:{...p,archive_count:Se?.total_archives||0,total_items:Se?.total_items||0,completed_count:Se?.completed_prints||0,failed_count:Se?.failed_prints||0,queue_count:Se?.queued_prints||0,progress_percent:Se?.progress_percent||null,archives:[]},onClose:()=>l(!1),onSave:ve=>E.mutate(ve),isLoading:E.isPending}),Fe.isOpen&&i.jsx(gn,{title:Fe.title,message:Fe.message,confirmText:n("common.delete"),variant:"danger",onConfirm:Fe.onConfirm,onCancel:()=>pe(ve=>({...ve,isOpen:!1}))})]})}function JZe({parentId:t,onClose:e,onSave:n,isLoading:r,t:a}){const[s,o]=w.useState(""),l=c=>{c.preventDefault(),n({name:s.trim(),parent_id:t})};return i.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-sm border border-bambu-dark-tertiary",children:[i.jsx("div",{className:"p-4 border-b border-bambu-dark-tertiary",children:i.jsx("h2",{className:"text-lg font-semibold text-white",children:a("fileManager.newFolder")})}),i.jsxs("form",{onSubmit:l,className:"p-4 space-y-4",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:a("fileManager.folderName")}),i.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:a("fileManager.folderNamePlaceholder"),autoFocus:!0,required:!0})]}),i.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[i.jsx(Ce,{type:"button",variant:"secondary",onClick:e,children:a("common.cancel")}),i.jsx(Ce,{type:"submit",disabled:!s.trim()||r,children:r?i.jsx(it,{className:"w-4 h-4 animate-spin"}):a("common.create")})]})]})]})})}function eJe({type:t,currentName:e,onClose:n,onSave:r,isLoading:a,t:s}){const[o,l]=w.useState(e),c=u=>{u.preventDefault(),o.trim()&&o.trim()!==e&&r(o.trim())};return i.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-sm border border-bambu-dark-tertiary",children:[i.jsx("div",{className:"p-4 border-b border-bambu-dark-tertiary",children:i.jsx("h2",{className:"text-lg font-semibold text-white",children:s(t==="file"?"fileManager.renameFile":"fileManager.renameFolder")})}),i.jsxs("form",{onSubmit:c,className:"p-4 space-y-4",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("common.name")}),i.jsx("input",{type:"text",value:o,onChange:u=>l(u.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",autoFocus:!0,required:!0})]}),i.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[i.jsx(Ce,{type:"button",variant:"secondary",onClick:n,children:s("common.cancel")}),i.jsx(Ce,{type:"submit",disabled:!o.trim()||o.trim()===e||a,children:a?i.jsx(it,{className:"w-4 h-4 animate-spin"}):s("common.rename")})]})]})]})})}function tJe({folders:t,selectedFiles:e,currentFolderId:n,onClose:r,onMove:a,isLoading:s,t:o}){const[l,c]=w.useState(null),u=(h,f=0)=>{const p=[];for(const x of h)p.push({id:x.id,name:x.name,depth:f}),x.children.length>0&&p.push(...u(x.children,f+1));return p},d=[{id:null,name:o("fileManager.rootNoFolder"),depth:0},...u(t)];return i.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-sm border border-bambu-dark-tertiary",children:[i.jsx("div",{className:"p-4 border-b border-bambu-dark-tertiary",children:i.jsx("h2",{className:"text-lg font-semibold text-white",children:o("fileManager.moveFiles",{count:e.length})})}),i.jsxs("div",{className:"p-4 space-y-4",children:[i.jsx("div",{className:"max-h-64 overflow-y-auto space-y-1",children:d.map(h=>i.jsxs("button",{onClick:()=>c(h.id),disabled:h.id===n,className:`w-full text-left px-3 py-2 rounded transition-colors flex items-center gap-2 ${l===h.id?"bg-bambu-green/20 text-bambu-green":h.id===n?"opacity-50 cursor-not-allowed text-bambu-gray":"hover:bg-bambu-dark text-white"}`,style:{paddingLeft:`${12+h.depth*16}px`},children:[i.jsx(Zl,{className:"w-4 h-4"}),h.name,h.id===n&&i.jsxs("span",{className:"text-xs text-bambu-gray ml-auto",children:["(",o("fileManager.current"),")"]})]},h.id??"root"))}),i.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[i.jsx(Ce,{type:"button",variant:"secondary",onClick:r,children:o("common.cancel")}),i.jsx(Ce,{onClick:()=>a(l),disabled:s,children:s?i.jsx(it,{className:"w-4 h-4 animate-spin"}):o("common.move")})]})]})]})})}function nJe({folder:t,onClose:e,onLink:n,isLoading:r,t:a}){const[s,o]=w.useState("project"),[l,c]=w.useState(t.project_id||t.archive_id||null);w.useState(()=>{t.archive_id&&o("archive")});const{data:u}=Je({queryKey:["projects"],queryFn:()=>ne.getProjects()}),{data:d}=Je({queryKey:["archives-for-link"],queryFn:()=>ne.getArchives(void 0,void 0,100)}),h=()=>{n(s==="project"?{project_id:l,archive_id:0}:{project_id:0,archive_id:l})},f=()=>{n({project_id:0,archive_id:0})},p=t.project_id||t.archive_id;return i.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-md border border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"p-4 border-b border-bambu-dark-tertiary flex items-center justify-between",children:[i.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[i.jsx(Eh,{className:"w-5 h-5 text-bambu-green"}),a("fileManager.linkFolder")]}),i.jsx("button",{onClick:e,className:"p-1 hover:bg-bambu-dark rounded",children:i.jsx(Ft,{className:"w-5 h-5 text-bambu-gray"})})]}),i.jsxs("div",{className:"p-4 space-y-4",children:[i.jsx("p",{className:"text-sm text-bambu-gray",children:a("fileManager.linkFolderDescription",{name:t.name})}),i.jsxs("div",{className:"flex gap-2",children:[i.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:[i.jsx(JK,{className:"w-4 h-4"}),a("fileManager.project")]}),i.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:[i.jsx(js,{className:"w-4 h-4"}),a("fileManager.archive")]})]}),i.jsx("div",{className:"max-h-64 overflow-y-auto space-y-1 bg-bambu-dark rounded-lg p-2",children:s==="project"?u&&u.length>0?u.map(x=>i.jsxs("button",{onClick:()=>c(x.id),className:`w-full text-left px-3 py-2 rounded transition-colors flex items-center gap-2 ${l===x.id?"bg-bambu-green/20 text-bambu-green":"hover:bg-bambu-dark-tertiary text-white"}`,children:[i.jsx("div",{className:"w-3 h-3 rounded-full flex-shrink-0",style:{backgroundColor:x.color||"#00ae42"}}),i.jsx("span",{className:"truncate",children:x.name})]},x.id)):i.jsx("p",{className:"text-sm text-bambu-gray text-center py-4",children:a("fileManager.noProjectsFound")}):d&&d.length>0?d.map(x=>i.jsxs("button",{onClick:()=>c(x.id),className:`w-full text-left px-3 py-2 rounded transition-colors flex items-center gap-2 ${l===x.id?"bg-bambu-green/20 text-bambu-green":"hover:bg-bambu-dark-tertiary text-white"}`,children:[i.jsx(df,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"}),i.jsx("span",{className:"truncate",children:x.print_name||x.filename})]},x.id)):i.jsx("p",{className:"text-sm text-bambu-gray text-center py-4",children:a("fileManager.noArchivesFound")})})]}),i.jsxs("div",{className:"p-4 border-t border-bambu-dark-tertiary flex justify-between",children:[p&&i.jsxs(Ce,{variant:"danger",onClick:f,disabled:r,children:[i.jsx(YC,{className:"w-4 h-4 mr-2"}),a("fileManager.unlink")]}),i.jsxs("div",{className:`flex gap-2 ${p?"":"ml-auto"}`,children:[i.jsx(Ce,{variant:"secondary",onClick:e,children:a("common.cancel")}),i.jsx(Ce,{onClick:h,disabled:!l||r,children:r?i.jsx(it,{className:"w-4 h-4 animate-spin"}):a("fileManager.link")})]})]})]})})}function rJe({folderId:t,onClose:e,onUploadComplete:n,t:r}){const[a,s]=w.useState([]),[o,l]=w.useState(!1),[c,u]=w.useState(!1),[d,h]=w.useState(!0),[f,p]=w.useState(!1),[x,v]=w.useState(!0),g=w.useRef(null),y=V=>{V.preventDefault(),l(!0)},_=V=>{V.preventDefault(),l(!1)},N=V=>{V.preventDefault(),l(!1);const G=Array.from(V.dataTransfer.files);A(G)},k=V=>{V.target.files&&A(Array.from(V.target.files))},A=V=>{const G=V.map(z=>({file:z,status:"pending",isZip:z.name.toLowerCase().endsWith(".zip"),is3mf:z.name.toLowerCase().endsWith(".3mf")}));s(z=>[...z,...G])},M=V=>{s(G=>G.filter((z,K)=>K!==V))},C=a.some(V=>V.isZip&&V.status==="pending"),j=a.some(V=>V.file.name.toLowerCase().endsWith(".stl")&&V.status==="pending"),P=a.some(V=>V.is3mf&&V.status==="pending"),E=async()=>{if(a.length!==0){u(!0);for(let V=0;VG.map((z,K)=>K===V?{...z,status:"uploading"}:z));try{if(a[V].isZip){const G=await ne.extractZipFile(a[V].file,t,d,f,x);s(z=>z.map((K,Y)=>Y===V?{...K,status:G.errors.length>0&&G.extracted===0?"error":"success",extractedCount:G.extracted,error:G.errors.length>0?`${G.errors.length} files failed`:void 0}:K))}else await ne.uploadLibraryFile(a[V].file,t,x),s(G=>G.map((z,K)=>K===V?{...z,status:"success"}:z))}catch(G){s(z=>z.map((K,Y)=>Y===V?{...K,status:"error",error:G instanceof Error?G.message:"Upload failed"}:K))}}u(!1),n(),e()}},B=a.filter(V=>V.status==="pending").length,O=a.filter(V=>V.status==="success").length,U=a.filter(V=>V.status==="error").length,R=a.length>0&&B===0&&!c;return i.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-lg border border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"p-4 border-b border-bambu-dark-tertiary flex items-center justify-between",children:[i.jsx("h2",{className:"text-lg font-semibold text-white",children:r("fileManager.uploadFiles")}),i.jsx("button",{onClick:e,className:"p-1 hover:bg-bambu-dark rounded",children:i.jsx(Ft,{className:"w-5 h-5 text-bambu-gray"})})]}),i.jsxs("div",{className:"p-4 space-y-4",children:[i.jsxs("div",{onDragOver:y,onDragLeave:_,onDrop:N,onClick:()=>g.current?.click(),className:`border-2 border-dashed rounded-lg p-8 text-center cursor-pointer transition-colors ${o?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary hover:border-bambu-green/50"}`,children:[i.jsx(Ra,{className:`w-10 h-10 mx-auto mb-3 ${o?"text-bambu-green":"text-bambu-gray"}`}),i.jsx("p",{className:"text-white font-medium",children:r(o?"fileManager.dropFilesHere":"fileManager.dragDropFiles")}),i.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:r("fileManager.orClickToBrowse")}),i.jsx("p",{className:"text-xs text-bambu-gray/70 mt-2",children:r("fileManager.allFileTypesSupported")})]}),i.jsx("input",{ref:g,type:"file",multiple:!0,className:"hidden",onChange:k}),C&&i.jsx("div",{className:"p-3 bg-blue-500/10 border border-blue-500/30 rounded-lg",children:i.jsxs("div",{className:"flex items-start gap-3",children:[i.jsx(js,{className:"w-5 h-5 text-blue-400 mt-0.5 flex-shrink-0"}),i.jsxs("div",{className:"flex-1",children:[i.jsx("p",{className:"text-sm text-blue-300 font-medium",children:r("fileManager.zipFilesDetected")}),i.jsx("p",{className:"text-xs text-blue-300/70 mt-1",children:r("fileManager.zipExtractOptions")}),i.jsxs("label",{className:"flex items-center gap-2 mt-2 cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:d,onChange:V=>h(V.target.checked),className:"w-4 h-4 rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),i.jsx("span",{className:"text-sm text-white",children:r("fileManager.preserveZipStructure")})]}),i.jsxs("label",{className:"flex items-center gap-2 mt-2 cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:f,onChange:V=>p(V.target.checked),className:"w-4 h-4 rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),i.jsx("span",{className:"text-sm text-white",children:r("fileManager.createFolderFromZip")})]})]})]})}),P&&i.jsx("div",{className:"p-3 bg-purple-500/10 border border-purple-500/30 rounded-lg",children:i.jsxs("div",{className:"flex items-start gap-3",children:[i.jsx(xr,{className:"w-5 h-5 text-purple-400 mt-0.5 flex-shrink-0"}),i.jsxs("div",{className:"flex-1",children:[i.jsx("p",{className:"text-sm text-purple-300 font-medium",children:r("fileManager.threemfDetected")}),i.jsx("p",{className:"text-xs text-purple-300/70 mt-1",children:r("fileManager.threemfExtractionInfo")})]})]})}),(j||C)&&i.jsx("div",{className:"p-3 bg-bambu-green/10 border border-bambu-green/30 rounded-lg",children:i.jsxs("div",{className:"flex items-start gap-3",children:[i.jsx(Ju,{className:"w-5 h-5 text-bambu-green mt-0.5 flex-shrink-0"}),i.jsxs("div",{className:"flex-1",children:[i.jsx("p",{className:"text-sm text-bambu-green font-medium",children:r("fileManager.stlThumbnailGeneration")}),i.jsx("p",{className:"text-xs text-bambu-green/70 mt-1",children:r(C&&!j?"fileManager.zipMayContainStl":"fileManager.thumbnailsCanBeGenerated")}),i.jsxs("label",{className:"flex items-center gap-2 mt-2 cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:x,onChange:V=>v(V.target.checked),className:"w-4 h-4 rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),i.jsx("span",{className:"text-sm text-white",children:r("fileManager.generateThumbnailsForStl")})]})]})]})}),a.length>0&&i.jsx("div",{className:"max-h-48 overflow-y-auto space-y-2",children:a.map((V,G)=>i.jsxs("div",{className:"flex items-center gap-3 p-2 bg-bambu-dark rounded-lg",children:[V.isZip?i.jsx(js,{className:"w-4 h-4 text-blue-400 flex-shrink-0"}):i.jsx(zC,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsx("p",{className:"text-sm text-white truncate",children:V.file.name}),i.jsxs("p",{className:"text-xs text-bambu-gray",children:[(V.file.size/1024/1024).toFixed(2)," MB",V.isZip&&V.status==="pending"&&i.jsxs("span",{className:"text-blue-400 ml-2",children:["• ",r("fileManager.willBeExtracted")]}),V.extractedCount!==void 0&&i.jsxs("span",{className:"text-green-400 ml-2",children:["• ",r("fileManager.filesExtracted",{count:V.extractedCount})]})]})]}),V.status==="pending"&&i.jsx("button",{onClick:()=>M(G),className:"p-1 hover:bg-bambu-dark-tertiary rounded",children:i.jsx(Ft,{className:"w-4 h-4 text-bambu-gray"})}),V.status==="uploading"&&i.jsx(it,{className:"w-4 h-4 text-bambu-green animate-spin"}),V.status==="success"&&i.jsx(pr,{className:"w-4 h-4 text-green-500"}),V.status==="error"&&i.jsx("span",{title:V.error,children:i.jsx(hi,{className:"w-4 h-4 text-red-500"})})]},G))}),R&&i.jsx("div",{className:"p-3 bg-bambu-dark rounded-lg",children:i.jsxs("p",{className:"text-sm text-white",children:[r("fileManager.uploadComplete",{succeeded:O}),U>0&&i.jsxs("span",{className:"text-red-400",children:[", ",r("fileManager.uploadFailed",{count:U})]})]})})]}),i.jsxs("div",{className:"p-4 border-t border-bambu-dark-tertiary flex justify-end gap-2",children:[i.jsx(Ce,{variant:"secondary",onClick:e,children:r(R?"common.close":"common.cancel")}),!R&&i.jsx(Ce,{onClick:E,disabled:B===0||c,children:c?i.jsxs(i.Fragment,{children:[i.jsx(it,{className:"w-4 h-4 mr-2 animate-spin"}),r("fileManager.uploading")]}):i.jsxs(i.Fragment,{children:[i.jsx(Ra,{className:"w-4 h-4 mr-2"}),r("common.upload")," ",B>0?`(${B})`:""]})})]})]})})}function Bie({folder:t,selectedFolderId:e,onSelect:n,onDelete:r,onLink:a,onRename:s,depth:o=0,wrapNames:l=!1,hasPermission:c,t:u}){const[d,h]=w.useState(!0),[f,p]=w.useState(!1),x=t.children.length>0,v=t.project_id||t.archive_id;return i.jsxs("div",{children:[i.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:[x?i.jsx("button",{onClick:g=>{g.stopPropagation(),h(!d)},className:"p-0.5 hover:bg-bambu-dark-tertiary rounded",children:i.jsx(pi,{className:`w-3.5 h-3.5 transition-transform ${d?"rotate-90":""}`})}):i.jsx("div",{className:"w-4.5"}),i.jsx(Zl,{className:"w-4 h-4 text-bambu-green flex-shrink-0"}),i.jsx("span",{className:`text-sm flex-1 min-w-0 ${l?"break-all":"truncate"}`,title:t.name,children:t.name}),v&&i.jsxs("button",{onClick:g=>{g.stopPropagation(),a(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:[i.jsx(Eh,{className:"w-3 h-3"}),t.project_name?i.jsx(JK,{className:"w-3 h-3"}):i.jsx(js,{className:"w-3 h-3"})]}),t.file_count>0&&i.jsx("span",{className:"flex-shrink-0 text-xs text-bambu-gray",children:t.file_count}),!v&&i.jsx("button",{onClick:g=>{g.stopPropagation(),a(t)},className:"flex-shrink-0 p-1 rounded hover:bg-bambu-dark-tertiary",title:u("fileManager.linkToProjectOrArchive"),children:i.jsx(Eh,{className:"w-3.5 h-3.5 text-bambu-gray hover:text-bambu-green"})}),i.jsx("div",{className:`flex-shrink-0 flex items-center gap-0.5 transition-opacity ${l?"":"opacity-0 group-hover:opacity-100"}`,onClick:g=>g.stopPropagation(),children:i.jsxs("div",{className:"relative",children:[i.jsx("button",{onClick:()=>p(!f),className:"p-1 rounded hover:bg-bambu-dark-tertiary",children:i.jsx(Ah,{className:"w-3.5 h-3.5 text-bambu-gray"})}),f&&i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>p(!1)}),i.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:[i.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${c("library:update_all")?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{c("library:update_all")&&(s(t),p(!1))},disabled:!c("library:update_all"),title:c("library:update_all")?void 0:u("fileManager.noPermissionRenameFolder"),children:[i.jsx($a,{className:"w-3.5 h-3.5"}),u("common.rename")]}),i.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${c("library:update_all")?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{c("library:update_all")&&(a(t),p(!1))},disabled:!c("library:update_all"),title:c("library:update_all")?void 0:u("fileManager.noPermissionLinkFolder"),children:[i.jsx(Eh,{className:"w-3.5 h-3.5"}),u(v?"fileManager.changeLink":"fileManager.linkTo")]}),i.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${c("library:delete_all")?"text-red-400 hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{c("library:delete_all")&&(r(t.id),p(!1))},disabled:!c("library:delete_all"),title:c("library:delete_all")?void 0:u("fileManager.noPermissionDeleteFolder"),children:[i.jsx(Jt,{className:"w-3.5 h-3.5"}),u("common.delete")]})]})]})]})})]}),x&&d&&i.jsx("div",{children:t.children.map(g=>i.jsx(Bie,{folder:g,selectedFolderId:e,onSelect:n,onDelete:r,onLink:a,onRename:s,depth:o+1,wrapNames:l,hasPermission:c,t:u},g.id))})]})}function tF(t){const e=t.toLowerCase();return e.endsWith(".gcode")||e.includes(".gcode.")}function aJe({file:t,isSelected:e,isMobile:n,onSelect:r,onDelete:a,onDownload:s,onAddToQueue:o,onPrint:l,onPreview3d:c,onRename:u,onGenerateThumbnail:d,thumbnailVersion:h,hasPermission:f,canModify:p,authEnabled:x,t:v}){const[g,y]=w.useState(!1);return i.jsxs("div",{className:`group relative bg-bambu-dark-secondary rounded-lg border transition-all cursor-pointer overflow-hidden ${e?"border-bambu-green ring-1 ring-bambu-green":"border-bambu-dark-tertiary hover:border-bambu-green/50"}`,onClick:()=>r(t.id),children:[i.jsxs("div",{className:"aspect-square bg-bambu-dark flex items-center justify-center overflow-hidden",children:[t.thumbnail_path?i.jsx("img",{src:`${ne.getLibraryFileThumbnailUrl(t.id)}${h?`?v=${h}`:""}`,alt:t.filename,className:"w-full h-full object-cover"}):i.jsx(df,{className:"w-12 h-12 text-bambu-gray/30"}),i.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()})]}),i.jsxs("div",{className:"p-3",children:[i.jsx("h3",{className:"text-sm font-medium text-white truncate",title:t.print_name||t.filename,children:t.print_name||t.filename}),i.jsxs("div",{className:"flex items-center gap-3 mt-1 text-xs text-bambu-gray",children:[i.jsx("span",{children:ul(t.file_size)}),t.print_time_seconds&&i.jsxs("span",{className:"flex items-center gap-1",children:[i.jsx(Gn,{className:"w-3 h-3"}),Qs(t.print_time_seconds)]})]}),t.sliced_for_model&&i.jsxs("div",{className:"mt-1 text-xs text-bambu-gray flex items-center gap-1",children:[i.jsx(xr,{className:"w-3 h-3"}),t.sliced_for_model]}),t.print_count>0&&i.jsx("div",{className:"mt-1 text-xs text-bambu-green",children:v("fileManager.printedCount",{count:t.print_count})}),x&&t.created_by_username&&i.jsxs("div",{className:"mt-1 text-xs text-bambu-gray flex items-center gap-1",children:[i.jsx(td,{className:"w-3 h-3"}),t.created_by_username]})]}),i.jsxs("div",{className:`absolute bottom-2 right-2 transition-opacity ${n?"opacity-100":"opacity-0 group-hover:opacity-100"}`,onClick:_=>_.stopPropagation(),children:[i.jsx("button",{onClick:()=>y(!g),className:"p-1.5 rounded bg-bambu-dark-secondary/90 hover:bg-bambu-dark-tertiary",children:i.jsx(Ah,{className:"w-4 h-4 text-bambu-gray"})}),g&&i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>y(!1)}),i.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&&tF(t.filename)&&i.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${f("printers:control")?"text-bambu-green hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{f("printers:control")&&(l(t),y(!1))},disabled:!f("printers:control"),title:f("printers:control")?void 0:v("fileManager.noPermissionPrint"),children:[i.jsx(xr,{className:"w-3.5 h-3.5"}),v("common.print")]}),o&&tF(t.filename)&&i.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${f("queue:create")?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{f("queue:create")&&(o(t.id),y(!1))},disabled:!f("queue:create"),title:f("queue:create")?void 0:v("fileManager.noPermissionAddToQueue"),children:[i.jsx(Gn,{className:"w-3.5 h-3.5"}),v("fileManager.schedulePrint")]}),c&&(t.file_type==="3mf"||t.file_type==="gcode"||t.file_type==="stl")&&i.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${f("library:read")?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{f("library:read")&&(c(t),y(!1))},disabled:!f("library:read"),title:f("library:read")?void 0:"You do not have permission to preview files",children:[i.jsx(Ja,{className:"w-3.5 h-3.5"}),"3D Preview"]}),i.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${f("library:read")?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{f("library:read")&&(s(t.id),y(!1))},disabled:!f("library:read"),title:f("library:read")?void 0:v("fileManager.noPermissionDownload"),children:[i.jsx(ua,{className:"w-3.5 h-3.5"}),v("common.download")]}),u&&i.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${p("library","update",t.created_by_id)?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{p("library","update",t.created_by_id)&&(u(t),y(!1))},disabled:!p("library","update",t.created_by_id),title:p("library","update",t.created_by_id)?void 0:v("fileManager.noPermissionRenameFile"),children:[i.jsx($a,{className:"w-3.5 h-3.5"}),v("common.rename")]}),d&&t.file_type==="stl"&&i.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${p("library","update",t.created_by_id)?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{p("library","update",t.created_by_id)&&(d(t),y(!1))},disabled:!p("library","update",t.created_by_id),title:p("library","update",t.created_by_id)?void 0:v("fileManager.noPermissionGenerateThumbnail"),children:[i.jsx(Ju,{className:"w-3.5 h-3.5"}),v("fileManager.generateThumbnail")]}),i.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${p("library","delete",t.created_by_id)?"text-red-400 hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{p("library","delete",t.created_by_id)&&(a(t.id),y(!1))},disabled:!p("library","delete",t.created_by_id),title:p("library","delete",t.created_by_id)?void 0:v("fileManager.noPermissionDeleteFile"),children:[i.jsx(Jt,{className:"w-3.5 h-3.5"}),v("common.delete")]})]})]})]}),i.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&&i.jsx("div",{className:"w-2 h-2 bg-white rounded-sm"})})]})}function iJe(){const{t}=Ut(),e=tn(),{showToast:n}=cn(),{hasPermission:r,hasAnyPermission:a,canModify:s,authEnabled:o}=Or(),[l]=dF(),c=l.get("folder"),u=c?parseInt(c,10):null,[d,h]=w.useState(u),[f,p]=w.useState([]),[x,v]=w.useState(!1),[g,y]=w.useState(!1),[_,N]=w.useState(!1),[k,A]=w.useState(null),[M,C]=w.useState(null),[j,P]=w.useState(null),[E,B]=w.useState(null),[O,U]=w.useState(null),[R,V]=w.useState(null),[G,z]=w.useState({}),[K,Y]=w.useState(null),[ae,$]=w.useState(()=>localStorage.getItem("library-view-mode")||"grid"),[W,ee]=w.useState(()=>localStorage.getItem("library-wrap-folders")==="true"),[J,ye]=w.useState(()=>{const Ue=localStorage.getItem("library-sidebar-width");return Ue?parseInt(Ue,10):256}),[me,te]=w.useState(!1),je=w.useRef(null);w.useEffect(()=>{if(!me)return;document.body.style.userSelect="none",document.body.style.cursor="col-resize";const Ue=wt=>{if(!je.current)return;const qt=je.current.parentElement?.getBoundingClientRect();if(!qt)return;const Cn=wt.clientX-qt.left,yr=Math.min(500,Math.max(200,Cn));ye(yr)},bt=()=>{te(!1),document.body.style.userSelect="",document.body.style.cursor="",localStorage.setItem("library-sidebar-width",String(J))};return document.addEventListener("mousemove",Ue),document.addEventListener("mouseup",bt),()=>{document.removeEventListener("mousemove",Ue),document.removeEventListener("mouseup",bt),document.body.style.userSelect="",document.body.style.cursor=""}},[me,J]);const[ue,oe]=w.useState(""),[_e,se]=w.useState("all"),[Oe,q]=w.useState(""),[X,de]=w.useState(()=>localStorage.getItem("library-sort-field")||"name"),[Z,ie]=w.useState(()=>localStorage.getItem("library-sort-direction")||"asc"),le=sne();w.useEffect(()=>{const Ue=l.get("folder");if(Ue){const bt=parseInt(Ue,10);h(bt)}},[l]);const{data:Fe}=Je({queryKey:["settings"],queryFn:()=>ne.getSettings()}),{data:pe,isLoading:Q}=Je({queryKey:["library-folders"],queryFn:()=>ne.getLibraryFolders()}),{data:L,isLoading:D}=Je({queryKey:["library-files",d],queryFn:()=>ne.getLibraryFiles(d,d===null)}),{data:H}=Je({queryKey:["library-stats"],queryFn:()=>ne.getLibraryStats()}),{data:he}=Je({queryKey:["users"],queryFn:()=>ne.getUsers()}),be=w.useMemo(()=>{if(!L)return[];const Ue=new Set(L.map(bt=>bt.file_type));return Array.from(Ue).sort()},[L]),fe=w.useMemo(()=>{if(!L)return[];let Ue=[...L];if(ue.trim()){const bt=ue.toLowerCase();Ue=Ue.filter(wt=>wt.filename.toLowerCase().includes(bt)||wt.print_name&&wt.print_name.toLowerCase().includes(bt))}if(_e!=="all"&&(Ue=Ue.filter(bt=>bt.file_type===_e)),Oe.trim()){const bt=Oe.toLowerCase();Ue=Ue.filter(wt=>wt.created_by_username&&wt.created_by_username.toLowerCase().includes(bt))}return Ue.sort((bt,wt)=>{let qt=0;switch(X){case"name":qt=(bt.print_name||bt.filename).localeCompare(wt.print_name||wt.filename);break;case"date":qt=new Date(bt.created_at).getTime()-new Date(wt.created_at).getTime();break;case"size":qt=bt.file_size-wt.file_size;break;case"type":qt=bt.file_type.localeCompare(wt.file_type);break;case"prints":qt=bt.print_count-wt.print_count;break}return Z==="asc"?qt:-qt}),Ue},[L,ue,_e,Oe,X,Z]),ze=w.useMemo(()=>{if(!H||!Fe)return!1;const Ue=(Fe.library_disk_warning_gb||5)*1024*1024*1024;return H.disk_free_bytesne.createLibraryFolder(Ue),onSuccess:()=>{e.invalidateQueries({queryKey:["library-folders"]}),v(!1),n(t("fileManager.toast.folderCreated"),"success")},onError:Ue=>n(Ue.message,"error")}),qe=ot({mutationFn:Ue=>ne.deleteLibraryFolder(Ue),onSuccess:()=>{e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-stats"]}),d===M?.id&&h(null),C(null),n(t("fileManager.toast.folderDeleted"),"success")},onError:Ue=>{C(null),n(Ue.message,"error")}}),tt=ot({mutationFn:Ue=>ne.deleteLibraryFile(Ue),onSuccess:()=>{e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-stats"]}),p(Ue=>Ue.filter(bt=>bt!==M?.id)),C(null),n(t("fileManager.toast.fileDeleted"),"success")},onError:Ue=>{C(null),n(Ue.message,"error")}}),Ee=ot({mutationFn:Ue=>ne.bulkDeleteLibrary(Ue,[]),onSuccess:(Ue,bt)=>{e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-stats"]}),n(t("fileManager.toast.filesDeleted",{count:bt.length}),"success"),p([]),C(null)},onError:Ue=>{C(null),n(Ue.message,"error")}}),Se=ot({mutationFn:({fileIds:Ue,folderId:bt})=>ne.moveLibraryFiles(Ue,bt),onSuccess:()=>{e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-folders"]}),p([]),y(!1),n(t("fileManager.toast.filesMoved"),"success")},onError:Ue=>n(Ue.message,"error")}),Me=ot({mutationFn:({id:Ue,data:bt})=>ne.updateLibraryFolder(Ue,bt),onSuccess:(Ue,bt)=>{e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["project-folders"]}),e.invalidateQueries({queryKey:["archive-folders"]}),A(null);const wt=bt.data.project_id===0&&bt.data.archive_id===0;n(t(wt?"fileManager.toast.folderUnlinked":"fileManager.toast.folderLinked"),"success")},onError:Ue=>n(Ue.message,"error")}),xe=ot({mutationFn:({id:Ue,filename:bt})=>ne.updateLibraryFile(Ue,{filename:bt}),onSuccess:()=>{e.invalidateQueries({queryKey:["library-files"]}),V(null),n(t("fileManager.toast.fileRenamed"),"success")},onError:Ue=>{V(null),n(Ue.message,"error")}}),ve=ot({mutationFn:({id:Ue,name:bt})=>ne.updateLibraryFolder(Ue,{name:bt}),onSuccess:()=>{e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-files"]}),V(null),n(t("fileManager.toast.folderRenamed"),"success")},onError:Ue=>{V(null),n(Ue.message,"error")}}),He=ot({mutationFn:()=>ne.batchGenerateStlThumbnails({all_missing:!0}),onSuccess:Ue=>{if(e.invalidateQueries({queryKey:["library-files"]}),Ue.succeeded>0){const bt=Date.now(),wt={};Ue.results.forEach(qt=>{qt.success&&(wt[qt.file_id]=bt)}),z(qt=>({...qt,...wt}))}Ue.succeeded>0&&Ue.failed===0?n(t("fileManager.toast.thumbnailsGenerated",{count:Ue.succeeded}),"success"):Ue.succeeded>0&&Ue.failed>0?n(t("fileManager.toast.thumbnailsGeneratedPartial",{succeeded:Ue.succeeded,failed:Ue.failed}),"success"):Ue.processed===0?n(t("fileManager.toast.noStlMissingThumbnails"),"info"):n(t("fileManager.toast.failedToGenerateThumbnails",{error:Ue.results[0]?.error||"Unknown error"}),"error")},onError:Ue=>n(Ue.message,"error")}),Pe=ot({mutationFn:Ue=>ne.batchGenerateStlThumbnails({file_ids:[Ue]}),onSuccess:Ue=>{if(e.invalidateQueries({queryKey:["library-files"]}),Ue.succeeded>0){const bt=Ue.results[0]?.file_id;bt&&z(wt=>({...wt,[bt]:Date.now()})),n(t("fileManager.toast.thumbnailGenerated"),"success")}else n(t("fileManager.toast.failedToGenerateThumbnail",{error:Ue.results[0]?.error||"Unknown error"}),"error")},onError:Ue=>n(Ue.message,"error")}),nt=w.useCallback(Ue=>{const bt=Ue.toLowerCase();return bt.endsWith(".gcode")||bt.includes(".gcode.")},[]),Te=w.useMemo(()=>L?L.filter(Ue=>f.includes(Ue.id)&&nt(Ue.filename)):[],[L,f,nt]),Ge=w.useCallback(Ue=>{p(bt=>bt.includes(Ue)?bt.filter(wt=>wt!==Ue):[...bt,Ue])},[]),Re=w.useCallback(()=>{fe.length>0&&p(fe.map(Ue=>Ue.id))},[fe]),Le=w.useCallback(()=>{p([])},[]),Ke=()=>{e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-stats"]})},ft=Ue=>{ne.downloadLibraryFile(Ue).catch(bt=>{console.error("Library file download failed:",bt)})},kt=()=>{M&&(M.type==="file"?tt.mutate(M.id):M.type==="folder"?qe.mutate(M.id):M.type==="bulk"&&Ee.mutate(f))},Lt=qe.isPending||tt.isPending||Ee.isPending,Kt=Ue=>{$(Ue),localStorage.setItem("library-view-mode",Ue)},Mt=Q||D;return i.jsxs("div",{className:"p-4 md:p-8 min-h-[calc(100vh-64px)] lg:h-[calc(100vh-64px)] flex flex-col",children:[i.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4 mb-6",children:[i.jsxs("div",{children:[i.jsxs("h1",{className:"text-2xl font-bold text-white flex items-center gap-3",children:[i.jsx("div",{className:"p-2.5 bg-bambu-green/10 rounded-xl",children:i.jsx(Zl,{className:"w-6 h-6 text-bambu-green"})}),t("fileManager.title")]}),i.jsx("p",{className:"text-sm text-bambu-gray mt-2 ml-14",children:t("fileManager.subtitle")})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsxs("div",{className:"flex items-center bg-bambu-dark rounded-lg p-1",children:[i.jsx("button",{onClick:()=>Kt("grid"),className:`p-1.5 rounded transition-colors ${ae==="grid"?"bg-bambu-dark-secondary text-white":"text-bambu-gray hover:text-white"}`,title:t("fileManager.gridView"),children:i.jsx(c0,{className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>Kt("list"),className:`p-1.5 rounded transition-colors ${ae==="list"?"bg-bambu-dark-secondary text-white":"text-bambu-gray hover:text-white"}`,title:t("fileManager.listView"),children:i.jsx(HC,{className:"w-4 h-4"})})]}),i.jsxs(Ce,{variant:"secondary",onClick:()=>He.mutate(),disabled:He.isPending||!a("library:update_own","library:update_all"),title:a("library:update_own","library:update_all")?t("fileManager.generateThumbnailsForMissing"):t("fileManager.noPermissionGenerateThumbnail"),children:[He.isPending?i.jsx(it,{className:"w-4 h-4 mr-2 animate-spin"}):i.jsx(Ju,{className:"w-4 h-4 mr-2"}),t("fileManager.generateThumbnails")]}),i.jsxs(Ce,{variant:"secondary",onClick:()=>v(!0),disabled:!r("library:upload"),title:r("library:upload")?void 0:t("fileManager.noPermissionCreateFolder"),children:[i.jsx(ume,{className:"w-4 h-4 mr-2"}),t("fileManager.newFolder")]}),i.jsxs(Ce,{onClick:()=>N(!0),disabled:!r("library:upload"),title:r("library:upload")?void 0:t("fileManager.noPermissionUpload"),children:[i.jsx(Ra,{className:"w-4 h-4 mr-2"}),t("common.upload")]})]})]}),ze&&H&&Fe&&i.jsxs("div",{className:"flex items-center gap-3 mb-4 p-3 bg-amber-500/10 border border-amber-500/30 rounded-lg",children:[i.jsx(Tn,{className:"w-5 h-5 text-amber-500 flex-shrink-0"}),i.jsxs("div",{className:"flex-1",children:[i.jsx("p",{className:"text-sm text-amber-500 font-medium",children:t("fileManager.lowDiskSpaceWarning")}),i.jsx("p",{className:"text-xs text-amber-500/80",children:t("fileManager.lowDiskSpaceDetails",{free:ul(H.disk_free_bytes),total:ul(H.disk_total_bytes),threshold:Fe.library_disk_warning_gb})})]})]}),H&&i.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:[i.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[i.jsx(zC,{className:"w-4 h-4 text-bambu-green"}),i.jsxs("span",{className:"text-bambu-gray",children:[t("fileManager.files"),":"]}),i.jsx("span",{className:"text-white font-medium",children:H.total_files})]}),i.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[i.jsx(Zl,{className:"w-4 h-4 text-blue-400"}),i.jsxs("span",{className:"text-bambu-gray",children:[t("fileManager.folders"),":"]}),i.jsx("span",{className:"text-white font-medium",children:H.total_folders})]}),i.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[i.jsx(Ub,{className:"w-4 h-4 text-amber-400"}),i.jsxs("span",{className:"text-bambu-gray",children:[t("fileManager.size"),":"]}),i.jsx("span",{className:"text-white font-medium",children:ul(H.total_size_bytes)})]}),i.jsxs("div",{className:"flex items-center gap-2 text-sm sm:ml-auto",children:[i.jsxs("span",{className:"text-bambu-gray",children:[t("fileManager.free"),":"]}),i.jsx("span",{className:`font-medium ${ze?"text-amber-500":"text-white"}`,children:ul(H.disk_free_bytes)})]})]}),i.jsxs("div",{className:"flex-1 flex flex-col lg:flex-row gap-4 lg:gap-6 min-h-0",children:[i.jsx("div",{className:"lg:hidden",children:i.jsxs("select",{value:d??"",onChange:Ue=>h(Ue.target.value?parseInt(Ue.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:[i.jsxs("option",{value:"",children:["📁 ",t("fileManager.allFiles")]}),pe&&(()=>{const Ue=(bt,wt=0)=>{const qt=[];for(const Cn of bt)qt.push({id:Cn.id,name:Cn.name,fileCount:Cn.file_count,depth:wt}),Cn.children.length>0&&qt.push(...Ue(Cn.children,wt+1));return qt};return Ue(pe).map(bt=>i.jsxs("option",{value:bt.id,children:["│ ".repeat(bt.depth),"📂 ",bt.name," ",bt.fileCount>0?`(${bt.fileCount})`:""]},bt.id))})()]})}),i.jsxs("div",{ref:je,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:`${J}px`},children:[i.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 ${me?"bg-bambu-green":"hover:bg-bambu-green/50"}`,onMouseDown:Ue=>{Ue.preventDefault(),te(!0)},onDoubleClick:()=>{ye(256),localStorage.setItem("library-sidebar-width","256")},title:t("fileManager.dragToResizeTooltip"),children:i.jsxs("div",{className:`flex flex-col gap-1 opacity-0 group-hover/resize:opacity-100 transition-opacity ${me?"opacity-100":""}`,children:[i.jsx("div",{className:"w-0.5 h-0.5 rounded-full bg-white/70"}),i.jsx("div",{className:"w-0.5 h-0.5 rounded-full bg-white/70"}),i.jsx("div",{className:"w-0.5 h-0.5 rounded-full bg-white/70"})]})}),i.jsxs("div",{className:"p-3 border-b border-bambu-dark-tertiary flex items-center justify-between",children:[i.jsx("h2",{className:"text-sm font-medium text-white",children:t("fileManager.folders")}),i.jsx("button",{onClick:()=>{const Ue=!W;ee(Ue),localStorage.setItem("library-wrap-folders",String(Ue))},className:`text-xs px-1.5 py-0.5 rounded transition-colors ${W?"bg-bambu-green/20 text-bambu-green":"text-bambu-gray hover:text-white hover:bg-bambu-dark"}`,title:t(W?"fileManager.disableTextWrapping":"fileManager.enableTextWrapping"),children:t("fileManager.wrap")})]}),i.jsxs("div",{className:"flex-1 overflow-y-auto p-2",children:[i.jsxs("div",{className:`flex items-center gap-2 px-2 py-1.5 rounded cursor-pointer transition-colors ${d===null?"bg-bambu-green/20 text-bambu-green":"hover:bg-bambu-dark text-white"}`,onClick:()=>h(null),children:[i.jsx(df,{className:"w-4 h-4"}),i.jsx("span",{className:"text-sm",children:t("fileManager.allFiles")})]}),pe?.map(Ue=>i.jsx(Bie,{folder:Ue,selectedFolderId:d,onSelect:h,onDelete:bt=>C({type:"folder",id:bt}),onLink:A,onRename:bt=>V({type:"folder",id:bt.id,name:bt.name}),wrapNames:W,hasPermission:r,t},Ue.id))]})]}),i.jsxs("div",{className:"flex-1 flex flex-col min-w-0 min-h-0",children:[L&&L.length>0&&i.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:[i.jsxs("div",{className:"relative w-full sm:w-auto sm:flex-1 sm:max-w-xs",children:[i.jsx(kr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),i.jsx("input",{type:"text",placeholder:t("fileManager.searchFiles"),value:ue,onChange:Ue=>oe(Ue.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"})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(UC,{className:"w-4 h-4 text-bambu-gray hidden sm:block"}),i.jsxs("select",{value:_e,onChange:Ue=>se(Ue.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:[i.jsx("option",{value:"all",children:t("fileManager.allTypes")}),be.map(Ue=>i.jsx("option",{value:Ue,children:Ue.toUpperCase()},Ue))]})]}),o&&i.jsxs("div",{className:"relative",children:[i.jsx("input",{type:"text",placeholder:t("fileManager.filterByUser",{defaultValue:"Filter by user"}),value:Oe,onChange:Ue=>q(Ue.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 ${Oe?"pr-7":""}`,style:Oe?{WebkitAppearance:"none",MozAppearance:"textfield"}:void 0}),Oe&&i.jsx("button",{onClick:()=>q(""),className:"absolute right-2 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white z-10",children:i.jsx(Ft,{className:"w-3 h-3"})}),i.jsx("datalist",{id:"usernames-list",children:he?.map(Ue=>i.jsx("option",{value:Ue.username},Ue.id))})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsxs("select",{value:X,onChange:Ue=>{const bt=Ue.target.value;de(bt),localStorage.setItem("library-sort-field",bt)},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:[i.jsx("option",{value:"name",children:t("common.name")}),i.jsx("option",{value:"date",children:t("common.date")}),i.jsx("option",{value:"size",children:t("fileManager.size")}),i.jsx("option",{value:"type",children:t("common.type")}),i.jsx("option",{value:"prints",children:t("fileManager.prints")})]}),i.jsx("button",{onClick:()=>ie(Ue=>{const bt=Ue==="asc"?"desc":"asc";return localStorage.setItem("library-sort-direction",bt),bt}),className:"p-1.5 rounded bg-bambu-dark border border-bambu-dark-tertiary hover:border-bambu-green transition-colors",title:t(Z==="asc"?"fileManager.ascending":"fileManager.descending"),children:Z==="asc"?i.jsx(Tde,{className:"w-4 h-4 text-white"}):i.jsx(wde,{className:"w-4 h-4 text-white"})})]}),(ue||_e!=="all"||Oe)&&i.jsx("span",{className:"text-sm text-bambu-gray hidden sm:inline",children:t("fileManager.resultsCount",{showing:fe.length,total:L.length})})]}),fe.length>0&&i.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===fe.length&&f.length>0?i.jsxs(Ce,{variant:"secondary",size:"sm",onClick:Le,children:[i.jsx(vl,{className:"w-4 h-4 sm:mr-1"}),i.jsx("span",{className:"hidden sm:inline",children:t("fileManager.deselectAll")})]}):i.jsxs(Ce,{variant:"secondary",size:"sm",onClick:Re,children:[i.jsx(so,{className:"w-4 h-4 sm:mr-1"}),i.jsx("span",{className:"hidden sm:inline",children:t("fileManager.selectAll")})]}),f.length>0&&i.jsxs(i.Fragment,{children:[i.jsx("span",{className:"text-sm text-bambu-gray ml-2",children:t("fileManager.selected",{count:f.length})}),i.jsx("div",{className:"hidden sm:block flex-1"}),i.jsxs("div",{className:"w-full sm:w-auto flex flex-wrap items-center gap-2 mt-2 sm:mt-0",children:[Te.length===1&&i.jsxs(Ce,{variant:"primary",size:"sm",onClick:()=>B(Te[0]),disabled:!r("printers:control"),title:r("printers:control")?void 0:t("fileManager.noPermissionPrint"),children:[i.jsx(io,{className:"w-4 h-4 sm:mr-1"}),i.jsx("span",{className:"hidden sm:inline",children:t("common.print")})]}),Te.length===1&&i.jsxs(Ce,{variant:"secondary",size:"sm",onClick:()=>U(Te[0]),disabled:!r("queue:create"),title:r("queue:create")?void 0:t("fileManager.noPermissionAddToQueue"),children:[i.jsx(Gn,{className:"w-4 h-4 sm:mr-1"}),i.jsx("span",{className:"hidden sm:inline",children:t("fileManager.schedulePrint")})]}),i.jsxs(Ce,{variant:"secondary",size:"sm",onClick:()=>y(!0),disabled:!a("library:update_own","library:update_all"),title:a("library:update_own","library:update_all")?void 0:t("fileManager.noPermissionMoveFiles"),children:[i.jsx(bfe,{className:"w-4 h-4 sm:mr-1"}),i.jsx("span",{className:"hidden sm:inline",children:t("common.move")})]}),i.jsxs(Ce,{variant:"danger",size:"sm",onClick:()=>{f.length===1?C({type:"file",id:f[0]}):C({type:"bulk",id:0,count:f.length})},disabled:!a("library:delete_own","library:delete_all"),title:a("library:delete_own","library:delete_all")?void 0:t("fileManager.noPermissionDeleteFiles"),children:[i.jsx(Jt,{className:"w-4 h-4 sm:mr-1"}),i.jsx("span",{className:"hidden sm:inline",children:t("common.delete")})]}),i.jsxs(Ce,{variant:"secondary",size:"sm",onClick:Le,children:[i.jsx(Ft,{className:"w-4 h-4 sm:mr-1"}),i.jsx("span",{className:"hidden sm:inline",children:t("common.clear")})]})]})]})]}),Mt?i.jsx("div",{className:"flex-1 flex items-center justify-center",children:i.jsxs("div",{className:"flex flex-col items-center gap-3",children:[i.jsx(it,{className:"w-8 h-8 animate-spin text-bambu-green"}),i.jsx("p",{className:"text-sm text-bambu-gray",children:t("fileManager.loadingFiles")})]})}):L?.length===0?i.jsxs("div",{className:"flex-1 flex flex-col items-center justify-center",children:[i.jsx("div",{className:"p-4 bg-bambu-dark rounded-2xl mb-4",children:i.jsx(df,{className:"w-12 h-12 text-bambu-gray/50"})}),i.jsx("h3",{className:"text-lg font-medium text-white mb-2",children:t(d!==null?"fileManager.folderIsEmpty":"fileManager.noFilesYet")}),i.jsx("p",{className:"text-bambu-gray text-center max-w-md mb-6",children:t(d!==null?"fileManager.folderEmptyDescription":"fileManager.noFilesDescription")}),i.jsxs(Ce,{onClick:()=>N(!0),disabled:!r("library:upload"),title:r("library:upload")?void 0:t("fileManager.noPermissionUpload"),children:[i.jsx(Xn,{className:"w-4 h-4 mr-2"}),t("fileManager.uploadFiles")]})]}):fe.length===0?i.jsxs("div",{className:"flex-1 flex flex-col items-center justify-center",children:[i.jsx("div",{className:"p-4 bg-bambu-dark rounded-2xl mb-4",children:i.jsx(kr,{className:"w-12 h-12 text-bambu-gray/50"})}),i.jsx("h3",{className:"text-lg font-medium text-white mb-2",children:t("fileManager.noMatchingFiles")}),i.jsx("p",{className:"text-bambu-gray text-center max-w-md mb-6",children:t("fileManager.noMatchingFilesDescription")}),i.jsx(Ce,{variant:"secondary",onClick:()=>{oe(""),se("all")},children:t("fileManager.clearFilters")})]}):ae==="grid"?i.jsx("div",{className:"flex-1 lg:overflow-y-auto",children:i.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:fe.map(Ue=>i.jsx(aJe,{file:Ue,isSelected:f.includes(Ue.id),isMobile:le,t,onSelect:Ge,onDelete:bt=>C({type:"file",id:bt}),onDownload:ft,onAddToQueue:bt=>{const wt=L?.find(qt=>qt.id===bt);wt&&U(wt)},onPrint:P,onPreview3d:Y,onRename:bt=>V({type:"file",id:bt.id,name:bt.filename}),onGenerateThumbnail:bt=>Pe.mutate(bt.id),thumbnailVersion:G[Ue.id],hasPermission:r,canModify:s,authEnabled:o},Ue.id))})}):i.jsx("div",{className:"flex-1 lg:overflow-y-auto",children:i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg border border-bambu-dark-tertiary overflow-hidden",children:[i.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:[i.jsx("div",{className:"w-6"}),i.jsx("div",{children:t("common.name")}),o&&i.jsx("div",{children:t("fileManager.uploadedBy",{defaultValue:"Uploaded By"})}),i.jsx("div",{children:t("common.type")}),i.jsx("div",{children:t("fileManager.size")}),i.jsx("div",{children:t("fileManager.prints")}),i.jsx("div",{})]}),fe.map(Ue=>i.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(Ue.id)?"bg-bambu-green/10":""}`,onClick:()=>Ge(Ue.id),children:[i.jsx("div",{className:`w-5 h-5 rounded border-2 flex items-center justify-center ${f.includes(Ue.id)?"bg-bambu-green border-bambu-green":"border-bambu-gray/50"}`,children:f.includes(Ue.id)&&i.jsx("div",{className:"w-2 h-2 bg-white rounded-sm"})}),i.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[i.jsxs("div",{className:"relative group/thumb",children:[i.jsx("div",{className:"w-10 h-10 rounded bg-bambu-dark flex-shrink-0 overflow-hidden",children:Ue.thumbnail_path?i.jsx("img",{src:`${ne.getLibraryFileThumbnailUrl(Ue.id)}${G[Ue.id]?`?v=${G[Ue.id]}`:""}`,alt:"",className:"w-full h-full object-cover"}):i.jsx("div",{className:"w-full h-full flex items-center justify-center",children:i.jsx(df,{className:"w-5 h-5 text-bambu-gray/50"})})}),Ue.thumbnail_path&&i.jsx("div",{className:"absolute left-0 top-full mt-2 z-50 hidden group-hover/thumb:block",children:i.jsx("div",{className:"w-48 h-48 rounded-lg bg-bambu-dark-secondary border border-bambu-dark-tertiary shadow-xl overflow-hidden",children:i.jsx("img",{src:`${ne.getLibraryFileThumbnailUrl(Ue.id)}${G[Ue.id]?`?v=${G[Ue.id]}`:""}`,alt:Ue.filename,className:"w-full h-full object-contain"})})})]}),i.jsx("div",{className:"min-w-0",children:i.jsx("div",{className:"text-sm text-white truncate",children:Ue.print_name||Ue.filename})})]}),o&&i.jsx("div",{className:"text-sm text-bambu-gray flex items-center gap-1",children:Ue.created_by_username?i.jsxs(i.Fragment,{children:[i.jsx(td,{className:"w-3 h-3"}),i.jsx("span",{className:"truncate",children:Ue.created_by_username})]}):"-"}),i.jsx("div",{children:i.jsx("span",{className:`text-xs px-1.5 py-0.5 rounded font-medium ${Ue.file_type==="3mf"?"bg-bambu-green/20 text-bambu-green":Ue.file_type==="gcode"?"bg-blue-500/20 text-blue-400":Ue.file_type==="stl"?"bg-purple-500/20 text-purple-400":"bg-bambu-gray/20 text-bambu-gray"}`,children:Ue.file_type.toUpperCase()})}),i.jsx("div",{className:"text-sm text-bambu-gray",children:ul(Ue.file_size)}),i.jsx("div",{className:"text-sm text-bambu-gray",children:Ue.print_count>0?`${Ue.print_count}x`:"-"}),i.jsxs("div",{className:"flex items-center gap-1",onClick:bt=>bt.stopPropagation(),children:[tF(Ue.filename)&&i.jsxs(i.Fragment,{children:[i.jsx("button",{onClick:()=>r("printers:control")&&P(Ue),className:`p-1.5 rounded transition-colors ${r("printers:control")?"hover:bg-bambu-dark text-bambu-gray hover:text-bambu-green":"text-bambu-gray/50 cursor-not-allowed"}`,title:r("printers:control")?t("common.print"):t("fileManager.noPermissionPrint"),disabled:!r("printers:control"),children:i.jsx(xr,{className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>{r("queue:create")&&U(Ue)},className:`p-1.5 rounded transition-colors ${r("queue:create")?"hover:bg-bambu-dark text-bambu-gray hover:text-white":"text-bambu-gray/50 cursor-not-allowed"}`,title:r("queue:create")?t("fileManager.schedulePrint"):t("fileManager.noPermissionAddToQueue"),disabled:!r("queue:create"),children:i.jsx(Gn,{className:"w-4 h-4"})})]}),(Ue.file_type==="3mf"||Ue.file_type==="gcode"||Ue.file_type==="stl")&&i.jsx("button",{onClick:()=>r("library:read")&&Y(Ue),className:`p-1.5 rounded transition-colors ${r("library:read")?"hover:bg-bambu-dark text-bambu-gray hover:text-bambu-green":"text-bambu-gray/50 cursor-not-allowed"}`,title:r("library:read")?"3D Preview":"You do not have permission to preview files",disabled:!r("library:read"),children:i.jsx(Ja,{className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>r("library:read")&&ft(Ue.id),className:`p-1.5 rounded transition-colors ${r("library:read")?"hover:bg-bambu-dark text-bambu-gray hover:text-white":"text-bambu-gray/50 cursor-not-allowed"}`,title:r("library:read")?t("common.download"):t("fileManager.noPermissionDownload"),disabled:!r("library:read"),children:i.jsx(ua,{className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>s("library","update",Ue.created_by_id)&&V({type:"file",id:Ue.id,name:Ue.filename}),className:`p-1.5 rounded transition-colors ${s("library","update",Ue.created_by_id)?"hover:bg-bambu-dark text-bambu-gray hover:text-white":"text-bambu-gray/50 cursor-not-allowed"}`,title:s("library","update",Ue.created_by_id)?t("common.rename"):t("fileManager.noPermissionRenameFile"),disabled:!s("library","update",Ue.created_by_id),children:i.jsx($a,{className:"w-4 h-4"})}),Ue.file_type==="stl"&&i.jsx("button",{onClick:()=>s("library","update",Ue.created_by_id)&&Pe.mutate(Ue.id),className:`p-1.5 rounded transition-colors ${s("library","update",Ue.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",Ue.created_by_id)?t("fileManager.generateThumbnail"):t("fileManager.noPermissionGenerateThumbnail"),disabled:Pe.isPending||!s("library","update",Ue.created_by_id),children:i.jsx(Ju,{className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>s("library","delete",Ue.created_by_id)&&C({type:"file",id:Ue.id}),className:`p-1.5 rounded transition-colors ${s("library","delete",Ue.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",Ue.created_by_id)?t("common.delete"):t("fileManager.noPermissionDeleteFile"),disabled:!s("library","delete",Ue.created_by_id),children:i.jsx(Jt,{className:"w-4 h-4"})})]})]},Ue.id))]})})]})]}),x&&i.jsx(JZe,{parentId:d,onClose:()=>v(!1),onSave:Ue=>Ie.mutate(Ue),isLoading:Ie.isPending,t}),g&&pe&&i.jsx(tJe,{folders:pe,selectedFiles:f,currentFolderId:d,onClose:()=>y(!1),onMove:Ue=>Se.mutate({fileIds:f,folderId:Ue}),isLoading:Se.isPending,t}),_&&i.jsx(rJe,{folderId:d,onClose:()=>N(!1),onUploadComplete:Ke,t}),k&&i.jsx(nJe,{folder:k,onClose:()=>A(null),onLink:Ue=>Me.mutate({id:k.id,data:Ue}),isLoading:Me.isPending,t}),M&&i.jsx(gn,{title:M.type==="folder"?t("fileManager.deleteFolder"):M.type==="bulk"?t("fileManager.deleteFilesCount",{count:M.count}):t("fileManager.deleteFile"),message:M.type==="folder"?t("fileManager.deleteFolderConfirm"):M.type==="bulk"?t("fileManager.deleteFilesConfirm",{count:M.count}):t("fileManager.deleteFileConfirm"),confirmText:t("common.delete"),variant:"danger",isLoading:Lt,loadingText:t("fileManager.deleting"),onConfirm:kt,onCancel:()=>C(null)}),j&&i.jsx(Xu,{mode:"reprint",libraryFileId:j.id,archiveName:j.print_name||j.filename,onClose:()=>P(null),onSuccess:()=>{P(null),e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["archives"]})}}),E&&i.jsx(Xu,{mode:"reprint",libraryFileId:E.id,archiveName:E.print_name||E.filename,onClose:()=>B(null),onSuccess:()=>{B(null),p([]),e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["archives"]})}}),O&&i.jsx(Xu,{mode:"add-to-queue",libraryFileId:O.id,archiveName:O.print_name||O.filename,onClose:()=>U(null),onSuccess:()=>{U(null),p([]),e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["queue"]}),e.invalidateQueries({queryKey:["archives"]})}}),K&&i.jsx(hI,{libraryFileId:K.id,title:K.print_name||K.filename,fileType:K.file_type,onClose:()=>Y(null)}),R&&i.jsx(eJe,{type:R.type,currentName:R.name,onClose:()=>V(null),onSave:Ue=>{R.type==="file"?xe.mutate({id:R.id,filename:Ue}):ve.mutate({id:R.id,name:Ue})},isLoading:xe.isPending||ve.isPending,t})]})}const Pj=5,sJe=2e3,oJe=3e4,lJe=5e3;function cJe(){const{t}=Ut(),e=tn(),{showToast:n}=cn(),{hasPermission:r}=Or(),{printerId:a}=i0(),s=parseInt(a||"0",10),[o,l]=w.useState("stream"),[c,u]=w.useState(!1),[d,h]=w.useState(!1),[f,p]=w.useState(!0),[x,v]=w.useState(Date.now()),[g,y]=w.useState(!1),[_,N]=w.useState(!1),[k,A]=w.useState(0),[M,C]=w.useState(!1),[j,P]=w.useState(0),[E,B]=w.useState(1),[O,U]=w.useState({x:0,y:0}),[R,V]=w.useState(!1),[G,z]=w.useState({x:0,y:0}),[K,Y]=w.useState(null),[ae,$]=w.useState(null),W=w.useRef(null),ee=w.useRef(null),J=w.useRef(null),ye=w.useRef(null),me=w.useRef(null),{data:te}=Je({queryKey:["printer",s],queryFn:()=>ne.getPrinter(s),enabled:s>0}),{data:je}=Je({queryKey:["printerStatus",s],queryFn:()=>ne.getPrinterStatus(s),refetchInterval:3e4,enabled:s>0}),ue=ot({mutationFn:Se=>ne.setChamberLight(s,Se),onMutate:async Se=>{await e.cancelQueries({queryKey:["printerStatus",s]});const Me=e.getQueryData(["printerStatus",s]);return e.setQueryData(["printerStatus",s],xe=>({...xe,chamber_light:Se})),{previousStatus:Me}},onSuccess:(Se,Me)=>{n(`Chamber light ${Me?"on":"off"}`)},onError:(Se,Me,xe)=>{xe?.previousStatus&&e.setQueryData(["printerStatus",s],xe.previousStatus),n(Se.message||t("printers.toast.failedToControlChamberLight"),"error")}}),oe=(je?.state==="RUNNING"||je?.state==="PAUSE")&&(je?.printable_objects_count??0)>=2;w.useEffect(()=>(te&&(document.title=`${te.name} - Camera`),()=>{document.title="Bambuddy"}),[te]);const _e=w.useRef(!1);w.useEffect(()=>{const Se=`/api/v1/printers/${s}/camera/stop`;_e.current=!1;const Me=()=>{if(s>0&&!_e.current){_e.current=!0;const He={},Pe=nd();Pe&&(He.Authorization=`Bearer ${Pe}`),fetch(Se,{method:"POST",keepalive:!0,headers:He}).catch(()=>{})}},xe=()=>{Me()};window.addEventListener("beforeunload",xe);const ve=W.current;return()=>{window.removeEventListener("beforeunload",xe),ve&&(ve.src=""),Me()}},[s]),w.useEffect(()=>{if(f&&!g){const Me=setTimeout(()=>{p(!1)},o==="stream"?3e3:2e4);return()=>clearTimeout(Me)}},[o,f,x,g]),w.useEffect(()=>{const Se=()=>{const Me=!!document.fullscreenElement;N(Me),B(1),U({x:0,y:0}),o==="stream"&&!g&&(W.current&&(W.current.src=""),setTimeout(()=>{p(!0),v(Date.now())},200))};return document.addEventListener("fullscreenchange",Se),()=>document.removeEventListener("fullscreenchange",Se)},[o,g]),w.useEffect(()=>{let Se;const Me=()=>{clearTimeout(Se),Se=setTimeout(()=>{localStorage.setItem("cameraWindowState",JSON.stringify({width:window.outerWidth,height:window.outerHeight,left:window.screenX,top:window.screenY}))},500)};return window.addEventListener("resize",Me),()=>{clearTimeout(Se),window.removeEventListener("resize",Me)}},[]),w.useEffect(()=>()=>{J.current&&clearTimeout(J.current),ye.current&&clearInterval(ye.current),me.current&&clearInterval(me.current)},[]);const se=w.useCallback(()=>{if(k>=Pj){C(!1),h(!0);return}const Se=Math.min(sJe*Math.pow(2,k),oJe);C(!0),P(Math.ceil(Se/1e3)),ye.current=setInterval(()=>{P(Me=>Me<=1?(ye.current&&clearInterval(ye.current),0):Me-1)},1e3),J.current=setTimeout(()=>{A(Me=>Me+1),C(!1),p(!0),h(!1),W.current&&(W.current.src=""),v(Date.now())},Se)},[k]);w.useEffect(()=>{if(o!=="stream"||f||M||g){me.current&&(clearInterval(me.current),me.current=null);return}return me.current=setInterval(async()=>{try{const Se=await ne.getCameraStatus(s);(Se.stalled||!Se.active&&!d)&&(console.log(`Stream issue detected: stalled=${Se.stalled}, active=${Se.active}, reconnecting...`),me.current&&(clearInterval(me.current),me.current=null),p(!1),se())}catch{}},lJe),()=>{me.current&&(clearInterval(me.current),me.current=null)}},[o,f,d,M,g,s,se]);const Oe=()=>{p(!1),o==="stream"&&k{if(p(!1),h(!1),A(0),C(!1),J.current&&clearTimeout(J.current),ye.current&&clearInterval(ye.current),W.current&&!localStorage.getItem("cameraWindowState")){const Se=W.current,Me=Se.naturalWidth,xe=Se.naturalHeight;if(Me>0&&xe>0){const Pe=window.outerWidth-window.innerWidth,nt=window.outerHeight-window.innerHeight,Te=Me+16+Pe,Ge=xe+45+16+nt;try{window.resizeTo(Te,Ge)}catch{}}}},X=()=>{if(s>0){const Se={},Me=nd();Me&&(Se.Authorization=`Bearer ${Me}`),fetch(`/api/v1/printers/${s}/camera/stop`,{method:"POST",headers:Se}).catch(()=>{})}},de=Se=>{o===Se||g||(y(!0),p(!0),h(!1),A(0),C(!1),B(1),U({x:0,y:0}),J.current&&clearTimeout(J.current),ye.current&&clearInterval(ye.current),W.current&&(W.current.src=""),o==="stream"&&X(),setTimeout(()=>{l(Se),v(Date.now()),y(!1)},100))},Z=()=>{g||(y(!0),p(!0),h(!1),A(0),C(!1),J.current&&clearTimeout(J.current),ye.current&&clearInterval(ye.current),W.current&&(W.current.src=""),o==="stream"&&X(),setTimeout(()=>{v(Date.now()),y(!1)},100))},ie=()=>{ee.current&&(document.fullscreenElement?document.exitFullscreen():ee.current.requestFullscreen())},le=()=>{B(Se=>Math.min(Se+.5,4))},Fe=()=>{B(Se=>{const Me=Math.max(Se-.5,1);return Me===1&&U({x:0,y:0}),Me})},pe=Se=>{Se.preventDefault(),Se.deltaY<0?le():Fe()},Q=Se=>{E>1&&(Se.preventDefault(),V(!0),z({x:Se.clientX-O.x,y:Se.clientY-O.y}))},L=w.useCallback(()=>{if(!ee.current)return{x:300,y:200};const Se=ee.current.getBoundingClientRect(),Me=Se.width*(E-1)/2,xe=Se.height*(E-1)/2;return{x:Math.max(50,Me),y:Math.max(50,xe)}},[E]),D=Se=>{if(R&&E>1){const Me=Se.clientX-G.x,xe=Se.clientY-G.y,ve=L();U({x:Math.max(-ve.x,Math.min(ve.x,Me)),y:Math.max(-ve.y,Math.min(ve.y,xe))})}},H=()=>{V(!1)},he=Se=>{if(Se.length<2)return 0;const Me=Se[0].clientX-Se[1].clientX,xe=Se[0].clientY-Se[1].clientY;return Math.sqrt(Me*Me+xe*xe)},be=Se=>Se.length<2?{x:Se[0].clientX,y:Se[0].clientY}:{x:(Se[0].clientX+Se[1].clientX)/2,y:(Se[0].clientY+Se[1].clientY)/2},fe=Se=>{Se.touches.length===2?(Se.preventDefault(),Y(he(Se.touches)),$(be(Se.touches))):Se.touches.length===1&&E>1&&(Se.preventDefault(),V(!0),z({x:Se.touches[0].clientX-O.x,y:Se.touches[0].clientY-O.y}))},ze=Se=>{if(Se.touches.length===2&&K!==null){Se.preventDefault();const Me=he(Se.touches),xe=Me/K;B(He=>{const Pe=Math.max(1,Math.min(4,He*xe));return Pe===1&&U({x:0,y:0}),Pe}),Y(Me);const ve=be(Se.touches);if(ae){const He=L();U(Pe=>({x:Math.max(-He.x,Math.min(He.x,Pe.x+(ve.x-ae.x))),y:Math.max(-He.y,Math.min(He.y,Pe.y+(ve.y-ae.y)))}))}$(ve)}else if(Se.touches.length===1&&R&&E>1){Se.preventDefault();const Me=Se.touches[0].clientX-G.x,xe=Se.touches[0].clientY-G.y,ve=L();U({x:Math.max(-ve.x,Math.min(ve.x,Me)),y:Math.max(-ve.y,Math.min(ve.y,xe))})}},Ie=Se=>{Se.touches.length<2&&(Y(null),$(null)),Se.touches.length===0&&V(!1)},qe=()=>{B(1),U({x:0,y:0})},tt=g?"":o==="stream"?`/api/v1/printers/${s}/camera/stream?fps=15&t=${x}`:`/api/v1/printers/${s}/camera/snapshot?t=${x}`,Ee=f||g||M;return s?i.jsxs("div",{ref:ee,className:"min-h-screen bg-black flex flex-col",children:[i.jsxs("div",{className:"flex items-center justify-between px-4 py-2 bg-bambu-dark-secondary border-b border-bambu-dark-tertiary",children:[i.jsxs("h1",{className:"text-sm font-medium text-white flex items-center gap-2",children:[i.jsx(sb,{className:"w-4 h-4"}),te?.name||`Printer ${s}`]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsxs("div",{className:"flex bg-bambu-dark rounded p-0.5",children:[i.jsx("button",{onClick:()=>de("stream"),disabled:Ee,className:`px-3 py-1 text-xs rounded transition-colors ${o==="stream"?"bg-bambu-green text-white":"text-bambu-gray hover:text-white disabled:opacity-50"}`,children:t("camera.live")}),i.jsx("button",{onClick:()=>de("snapshot"),disabled:Ee,className:`px-3 py-1 text-xs rounded transition-colors ${o==="snapshot"?"bg-bambu-green text-white":"text-bambu-gray hover:text-white disabled:opacity-50"}`,children:t("camera.snapshot")})]}),i.jsx("button",{onClick:()=>ue.mutate(!je?.chamber_light),disabled:!je?.connected||ue.isPending||!r("printers:control"),className:`p-1.5 rounded disabled:opacity-50 ${je?.chamber_light?"bg-yellow-500/20 hover:bg-yellow-500/30":"hover:bg-bambu-dark-tertiary"}`,title:r("printers:control")?t("camera.chamberLight"):t("printers.permission.noControl"),children:i.jsx(aL,{on:je?.chamber_light??!1,className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>u(!0),disabled:!oe||!r("printers:control"),className:`p-1.5 rounded disabled:opacity-50 ${oe&&r("printers:control")?"hover:bg-bambu-dark-tertiary":""}`,title:r("printers:control")?t(oe?"printers.skipObjects.tooltip":"printers.skipObjects.onlyWhilePrinting"):t("printers.permission.noControl"),children:i.jsx(lk,{className:"w-4 h-4 text-bambu-gray"})}),i.jsx("button",{onClick:Z,disabled:Ee,className:"p-1.5 hover:bg-bambu-dark-tertiary rounded disabled:opacity-50",title:t(o==="stream"?"camera.restartStream":"camera.refreshSnapshot"),children:i.jsx(Cr,{className:`w-4 h-4 text-bambu-gray ${Ee?"animate-spin":""}`})}),i.jsx("button",{onClick:ie,className:"p-1.5 hover:bg-bambu-dark-tertiary rounded",title:t(_?"camera.exitFullscreen":"camera.fullscreen"),children:_?i.jsx(oX,{className:"w-4 h-4 text-bambu-gray"}):i.jsx(ife,{className:"w-4 h-4 text-bambu-gray"})})]})]}),i.jsx("div",{className:"flex-1 flex items-center justify-center p-2 overflow-hidden",onWheel:pe,onMouseMove:D,onMouseUp:H,onMouseLeave:H,onTouchStart:fe,onTouchMove:ze,onTouchEnd:Ie,style:{touchAction:"none"},children:i.jsxs("div",{className:"relative w-full h-full flex items-center justify-center",children:[(f||g)&&!M&&i.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/50 z-10",children:i.jsxs("div",{className:"text-center",children:[i.jsx(Cr,{className:"w-8 h-8 text-bambu-gray animate-spin mx-auto mb-2"}),i.jsx("p",{className:"text-sm text-bambu-gray",children:t(o==="stream"?"camera.connectingToCamera":"camera.capturingSnapshot")})]})}),M&&i.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/80 z-10",children:i.jsxs("div",{className:"text-center p-4",children:[i.jsx(Pf,{className:"w-10 h-10 text-orange-400 mx-auto mb-3"}),i.jsx("p",{className:"text-white mb-2",children:t("camera.connectionLost")}),i.jsx("p",{className:"text-sm text-bambu-gray mb-3",children:t("camera.reconnecting",{countdown:j,attempt:k+1,max:Pj})}),i.jsx("button",{onClick:Z,className:"px-4 py-2 bg-bambu-green text-white text-sm rounded hover:bg-bambu-green/80 transition-colors",children:t("camera.reconnectNow")})]})}),d&&!M&&i.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black z-10",children:i.jsxs("div",{className:"text-center p-4",children:[i.jsx(Tn,{className:"w-12 h-12 text-orange-400 mx-auto mb-3"}),i.jsx("p",{className:"text-white mb-2",children:t("camera.cameraUnavailable")}),i.jsx("p",{className:"text-xs text-bambu-gray mb-4 max-w-md",children:t("camera.cameraUnavailableDesc")}),i.jsx("button",{onClick:Z,className:"px-4 py-2 bg-bambu-green text-white rounded hover:bg-bambu-green/80 transition-colors",children:t("camera.retry")})]})}),i.jsx("img",{ref:W,src:tt,alt:t("camera.cameraStream"),className:"max-w-full max-h-full object-contain select-none",style:{transform:`scale(${E}) translate(${O.x/E}px, ${O.y/E}px)`,cursor:E>1?R?"grabbing":"grab":"default"},onError:tt?Oe:void 0,onLoad:tt?q:void 0,onMouseDown:Q,draggable:!1},x),i.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:[i.jsx("button",{onClick:Fe,disabled:E<=1,className:"p-1.5 hover:bg-white/10 rounded disabled:opacity-30",title:t("camera.zoomOut"),children:i.jsx(TF,{className:"w-4 h-4 text-white"})}),i.jsxs("button",{onClick:qe,className:"px-2 py-1 text-sm text-white hover:bg-white/10 rounded min-w-[48px]",title:t("camera.resetZoom"),children:[Math.round(E*100),"%"]}),i.jsx("button",{onClick:le,disabled:E>=4,className:"p-1.5 hover:bg-white/10 rounded disabled:opacity-30",title:t("camera.zoomIn"),children:i.jsx(AF,{className:"w-4 h-4 text-white"})})]})]})}),i.jsx(iL,{printerId:s,isOpen:c,onClose:()=>u(!1)})]}):i.jsx("div",{className:"min-h-screen bg-black flex items-center justify-center",children:i.jsx("p",{className:"text-white",children:t("camera.invalidPrinterId")})})}function uJe(t){const e=t.get("show")?.split(",")||["progress","layers","eta","filename","status"],n=parseInt(t.get("fps")||"15",10),r=Math.min(Math.max(isNaN(n)?15:n,1),30),a=t.get("camera"),s=a!=="false"&&a!=="0";return{size:t.get("size")||"medium",fps:r,showCamera:s,showProgress:e.includes("progress"),showLayers:e.includes("layers"),showEta:e.includes("eta"),showFilename:e.includes("filename"),showStatus:e.includes("status"),showPrinter:e.includes("printer")}}function dJe(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 hJe(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 mJe(){const{printerId:t}=i0(),[e]=dF(),{t:n}=Ut(),r=tn(),a=parseInt(t||"0",10),[s,o]=w.useState(Date.now()),l=w.useMemo(()=>uJe(e),[e]),c=hJe(l.size),{data:u}=Je({queryKey:["printer",a],queryFn:()=>ne.getPrinter(a),enabled:a>0}),{data:d}=Je({queryKey:["printerStatus",a],queryFn:()=>ne.getPrinterStatus(a),enabled:a>0,refetchInterval:2e3}),{data:h}=Je({queryKey:["settings"],queryFn:ne.getSettings}),f=h?.time_format||"system";w.useEffect(()=>{if(!a)return;const _=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/api/v1/ws`,N=new WebSocket(_);return N.onmessage=k=>{try{const A=JSON.parse(k.data);A.type==="printer_status"&&A.printer_id===a&&r.setQueryData(["printerStatus",a],A.status)}catch{}},N.onerror=()=>{},()=>{N.close()}},[a,r]),w.useEffect(()=>(document.title=u?`${u.name} - ${n("streamOverlay.title")}`:n("streamOverlay.title"),()=>{document.title="Bambuddy"}),[u,n]);const p=()=>{setTimeout(()=>{o(Date.now())},3e3)};if(!a)return i.jsx("div",{className:"min-h-screen bg-black flex items-center justify-center",children:i.jsx("p",{className:"text-white",children:n("streamOverlay.invalidPrinterId")})});if(!d)return i.jsx("div",{className:"min-h-screen bg-black flex items-center justify-center",children:i.jsx("p",{className:"text-gray-400",children:n("common.loading")})});const x=d.state==="RUNNING"||d.state==="PAUSE",v=d.progress||0,g=`/api/v1/printers/${a}/camera/stream?fps=${l.fps}&t=${s}`;return i.jsxs("div",{className:"min-h-screen bg-black relative overflow-hidden",children:[l.showCamera&&i.jsx("img",{src:g,alt:n("streamOverlay.cameraStream"),className:"absolute inset-0 w-full h-full object-contain",onError:p},s),i.jsx("a",{href:"https://github.com/maziggy/bambuddy",target:"_blank",rel:"noopener noreferrer",className:"absolute top-4 right-4 z-10",children:i.jsx("img",{src:"/img/bambuddy_logo_dark_transparent.png",alt:"Bambuddy",className:`${c.logoHeight} object-contain drop-shadow-lg hover:scale-105 transition-transform`})}),i.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:i.jsxs("div",{className:`${c.container}`,children:[l.showPrinter&&u&&i.jsxs("div",{className:`flex items-center ${c.gap} mb-2`,children:[i.jsx(xr,{className:`${c.icon} text-white/70`}),i.jsx("span",{className:`${c.text} text-white font-medium`,children:u.name})]}),l.showFilename&&d.current_print&&i.jsx("div",{className:`${c.textLarge} text-white font-semibold mb-2 truncate drop-shadow-md`,children:d.current_print.replace(/\.gcode\.3mf$|\.3mf$|\.gcode$/i,"")}),l.showStatus&&i.jsx("div",{className:`${c.text} text-white/70 mb-2`,children:dJe(d,n)}),l.showProgress&&x&&i.jsxs("div",{className:"mb-3",children:[i.jsxs("div",{className:`flex items-center justify-between mb-1 ${c.text}`,children:[i.jsx("span",{className:"text-white/70",children:n("streamOverlay.progress")}),i.jsxs("span",{className:"text-white font-bold",children:[Math.round(v),"%"]})]}),i.jsx("div",{className:`w-full bg-white/20 rounded-full ${c.progressHeight}`,children:i.jsx("div",{className:`bg-bambu-green ${c.progressHeight} rounded-full transition-all duration-500`,style:{width:`${v}%`}})})]}),x&&(l.showLayers||l.showEta)&&i.jsxs("div",{className:`flex items-center ${c.gap} flex-wrap`,children:[l.showLayers&&d.layer_num!=null&&d.total_layers!=null&&d.total_layers>0&&i.jsxs("div",{className:`flex items-center ${c.gap} text-white/70`,children:[i.jsx(mi,{className:c.icon}),i.jsxs("span",{className:c.text,children:[i.jsx("span",{className:"text-white",children:d.layer_num}),i.jsx("span",{className:"mx-1",children:"/"}),i.jsx("span",{children:d.total_layers})]})]}),l.showEta&&d.remaining_time!=null&&d.remaining_time>0&&i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:`flex items-center ${c.gap} text-white/70`,children:[i.jsx(Lu,{className:c.icon}),i.jsx("span",{className:`${c.text} text-white`,children:Qs(d.remaining_time*60)})]}),i.jsxs("div",{className:`flex items-center ${c.gap} text-white/70`,children:[i.jsx(Gn,{className:c.icon}),i.jsxs("span",{className:`${c.text} text-white`,children:[n("streamOverlay.eta")," ",MF(d.remaining_time,f,n)]})]})]})]}),!x&&i.jsx("div",{className:`${c.text} text-white/70 py-2`,children:d.connected?n("streamOverlay.printerIdle"):n("streamOverlay.printerOffline")})]})})]})}function fJe(){const{t}=Ut(),{id:e}=i0(),{mode:n}=Jf(),{data:r,isLoading:a,error:s}=Je({queryKey:["external-link",e],queryFn:()=>ne.getExternalLink(Number(e)),enabled:!!e});return a?i.jsx("div",{className:"flex items-center justify-center h-full",children:i.jsx(it,{className:"w-8 h-8 text-bambu-green animate-spin"})}):s||!r?i.jsxs("div",{className:"flex flex-col items-center justify-center h-full gap-4 text-bambu-gray",children:[i.jsx(Tn,{className:"w-12 h-12"}),i.jsx("p",{children:t("common.linkNotFound")})]}):i.jsx("iframe",{src:r.url,className:"h-full w-full border-0",style:{colorScheme:n},title:r.name,sandbox:"allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox"})}function tK(){const{id:t}=i0(),e=rc(),n=tn(),{t:r}=Ut(),{showToast:a}=cn(),s=!!t,[o,l]=w.useState(""),[c,u]=w.useState(""),[d,h]=w.useState([]),[f,p]=w.useState(""),[x,v]=w.useState(!1),{data:g,isLoading:y}=Je({queryKey:["group",t],queryFn:()=>ne.getGroup(Number(t)),enabled:s}),{data:_,isLoading:N}=Je({queryKey:["permissions"],queryFn:()=>ne.getPermissions()});s&&g&&!x&&(l(g.name),u(g.description||""),h(g.permissions),v(!0));const k=ot({mutationFn:z=>ne.createGroup(z),onSuccess:()=>{n.invalidateQueries({queryKey:["groups"]}),a(r("groups.toast.created")),e("/settings?tab=users")},onError:z=>{a(z.message,"error")}}),A=ot({mutationFn:z=>ne.updateGroup(Number(t),z),onSuccess:()=>{n.invalidateQueries({queryKey:["groups"]}),a(r("groups.toast.updated")),e("/settings?tab=users")},onError:z=>{a(z.message,"error")}}),M=k.isPending||A.isPending,C=()=>{if(!o.trim()){a(r("groups.toast.enterGroupName"),"error");return}s?A.mutate({name:o!==g?.name?o:void 0,description:c,permissions:d}):k.mutate({name:o,description:c||void 0,permissions:d})},j=z=>{h(K=>K.includes(z)?K.filter(Y=>Y!==z):[...K,z])},P=(z,K)=>{const Y=z.permissions.map(ae=>ae.value);h(ae=>{const $=ae.filter(W=>!Y.includes(W));return K?[...$,...Y]:$})},E=z=>z.permissions.every(K=>d.includes(K.value)),B=z=>{const K=z.permissions.filter(Y=>d.includes(Y.value)).length;return K>0&&K{_&&h(_.all_permissions)},U=()=>{h([])},R=f.toLowerCase(),V=w.useMemo(()=>_?R?_.categories.map(z=>({...z,permissions:z.permissions.filter(K=>K.label.toLowerCase().includes(R))})).filter(z=>z.permissions.length>0):_.categories:[],[_,R]),G=_?.all_permissions.length??0;return y||N?i.jsx("div",{className:"flex items-center justify-center py-16",children:i.jsx(it,{className:"w-8 h-8 text-bambu-green animate-spin"})}):i.jsxs("div",{className:"space-y-6 max-w-5xl mx-auto",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.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:i.jsx(ZK,{className:"w-5 h-5"})}),i.jsx("h1",{className:"text-xl font-bold text-white",children:r(s?"groups.editor.title":"groups.editor.createTitle")})]}),s&&g?.is_system&&i.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:[i.jsx(Tn,{className:"w-4 h-4 shrink-0"}),r("groups.form.systemGroupWarning")]}),i.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:r("groups.form.groupName")}),i.jsx("input",{type:"text",value:o,onChange:z=>l(z.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:r("groups.form.groupNamePlaceholder")})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:r("groups.form.description")}),i.jsx("input",{type:"text",value:c,onChange:z=>u(z.target.value),className:"w-full px-4 py-3 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors",placeholder:r("groups.form.descriptionPlaceholder")})]})]}),i.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-3",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsxs("span",{className:"text-sm text-bambu-gray",children:[r("groups.editor.permissionsSelected",{count:d.length})," / ",G]}),i.jsx(Ce,{size:"sm",variant:"ghost",onClick:O,children:r("groups.editor.selectAll")}),i.jsx(Ce,{size:"sm",variant:"ghost",onClick:U,children:r("groups.editor.clearAll")})]}),i.jsxs("div",{className:"relative",children:[i.jsx(kr,{className:"w-4 h-4 absolute left-3 top-1/2 -translate-y-1/2 text-bambu-gray"}),i.jsx("input",{type:"text",value:f,onChange:z=>p(z.target.value),placeholder:r("groups.editor.search"),className:"pl-9 pr-4 py-2 text-sm bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors w-64"})]})]}),V.length===0?i.jsx("div",{className:"text-center py-12 text-bambu-gray",children:r("groups.editor.noResults")}):i.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:V.map(z=>{const K=_.categories.find(ee=>ee.name===z.name),Y=K.permissions.filter(ee=>d.includes(ee.value)).length,ae=K.permissions.length,$=E(K),W=B(K);return i.jsxs(vt,{children:[i.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:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsxs("button",{type:"button",onClick:()=>P(K,!$),className:`w-5 h-5 rounded border flex items-center justify-center transition-colors shrink-0 ${$?"bg-bambu-green border-bambu-green":W?"bg-bambu-green/50 border-bambu-green":"border-bambu-gray hover:border-white"}`,children:[$&&i.jsx(ra,{className:"w-3 h-3 text-white"}),W&&!$&&i.jsx(x1,{className:"w-3 h-3 text-white"})]}),i.jsx(i3,{className:"w-4 h-4 text-bambu-gray shrink-0"}),i.jsx("span",{className:"text-white font-medium text-sm",children:z.name})]}),i.jsxs("span",{className:"text-xs text-bambu-gray tabular-nums",children:[Y,"/",ae]})]}),i.jsx("div",{className:"p-3 space-y-1",children:z.permissions.map(ee=>i.jsxs("label",{className:"flex items-center gap-3 px-2 py-1.5 rounded hover:bg-bambu-dark-secondary cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:d.includes(ee.value),onChange:()=>j(ee.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"}),i.jsx("span",{className:"text-sm text-bambu-gray",children:ee.label})]},ee.value))})]},z.name)})}),i.jsx("div",{className:"h-16"}),i.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:[i.jsx(Ce,{variant:"secondary",onClick:()=>e("/settings?tab=users"),children:r("common.cancel")}),i.jsx(Ce,{onClick:C,disabled:M||!o.trim(),children:M?i.jsxs(i.Fragment,{children:[i.jsx(it,{className:"w-4 h-4 animate-spin"}),r("common.saving")]}):i.jsxs(i.Fragment,{children:[i.jsx(ps,{className:"w-4 h-4"}),r("common.save")]})})]})]})}const nK={material:"",subtype:"",brand:"",color_name:"",rgba:"808080FF",label_weight:1e3,core_weight:250,core_weight_catalog_id:null,weight_used:0,slicer_filament:"",note:"",cost_per_kg:null};function pJe(t){const e={};return t.slicer_filament||(e.slicer_filament="Slicer preset is required"),t.material||(e.material="Material is required"),t.brand||(e.brand="Brand is required"),t.subtype||(e.subtype="Subtype is required"),{isValid:Object.keys(e).length===0,errors:e}}const gJe=["PLA","PETG","ABS","TPU","ASA","PC","PA","PVA","HIPS","PA-CF","PETG-CF","PLA-CF"],bJe=["Bambu","PolyLite","PolyTerra","eSUN","Overture","Fiberon","SUNLU","Inland","Hatchbox","Generic"],lv=["Basic","Matte","Silk","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"],Hie=[{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"}],xJe=[{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"}],rK=[...Hie,...xJe],$ie="bambuddy-recent-colors",yJe=8,vJe=[{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 Rb(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","PETG","PLA","ABS","ASA","PC","PA","TPU","PVA","HIPS","BVOH","PPS","PCTG","PEEK","PEI"];let r="",a=-1;for(const c of n){const u=e.toUpperCase().indexOf(c.toUpperCase());if(u!==-1){r=c,a=u;break}}let s="";a>0&&(s=e.substring(0,a).trim(),s=s.replace(/[-_\s]+$/,""));let o="";a!==-1&&r&&(o=e.substring(a+r.length).trim(),o=o.replace(/^[-_\s]+/,""));let l="";for(const c of lv)if(o.toLowerCase().includes(c.toLowerCase())){l=c;break}if(!l&&s)for(const c of lv){const u=new RegExp(`\\s+${c}$`,"i");if(u.test(s)){l=c,s=s.replace(u,"").trim();break}}return{brand:s,material:r,variant:l}}function wJe(t,e){const n=new Set(bJe);for(const r of t){const{brand:a}=Rb(r.name);a&&a.length>1&&n.add(a)}if(e)for(const r of e)if(r.filament_vendor&&r.filament_vendor.length>1)n.add(r.filament_vendor);else{const{brand:a}=Rb(r.name);a&&a.length>1&&n.add(a)}return Array.from(n).sort((r,a)=>r.localeCompare(a))}function SJe(t){const e=t.filter(r=>r.preset_type==="filament");if(e.length===0)return[];const n=new Map;for(const r of e){const a=r.name.replace(/@.*$/,"").trim(),s=n.get(a);if(s)s.allCodes.push(String(r.id));else{const o=r.filament_type||String(r.id);n.set(a,{code:o,name:a,displayName:a,isCustom:!1,allCodes:[o]})}}return Array.from(n.values()).sort((r,a)=>r.displayName.localeCompare(a.displayName))}function _Je(t,e,n){if(t.length>0){const r=[],a=new Map;for(const s of t)if(s.is_custom){const o=s.name.toUpperCase();(e.size===0||Array.from(e).some(c=>o.includes(c))||!o.includes("@"))&&r.push({code:s.setting_id,name:s.name,displayName:`${s.name} (Custom)`,isCustom:!0,allCodes:[s.setting_id]})}else{const o=s.name.replace(/@.*$/,"").trim(),l=a.get(o);l?l.allCodes.push(s.setting_id):a.set(o,{code:s.setting_id,name:o,displayName:o,isCustom:!1,allCodes:[s.setting_id]})}return[...r,...Array.from(a.values())].sort((s,o)=>s.displayName.localeCompare(o.displayName))}if(n&&n.length>0){const r=SJe(n);if(r.length>0)return r}return vJe}function NJe(t,e){if(!t)return;let n=e.find(r=>r.code===t);if(n||(n=e.find(r=>r.allCodes.includes(t))),!n){const r=t.toLowerCase();n=e.find(a=>a.code.toLowerCase()===r||a.allCodes.some(s=>s.toLowerCase()===r))}return n}function CJe(){try{const t=localStorage.getItem($ie);if(t)return JSON.parse(t)}catch{}return[]}function kJe(t,e){const n=e.filter(a=>a.hex.toUpperCase()!==t.hex.toUpperCase()),r=[t,...n].slice(0,yJe);try{localStorage.setItem($ie,JSON.stringify(r))}catch{}return r}function Ej(t,e){if(!e.material)return!1;const r=(t.name||"").replace(/^High Flow[_\s]+/i,"").replace(/^Standard[_\s]+/i,"").replace(/^HF[_\s]+/i,"").replace(/^S[_\s]+/i,"").trim(),a=Rb(r);return!(!(a.material.toUpperCase()===e.material.toUpperCase())||e.brand&&!(a.brand.toLowerCase().includes(e.brand.toLowerCase())||e.brand.toLowerCase().includes(a.brand.toLowerCase()))||e.subtype&&!(a.variant.toLowerCase().includes(e.subtype.toLowerCase())||e.subtype.toLowerCase().includes(a.variant.toLowerCase())||r.toLowerCase().includes(e.subtype.toLowerCase())))}function AJe({formData:t,updateField:e,cloudAuthenticated:n,loadingCloudPresets:r,presetInputValue:a,setPresetInputValue:s,selectedPresetOption:o,filamentOptions:l,availableBrands:c,availableMaterials:u}){const{t:d}=Ut(),[h,f]=w.useState(!1),[p,x]=w.useState(!1),[v,g]=w.useState(!1),[y,_]=w.useState(!1),[N,k]=w.useState(""),[A,M]=w.useState(""),[C,j]=w.useState(""),[P,E]=w.useState(String(t.label_weight)),[B,O]=w.useState(!1),U=w.useRef(null),R=w.useRef(null),V=w.useRef(null),G=w.useRef(null);w.useEffect(()=>{const W=ee=>{U.current&&!U.current.contains(ee.target)&&f(!1),G.current&&!G.current.contains(ee.target)&&_(!1),R.current&&!R.current.contains(ee.target)&&x(!1),V.current&&!V.current.contains(ee.target)&&g(!1)};return document.addEventListener("mousedown",W),()=>document.removeEventListener("mousedown",W)},[]);const z=w.useMemo(()=>{if(!a)return l;const W=a.toLowerCase();return l.filter(ee=>ee.displayName.toLowerCase().includes(W)||ee.code.toLowerCase().includes(W))},[l,a]),K=w.useMemo(()=>{if(!N)return c;const W=N.toLowerCase();return c.filter(J=>J.toLowerCase().includes(W)).sort((J,ye)=>{const me=J.toLowerCase()===W,te=ye.toLowerCase()===W;return me&&!te?-1:!me&&te?1:J.localeCompare(ye)})},[c,N]),Y=w.useMemo(()=>{if(!A)return lv;const W=A.toLowerCase();return lv.filter(ee=>ee.toLowerCase().includes(W))},[A]),ae=w.useMemo(()=>{if(!C)return u;const W=C.toLowerCase();return u.filter(J=>J.toLowerCase().includes(W)).sort((J,ye)=>{const me=J.toLowerCase()===W,te=ye.toLowerCase()===W;return me&&!te?-1:!me&&te?1:J.localeCompare(ye)})},[C,u]);w.useEffect(()=>{B||E(String(t.label_weight))},[t.label_weight,B]);const $=W=>{e("slicer_filament",W.code),s(W.displayName),f(!1);const ee=Rb(W.name);ee.material&&e("material",ee.material),ee.brand&&e("brand",ee.brand),ee.variant&&e("subtype",ee.variant)};return i.jsxs("div",{className:"space-y-4",children:[i.jsx("div",{className:"flex items-center gap-2 text-xs text-bambu-gray",children:r?i.jsxs(i.Fragment,{children:[i.jsx(it,{className:"w-3 h-3 animate-spin"})," ",d("inventory.loadingPresets")]}):n?i.jsxs(i.Fragment,{children:[i.jsx(zb,{className:"w-3 h-3 text-bambu-green"})," ",d("inventory.cloudConnected")]}):i.jsxs(i.Fragment,{children:[i.jsx(yhe,{className:"w-3 h-3"})," ",d("inventory.cloudNotConnected")]})}),i.jsxs("div",{children:[i.jsxs("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:[d("inventory.slicerPreset")," *"]}),i.jsxs("div",{className:"relative",ref:U,children:[i.jsx(kr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50 pointer-events-none"}),i.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:d("inventory.searchPresets"),value:a,onChange:W=>{s(W.target.value),f(!0)},onFocus:()=>{f(!0),s("")}}),h&&i.jsx("div",{className:"absolute z-50 w-full mt-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-lg max-h-64 overflow-y-auto",children:z.length===0?i.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:d("inventory.noPresetsFound")}):z.map(W=>i.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 ${o?.code===W.code?"bg-bambu-green/10 text-bambu-green":"text-white"}`,onClick:()=>$(W),children:[i.jsx("span",{className:"truncate",children:W.displayName}),i.jsx("span",{className:"font-mono text-xs text-bambu-gray ml-2 shrink-0",children:W.code})]},W.code))})]}),o&&i.jsxs("div",{className:"mt-1 text-xs text-bambu-gray",children:[d("inventory.selectedPreset"),": ",i.jsx("span",{className:"font-mono text-bambu-green",children:o.code})]})]}),i.jsxs("div",{children:[i.jsxs("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:[d("inventory.material")," *"]}),i.jsxs("div",{className:"relative",ref:G,children:[i.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:d("inventory.selectMaterial"),value:y?C:t.material,onChange:W=>{j(W.target.value),_(!0)},onFocus:()=>{_(!0),j("")}}),i.jsx(Un,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50 pointer-events-none"}),y&&i.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?i.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:d("inventory.noResults")}):ae.map(W=>i.jsx("button",{type:"button",className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary ${t.material===W?"bg-bambu-green/10 text-bambu-green":"text-white"}`,onClick:()=>{e("material",W),_(!1),j("")},children:W},W)),C&&!ae.includes(C)&&i.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",C),_(!1),j("")},children:d("inventory.useCustomMaterial",{material:C})})]})]})]}),i.jsxs("div",{children:[i.jsxs("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:[d("inventory.brand")," *"]}),i.jsxs("div",{className:"relative",ref:R,children:[i.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:d("inventory.searchBrand"),value:p?N:t.brand,onChange:W=>{k(W.target.value),x(!0)},onFocus:()=>{x(!0),k("")}}),i.jsx(Un,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50 pointer-events-none"}),p&&i.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:[K.length===0?i.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:d("inventory.noResults")}):K.map(W=>i.jsx("button",{type:"button",className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary ${t.brand===W?"bg-bambu-green/10 text-bambu-green":"text-white"}`,onClick:()=>{e("brand",W),x(!1),k("")},children:W},W)),N&&!K.includes(N)&&i.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",N),x(!1),k("")},children:d("inventory.useCustomBrand",{brand:N})})]})]})]}),i.jsxs("div",{children:[i.jsxs("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:[d("inventory.subtype")," *"]}),i.jsxs("div",{className:"relative",ref:V,children:[i.jsx("input",{type:"text",value:v?A:t.subtype,onChange:W=>{M(W.target.value),g(!0)},onFocus:()=>{g(!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"}),i.jsx(Un,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50 pointer-events-none"}),v&&i.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:[Y.length===0?i.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:d("inventory.noResults")}):Y.map(W=>i.jsx("button",{type:"button",className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary ${t.subtype===W?"bg-bambu-green/10 text-bambu-green":"text-white"}`,onClick:()=>{e("subtype",W),g(!1),M("")},children:W},W)),A&&!lv.some(W=>W.toLowerCase()===A.toLowerCase().trim())&&i.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",A),g(!1),M("")},children:d("inventory.useCustomBrand",{brand:A})})]})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:d("inventory.labelWeight")}),i.jsxs("div",{className:"relative",children:[i.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:P,min:0,onFocus:()=>O(!0),onChange:W=>E(W.target.value),onBlur:()=>{O(!1);const W=P.trim(),ee=Number(W);if(!W||!Number.isFinite(ee)||ee<0){E(String(t.label_weight));return}const J=Math.round(ee);e("label_weight",J),E(String(J))}}),i.jsx("span",{className:"absolute right-2 top-1/2 -translate-y-1/2 text-xs text-bambu-gray",children:"g"})]})]})]})}function TJe({formData:t,updateField:e,recentColors:n,onColorUsed:r,catalogColors:a}){const{t:s}=Ut(),[o,l]=w.useState(!1),[c,u]=w.useState(""),d=t.rgba.replace("#","").substring(0,6),h=y=>d.toUpperCase()===y.toUpperCase(),f=(y,_)=>{e("rgba",y.toUpperCase()+"FF"),e("color_name",_),r({name:_,hex:y})},p=w.useMemo(()=>{if(a.length===0)return[];const y=t.brand?.trim(),_=t.material?.toLowerCase().trim(),N=t.subtype?.toLowerCase().trim();if(!y&&!_)return[];const k=y?y.toLowerCase().split(/[\s\-_]+/).filter(C=>C.length>=2):[],A=C=>{if(k.length===0)return!0;const j=C.toLowerCase();return k.some(P=>j.includes(P))};if(y&&!_){const C=a.filter(j=>A(j.manufacturer));if(C.length>0)return C.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}))}const M=_&&N?`${_} ${N}`:"";if(M){const C=a.filter(P=>A(P.manufacturer)&&P.material?.toLowerCase()===M);if(C.length>0)return C.map(P=>({name:P.color_name,hex:P.hex_color.replace("#","").substring(0,6),manufacturer:P.manufacturer,material:typeof P.material=="string"?P.material:void 0}));const j=M.replace(/\+$/,"");if(j!==M){const P=a.filter(E=>A(E.manufacturer)&&E.material?.toLowerCase()===j);if(P.length>0)return P.map(E=>({name:E.color_name,hex:E.hex_color.replace("#","").substring(0,6),manufacturer:E.manufacturer,material:typeof E.material=="string"?E.material:void 0}))}}if(_){const C=a.filter(j=>A(j.manufacturer)&&(!j.material||j.material.toLowerCase().startsWith(_)));if(C.length>0)return C.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}))}return[]},[a,t.brand,t.material,t.subtype]),x=w.useMemo(()=>{if(!c)return p;if(p.length===0)return[];const y=c.toLowerCase();return p.filter(N=>N.name.toLowerCase().includes(y)||(N.manufacturer?.toLowerCase().includes(y)??!1)||(N.material?.toLowerCase().includes(y)??!1))},[c,p]),v=p.length>0,g=w.useMemo(()=>c?rK.filter(y=>y.name.toLowerCase().includes(c.toLowerCase())):o?rK:Hie,[c,o]);return i.jsxs("div",{className:"space-y-3",children:[i.jsx("div",{className:"h-10 rounded-lg border border-bambu-dark-tertiary",style:{backgroundColor:`#${d}`}}),n.length>0&&i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-bambu-gray shrink-0",children:[i.jsx(Gn,{className:"w-3 h-3"}),i.jsx("span",{children:s("inventory.recentColors")})]}),i.jsx("div",{className:"flex flex-wrap gap-1.5",children:n.map(y=>i.jsx("button",{type:"button",onClick:()=>f(y.hex,y.name),className:`w-6 h-6 rounded border-2 transition-all hover:scale-110 ${h(y.hex)?"border-bambu-green ring-1 ring-bambu-green/30 scale-110":"border-bambu-dark-tertiary"}`,style:{backgroundColor:`#${y.hex}`},title:y.name},y.hex))})]}),i.jsxs("div",{className:"relative",children:[i.jsx(kr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50 pointer-events-none"}),i.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:y=>u(y.target.value)})]}),v?i.jsxs("div",{className:"space-y-1.5",children:[i.jsx("span",{className:"text-xs text-bambu-gray",children:c?s("inventory.searchResults"):`${t.brand}${t.material?` ${t.material}`:""}`}),i.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[x.map(y=>i.jsx("button",{type:"button",onClick:()=>f(y.hex,y.name),className:`w-6 h-6 rounded border-2 transition-all hover:scale-110 hover:z-20 relative group ${h(y.hex)?"border-bambu-green ring-1 ring-bambu-green/30 scale-110":"border-bambu-dark-tertiary"}`,style:{backgroundColor:`#${y.hex}`},title:y.manufacturer&&y.material?`${y.name} (${y.manufacturer} — ${y.material})`:y.manufacturer?`${y.name} (${y.manufacturer})`:y.name,children:i.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:y.manufacturer&&y.material?`${y.name} (${y.manufacturer} — ${y.material})`:y.manufacturer?`${y.name} (${y.manufacturer})`:y.name})},`${y.hex}-${y.name}-${y.manufacturer??""}`)),x.length===0&&i.jsx("p",{className:"text-sm text-bambu-gray py-1",children:s("inventory.noColorsFound")})]})]}):i.jsxs("div",{className:"space-y-1.5",children:[i.jsxs("div",{className:"flex items-center justify-between text-xs text-bambu-gray",children:[i.jsx("span",{children:s(c?"inventory.searchResults":o?"inventory.allColors":"inventory.commonColors")}),!c&&i.jsx("button",{type:"button",onClick:()=>l(!o),className:"flex items-center gap-1 hover:text-white transition-colors",children:o?i.jsxs(i.Fragment,{children:[s("inventory.showLess")," ",i.jsx(yl,{className:"w-3 h-3"})]}):i.jsxs(i.Fragment,{children:[s("inventory.showAll")," ",i.jsx(Un,{className:"w-3 h-3"})]})})]}),i.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[g.map(y=>i.jsx("button",{type:"button",onClick:()=>f(y.hex,y.name),className:`w-6 h-6 rounded border-2 transition-all hover:scale-110 hover:z-20 relative group ${h(y.hex)?"border-bambu-green ring-1 ring-bambu-green/30 scale-110":"border-bambu-dark-tertiary"}`,style:{backgroundColor:`#${y.hex}`},title:y.name,children:i.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:y.name})},y.hex)),g.length===0&&i.jsx("p",{className:"text-sm text-bambu-gray py-1",children:s("inventory.noColorsFound")})]})]}),i.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:s("inventory.colorName")}),i.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:y=>e("color_name",y.target.value)})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:s("inventory.hexColor")}),i.jsxs("div",{className:"flex gap-2",children:[i.jsxs("div",{className:"relative flex-1",children:[i.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-bambu-gray",children:"#"}),i.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:d.toUpperCase(),onChange:y=>{const _=y.target.value.replace("#","").replace(/[^0-9A-Fa-f]/g,"");_.length<=8&&e("rgba",_.toUpperCase()+(_.length<=6?"FF":""))}})]}),i.jsx("input",{type:"color",className:"w-11 h-[38px] rounded-lg cursor-pointer border border-bambu-dark-tertiary shrink-0 bg-transparent",value:`#${d}`,onChange:y=>{const _=y.target.value.replace("#","").toUpperCase();e("rgba",_+"FF")},title:s("inventory.pickColor")})]})]})]})]})}function MJe({catalog:t,value:e,onChange:n,catalogId:r,onCatalogIdChange:a}){const{t:s}=Ut(),[o,l]=w.useState(!1),[c,u]=w.useState(""),d=w.useRef(null),h=w.useRef(null);w.useEffect(()=>{const v=g=>{d.current&&!d.current.contains(g.target)&&l(!1)};return document.addEventListener("mousedown",v),()=>document.removeEventListener("mousedown",v)},[]),w.useEffect(()=>{if(t.length===0)return;const v=t.filter(g=>g.weight===e);if(r){const g=t.find(y=>y.id===r);if(g&&g.weight===e)return}v.length===1?a(v[0].id):v.length===0&&r!==null&&a(null)},[e,t,r,a]);const f=w.useMemo(()=>{if(!c)return t;const v=c.toLowerCase();return t.filter(g=>g.name.toLowerCase().includes(v)||g.weight.toString().includes(v))},[t,c]),p=w.useMemo(()=>t.filter(v=>v.weight===e),[t,e]),x=w.useMemo(()=>{if(o)return c;if(r){const v=t.find(g=>g.id===r);if(v)return v.name}return p.length>0?p[0].name:""},[o,c,r,t,p]);return i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:i.jsxs("span",{className:"flex items-center gap-2",children:[i.jsx(Bfe,{className:"w-3.5 h-3.5 text-bambu-gray"}),s("inventory.coreWeight")]})}),i.jsxs("div",{className:"flex gap-2 items-center",children:[i.jsxs("div",{className:"flex-1 min-w-0 relative",ref:d,children:[i.jsx("input",{ref:h,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:x,onFocus:()=>{l(!0),u("")},onChange:v=>{u(v.target.value),l(!0)}}),o&&i.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:f.length===0?i.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:s("inventory.noResults")}):f.map(v=>i.jsxs("button",{type:"button",className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex justify-between items-center ${(r?v.id===r:v.weight===e)?"bg-bambu-green/10 text-bambu-green":"text-white"}`,onClick:()=>{a(v.id),n(v.weight),l(!1),u("")},children:[i.jsx("span",{className:"truncate",children:v.name}),i.jsxs("span",{className:"font-mono text-xs text-bambu-gray ml-2 shrink-0",children:[v.weight,"g"]})]},v.id))})]}),i.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[i.jsx("input",{type:"number",className:"w-16 px-2 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm text-center font-mono focus:outline-none focus:border-bambu-green",value:e,min:0,max:2e3,onChange:v=>{const g=parseInt(v.target.value);!isNaN(g)&&g>=0&&n(g)}}),i.jsx("span",{className:"text-bambu-gray text-sm",children:"g"})]})]})]})}function PJe({formData:t,updateField:e,spoolCatalog:n,currencySymbol:r}){const{t:a}=Ut(),{showToast:s}=cn(),[o,l]=w.useState(""),[c,u]=w.useState(!1),[d,h]=w.useState(""),[f,p]=w.useState(!1),x=Math.max(0,t.label_weight-t.weight_used),v=t.core_weight+x;return w.useEffect(()=>{c||l(String(v))},[c,v]),w.useEffect(()=>{f||h(String(x))},[f,x]),i.jsxs("div",{className:"space-y-4",children:[i.jsx(MJe,{catalog:n,value:t.core_weight,onChange:g=>e("core_weight",g),catalogId:t.core_weight_catalog_id,onCatalogIdChange:g=>e("core_weight_catalog_id",g)}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:a("inventory.currentWeight")}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsxs("div",{className:"relative flex-1",children:[i.jsx("input",{type:"number",value:d,min:0,max:t.label_weight,onFocus:()=>p(!0),onChange:g=>{h(g.target.value)},onBlur:()=>{p(!1);const g=d.trim(),y=Number(g);if(!g||!Number.isFinite(y)||y<0||y>t.label_weight){h(String(x));return}const _=Math.round(y);e("weight_used",Math.max(0,t.label_weight-_)),h(String(_))},className:"w-full px-3 py-2 pr-7 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:outline-none focus:border-bambu-green"}),i.jsx("span",{className:"absolute right-2 top-1/2 -translate-y-1/2 text-xs text-bambu-gray",children:"g"})]}),i.jsxs("span",{className:"text-xs text-bambu-gray shrink-0",children:["/ ",t.label_weight,"g"]})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:a("inventory.measuredWeight")}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsxs("div",{className:"relative flex-1",children:[i.jsx("input",{type:"number",value:o,min:0,onFocus:()=>u(!0),onChange:g=>{l(g.target.value)},onBlur:()=>{u(!1);const g=o.trim(),y=Number(g),_=t.core_weight,N=t.core_weight+t.label_weight;if(!g||!Number.isFinite(y)||y<_||y>N){s(a("inventory.measuredWeightError",{min:_,max:N}),"error"),l(String(v));return}const k=Math.round(y),A=Math.max(0,Math.min(t.label_weight,k-t.core_weight));e("weight_used",Math.max(0,t.label_weight-A)),l(String(k))},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"}),i.jsx("span",{className:"absolute right-2 top-1/2 -translate-y-1/2 text-xs text-bambu-gray",children:"g"})]}),i.jsxs("span",{className:"text-xs text-bambu-gray shrink-0",children:["/ ",t.core_weight+t.label_weight,"g"]})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:a("inventory.costPerKg","Cost per kg")}),i.jsx("div",{className:"flex items-center gap-2",children:i.jsxs("div",{className:"relative flex-1",children:[i.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-bambu-gray text-sm pointer-events-none",children:r}),i.jsx("input",{type:"number",value:t.cost_per_kg??"",min:0,step:.01,placeholder:"0.00",onChange:g=>{const y=g.target.value===""?null:parseFloat(g.target.value);e("cost_per_kg",y)},style:{paddingLeft:`${Math.max(2,r.length*.6+1)}rem`},className:"w-full py-2 pr-3 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:outline-none focus:border-bambu-green"})]})})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:a("inventory.note")}),i.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:a("inventory.notePlaceholder"),value:t.note,onChange:g=>e("note",g.target.value)})]})]})}function EJe({formData:t,printersWithCalibrations:e,selectedProfiles:n,setSelectedProfiles:r,expandedPrinters:a,setExpandedPrinters:s}){const{t:o}=Ut(),l=f=>{s(p=>{const x=new Set(p);return x.has(f)?x.delete(f):x.add(f),x})},c=(f,p,x)=>{const v=`${f}:${p}:${x??"null"}`,g=`${f}:${x??"null"}`;r(y=>{const _=new Set(y);if(_.has(v))_.delete(v);else{for(const N of Array.from(_)){const k=N.split(":");`${k[0]}:${k[2]}`===g&&_.delete(N)}_.add(v)}return _})},u=()=>{const f=new Set;for(const{printer:p,calibrations:x}of e){if(!p.connected)continue;const v=x.filter(y=>Ej(y,t)),g=new Map;for(const y of v){const _=`${y.extruder_id??"null"}`;g.has(_)||g.set(_,[]),g.get(_).push(y)}for(const[y,_]of g)if(_.length>0){const k=[..._].sort((A,M)=>M.k_value-A.k_value)[0];f.add(`${p.id}:${k.cali_idx}:${y}`)}}r(f)};if(!t.material)return i.jsx("div",{className:"p-6 bg-bambu-dark rounded-lg text-center",children:i.jsx("p",{className:"text-bambu-gray",children:o("inventory.selectMaterialFirst")})});if(e.length===0)return i.jsx("div",{className:"p-6 bg-bambu-dark rounded-lg text-center",children:i.jsx("p",{className:"text-bambu-gray",children:o("inventory.noPrintersConfigured")})});const d=e.reduce((f,{printer:p,calibrations:x})=>p.connected?f+x.filter(v=>Ej(v,t)).length:f,0),h=(f,p)=>{const x=`${f.id}:${p.cali_idx}:${p.extruder_id??"null"}`,v=n.has(x);return i.jsxs("label",{className:`flex items-center gap-3 p-3 rounded-lg cursor-pointer transition-all border ${v?"bg-bambu-green/10 border-bambu-green/30":"bg-bambu-dark border-transparent hover:bg-bambu-dark/80"}`,children:[i.jsx("input",{type:"checkbox",checked:v,onChange:()=>c(String(f.id),p.cali_idx,p.extruder_id),className:"w-4 h-4 rounded border-bambu-dark-tertiary text-bambu-green focus:ring-bambu-green"}),i.jsx("div",{className:"flex-1 min-w-0",children:i.jsx("span",{className:`text-sm font-medium ${v?"text-bambu-green":"text-white"}`,children:p.name||p.filament_id})}),i.jsx("div",{className:"flex items-center gap-2 shrink-0",children:i.jsxs("span",{className:"text-xs font-mono px-2 py-0.5 rounded bg-bambu-dark text-bambu-gray",children:["K=",p.k_value.toFixed(3)]})})]},`${p.cali_idx}-${p.extruder_id}`)};return i.jsxs("div",{className:"space-y-4",children:[i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("p",{className:"text-xs text-bambu-gray",children:[o("inventory.matchingFilter"),": ",t.brand||o("inventory.anyBrand")," / ",t.material," / ",t.subtype||o("inventory.anyVariant")]}),d>0&&i.jsxs("button",{type:"button",onClick:u,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:[i.jsx(lb,{className:"w-3.5 h-3.5"}),o("inventory.autoSelect")," (",d,")"]})]}),i.jsx("div",{className:"space-y-3",children:e.map(({printer:f,calibrations:p})=>{const x=a.has(String(f.id)),v=p.filter(k=>Ej(k,t)),g=v.length,y=v.some(k=>k.extruder_id!==void 0&&k.extruder_id!==null&&k.extruder_id>0),_=v.filter(k=>k.extruder_id===1),N=v.filter(k=>k.extruder_id===0||k.extruder_id===void 0||k.extruder_id===null);return i.jsxs("div",{className:"border border-bambu-dark-tertiary rounded-lg overflow-hidden",children:[i.jsxs("button",{type:"button",onClick:()=>l(String(f.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:[i.jsxs("div",{className:"flex items-center gap-3",children:[x?i.jsx(Un,{className:"w-4 h-4 text-bambu-gray"}):i.jsx(pi,{className:"w-4 h-4 text-bambu-gray"}),i.jsx("span",{className:"font-medium text-white",children:f.name}),g>0?i.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")]}):i.jsx("span",{className:"text-xs px-2 py-0.5 rounded-full bg-bambu-dark-tertiary text-bambu-gray",children:o("inventory.noMatches")})]}),i.jsx("span",{className:`text-xs px-2 py-1 rounded-full ${f.connected?"bg-green-500/20 text-green-500":"bg-bambu-gray/20 text-bambu-gray"}`,children:f.connected?o("inventory.connected"):o("inventory.offline")})]}),x&&i.jsx("div",{className:"px-4 py-3 space-y-3 bg-bambu-dark border-t border-bambu-dark-tertiary",children:f.connected?g===0?i.jsx("p",{className:"text-sm text-bambu-gray italic py-2",children:o("inventory.noKProfilesMatch")}):y?i.jsxs(i.Fragment,{children:[_.length>0&&i.jsxs("div",{className:"space-y-2",children:[i.jsx("p",{className:"text-xs font-medium text-bambu-gray uppercase tracking-wide",children:o("inventory.leftNozzle")}),i.jsx("div",{className:"space-y-2",children:_.map(k=>h(f,k))})]}),N.length>0&&i.jsxs("div",{className:"space-y-2",children:[i.jsx("p",{className:"text-xs font-medium text-bambu-gray uppercase tracking-wide",children:o("inventory.rightNozzle")}),i.jsx("div",{className:"space-y-2",children:N.map(k=>h(f,k))})]})]}):i.jsx("div",{className:"space-y-2",children:v.map(k=>h(f,k))}):i.jsx("p",{className:"text-sm text-bambu-gray italic py-2",children:o("inventory.printerOffline")})})]},f.id)})}),n.size>0&&i.jsx("div",{className:"p-3 bg-bambu-green/10 border border-bambu-green/30 rounded-lg",children:i.jsxs("p",{className:"text-sm text-white",children:[i.jsx("span",{className:"font-semibold",children:n.size})," ",o("inventory.profilesSelected")]})})]})}function jJe(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 DJe={completed:"text-bambu-green",failed:"text-red-400",aborted:"text-yellow-400"};function RJe({spoolId:t}){const{t:e}=Ut(),n=tn(),{showToast:r}=cn(),{data:a,isLoading:s}=Je({queryKey:["spool-usage",t],queryFn:()=>ne.getSpoolUsageHistory(t)}),o=ot({mutationFn:()=>ne.clearSpoolUsageHistory(t),onSuccess:()=>{n.invalidateQueries({queryKey:["spool-usage",t]}),r(e("inventory.historyCleared"),"success")}});return s?i.jsx("div",{className:"flex justify-center py-4",children:i.jsx(it,{className:"w-5 h-5 animate-spin text-bambu-green"})}):!a||a.length===0?i.jsxs("div",{className:"text-center py-4 text-bambu-gray text-sm",children:[i.jsx(Gn,{className:"w-5 h-5 mx-auto mb-2 opacity-50"}),e("inventory.noUsageHistory")]}):i.jsxs("div",{className:"space-y-2",children:[i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsx("h4",{className:"text-sm font-medium text-white",children:e("inventory.usageHistory")}),i.jsxs(Ce,{variant:"ghost",size:"sm",onClick:()=>o.mutate(),disabled:o.isPending,className:"text-xs text-bambu-gray hover:text-red-400",children:[i.jsx(Jt,{className:"w-3 h-3 mr-1"}),e("inventory.clearHistory")]})]}),i.jsx("div",{className:"max-h-48 overflow-y-auto space-y-1",children:a.map(l=>i.jsxs("div",{className:"flex items-center justify-between p-2 rounded bg-bambu-dark/50 text-xs",children:[i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsx("span",{className:"text-bambu-gray",children:jJe(l.created_at)}),l.print_name&&i.jsx("span",{className:"text-white ml-2 truncate",title:l.print_name,children:l.print_name})]}),i.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0 ml-2",children:[i.jsxs("span",{className:"text-white font-medium",children:[l.weight_used.toFixed(1),"g"]}),i.jsxs("span",{className:"text-bambu-gray",children:["(",l.percent_used,"%)"]}),i.jsx("span",{className:DJe[l.status]||"text-bambu-gray",children:l.status})]})]},l.id))})]})}function FJe({isOpen:t,onClose:e,spool:n,printersWithCalibrations:r=[],currencySymbol:a}){const{t:s}=Ut(),o=tn(),{showToast:l}=cn(),c=!!n,[u,d]=w.useState(nK),[h,f]=w.useState({}),[p,x]=w.useState("filament"),[v,g]=w.useState(!1),[y,_]=w.useState(!1),[N,k]=w.useState(!1),[A,M]=w.useState([]),[C,j]=w.useState(""),[P,E]=w.useState([]),[B,O]=w.useState([]),[U,R]=w.useState([]),[V,G]=w.useState([]),[z,K]=w.useState([]),[Y,ae]=w.useState(new Set),[$,W]=w.useState(new Set),ee=r.length>0?r:z,J=w.useMemo(()=>Y.size,[Y]);w.useEffect(()=>{G(CJe())},[]),w.useEffect(()=>{t&&((async()=>{k(!0);try{const Q=await ne.getCloudStatus();if(_(Q.is_authenticated),Q.is_authenticated){const L=await ne.getFilamentPresets();M(L)}}catch(Q){console.error("Failed to fetch cloud presets:",Q),_(!1)}finally{k(!1)}})(),ne.getSpoolCatalog().then(E).catch(console.error),ne.getColorCatalog().then(R).catch(console.error),ne.getLocalPresets().then(Q=>O(Q.filament)).catch(console.error),r.length===0&&(async()=>{try{const Q=await ne.getPrinters(),L=await Promise.all(Q.map(H=>ne.getPrinterStatus(H.id).catch(()=>null))),D=[];for(let H=0;H({cali_idx:qe.slot_id,filament_id:qe.filament_id,setting_id:qe.setting_id||"",name:qe.name,k_value:parseFloat(qe.k_value)||0,n_coef:parseFloat(qe.n_coef)||0,extruder_id:qe.extruder_id,nozzle_diameter:qe.nozzle_diameter}))}catch{}D.push({printer:{...he,connected:fe},calibrations:ze})}K(D)}catch(Q){console.error("Failed to fetch printer calibrations:",Q)}})())},[t,r.length]);const ye=w.useMemo(()=>_Je(A,new Set,B),[A,B]),me=w.useMemo(()=>{const pe=wJe(A,B),Q=U.map(D=>D.manufacturer?.trim()).filter(D=>!!D),L=new Set([...pe,...Q]);return Array.from(L).sort((D,H)=>D.localeCompare(H))},[A,B,U]),te=w.useMemo(()=>{const pe=U.map(L=>L.material?.trim()).filter(L=>!!L),Q=new Set([...gJe,...pe]);return Array.from(Q).sort((L,D)=>L.localeCompare(D))},[U]),je=w.useMemo(()=>{const pe=[];for(const Q of U){const L=Q.manufacturer?.trim(),D=Q.material?.trim();L&&D&&pe.push({brand:L,material:D})}for(const Q of A){const L=Rb(Q.name);L.brand&&L.material&&pe.push({brand:L.brand,material:L.material})}for(const Q of B){const L=Rb(Q.name),D=Q.filament_vendor?.trim()||L.brand,H=L.material;D&&H&&pe.push({brand:D,material:H})}return pe},[A,U,B]),ue=w.useMemo(()=>{const pe=new Map;for(const Q of je){const L=Q.brand.toLowerCase(),D=Q.material.toLowerCase();pe.has(L)||pe.set(L,new Set),pe.get(L).add(D)}return pe},[je]),oe=w.useMemo(()=>{const pe=new Map;for(const Q of je){const L=Q.brand.toLowerCase(),D=Q.material.toLowerCase();pe.has(D)||pe.set(D,new Set),pe.get(D).add(L)}return pe},[je]),_e=w.useMemo(()=>{if(!u.material)return me;const pe=u.material.toLowerCase(),Q=oe.get(pe);return!Q||Q.size===0?me:me.filter(L=>Q.has(L.toLowerCase()))},[me,u.material,oe]),se=w.useMemo(()=>{if(!u.brand)return te;const pe=u.brand.toLowerCase(),Q=ue.get(pe);return!Q||Q.size===0?te:te.filter(L=>Q.has(L.toLowerCase()))},[te,u.brand,ue]),Oe=w.useMemo(()=>NJe(u.slicer_filament,ye),[u.slicer_filament,ye]);w.useEffect(()=>{if(t){if(n)if(d({material:n.material||"",subtype:n.subtype||"",brand:n.brand||"",color_name:n.color_name||"",rgba:n.rgba||"808080FF",label_weight:n.label_weight||1e3,core_weight:n.core_weight||250,core_weight_catalog_id:n.core_weight_catalog_id??null,weight_used:n.weight_used||0,slicer_filament:n.slicer_filament||"",note:n.note||"",cost_per_kg:n.cost_per_kg??null}),j(n.slicer_filament_name||n.slicer_filament||""),n.k_profiles&&n.k_profiles.length>0){const pe=new Set;for(const Q of n.k_profiles)Q.cali_idx!==null&&Q.cali_idx!==void 0&&pe.add(`${Q.printer_id}:${Q.cali_idx}:${Q.extruder??"null"}`);ae(pe)}else ae(new Set);else d(nK),j(""),ae(new Set);f({}),x("filament"),g(!1)}},[t,n]),w.useEffect(()=>{t&&ee.length>0&&W(new Set(ee.map(pe=>String(pe.printer.id))))},[t,ee]);const q=(pe,Q)=>{d(L=>({...L,[pe]:Q})),pe==="weight_used"&&g(!0),h[pe]&&f(L=>({...L,[pe]:void 0}))},X=pe=>{G(Q=>kJe(pe,Q))},de=ot({mutationFn:pe=>ne.createSpool(pe),onSuccess:async pe=>{Y.size>0&&pe?.id&&await ie(pe.id),await o.invalidateQueries({queryKey:["inventory-spools"]}),l(s("inventory.spoolCreated"),"success"),e()},onError:pe=>{l(pe.message,"error")}}),Z=ot({mutationFn:pe=>ne.updateSpool(n.id,pe),onSuccess:async()=>{n?.id&&await ie(n.id),await o.invalidateQueries({queryKey:["inventory-spools"]}),l(s("inventory.spoolUpdated"),"success"),e()},onError:pe=>{l(pe.message,"error")}}),ie=async pe=>{if(Y.size===0){try{await ne.saveSpoolKProfiles(pe,[])}catch{}return}const Q=[];for(const L of Y){const[D,H,he]=L.split(":"),be=parseInt(D),fe=parseInt(H),ze=he==="null"?0:parseInt(he),Ie=ee.find(qe=>qe.printer.id===be);if(Ie){const qe=Ie.calibrations.find(tt=>tt.cali_idx===fe);qe&&Q.push({printer_id:be,extruder:ze,nozzle_diameter:qe.nozzle_diameter||"0.4",k_value:qe.k_value,name:qe.name||null,cali_idx:qe.cali_idx,setting_id:qe.setting_id||null})}}if(Q.length>0)try{await ne.saveSpoolKProfiles(pe,Q)}catch(L){console.error("Failed to save K-profiles:",L)}};if(w.useEffect(()=>{if(!t)return;const pe=Q=>{Q.key==="Escape"&&e()};return document.addEventListener("keydown",pe),()=>document.removeEventListener("keydown",pe)},[t,e]),!t)return null;const le=()=>{const pe=pJe(u);if(!pe.isValid){f(pe.errors),(pe.errors.slicer_filament||pe.errors.material||pe.errors.brand||pe.errors.subtype)&&x("filament");return}const Q=Oe?.displayName||C||null,L={material:u.material,subtype:u.subtype||null,brand:u.brand||null,color_name:u.color_name||null,rgba:u.rgba||null,label_weight:u.label_weight,core_weight:u.core_weight,core_weight_catalog_id:u.core_weight_catalog_id,slicer_filament:u.slicer_filament||null,slicer_filament_name:Q,nozzle_temp_min:null,nozzle_temp_max:null,note:u.note||null,cost_per_kg:u.cost_per_kg};(!c||v)&&(L.weight_used=u.weight_used),c?Z.mutate(L):de.mutate(L)},Fe=de.isPending||Z.isPending;return i.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[i.jsx("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-sm",onClick:e}),i.jsxs("div",{className:"relative w-full max-w-lg mx-4 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl max-h-[90vh] flex flex-col",children:[i.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary flex-shrink-0",children:[i.jsx("h2",{className:"text-lg font-semibold text-white",children:s(c?"inventory.editSpool":"inventory.addSpool")}),i.jsx("button",{onClick:e,className:"p-1 text-bambu-gray hover:text-white rounded transition-colors",children:i.jsx(Ft,{className:"w-5 h-5"})})]}),i.jsxs("div",{className:"flex border-b border-bambu-dark-tertiary flex-shrink-0",children:[i.jsxs("button",{onClick:()=>x("filament"),className:`flex-1 px-4 py-2.5 text-sm font-medium flex items-center justify-center gap-2 transition-colors ${p==="filament"?"text-bambu-green border-b-2 border-bambu-green":"text-bambu-gray hover:text-white"}`,children:[i.jsx(VC,{className:"w-4 h-4"}),s("inventory.filamentInfoTab")]}),i.jsxs("button",{onClick:()=>x("pa-profile"),className:`flex-1 px-4 py-2.5 text-sm font-medium flex items-center justify-center gap-2 transition-colors ${p==="pa-profile"?"text-bambu-green border-b-2 border-bambu-green":"text-bambu-gray hover:text-white"}`,children:[i.jsx(Ede,{className:"w-4 h-4"}),s("inventory.paProfileTab"),J>0&&i.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded-full bg-bambu-green/20 text-bambu-green",children:J})]})]}),i.jsx("div",{className:"p-4 overflow-y-auto flex-1",style:{scrollbarGutter:"stable"},children:p==="filament"?i.jsxs("div",{className:"space-y-6",children:[i.jsxs("div",{children:[i.jsx("h3",{className:"text-sm font-semibold text-bambu-gray uppercase tracking-wide mb-3",children:s("inventory.filamentInfo")}),i.jsx(AJe,{formData:u,updateField:q,cloudAuthenticated:y,loadingCloudPresets:N,presetInputValue:C,setPresetInputValue:j,selectedPresetOption:Oe,filamentOptions:ye,availableBrands:_e,availableMaterials:se}),h.slicer_filament&&i.jsx("p",{className:"mt-1 text-xs text-red-400",children:h.slicer_filament}),h.material&&i.jsx("p",{className:"mt-1 text-xs text-red-400",children:h.material}),h.brand&&i.jsx("p",{className:"mt-1 text-xs text-red-400",children:h.brand}),h.subtype&&i.jsx("p",{className:"mt-1 text-xs text-red-400",children:h.subtype})]}),i.jsxs("div",{children:[i.jsx("h3",{className:"text-sm font-semibold text-bambu-gray uppercase tracking-wide mb-3",children:s("inventory.color")}),i.jsx(TJe,{formData:u,updateField:q,recentColors:V,onColorUsed:X,catalogColors:U})]}),i.jsxs("div",{children:[i.jsx("h3",{className:"text-sm font-semibold text-bambu-gray uppercase tracking-wide mb-3",children:s("inventory.additional")}),i.jsx(PJe,{formData:u,updateField:q,spoolCatalog:P,currencySymbol:a})]}),c&&n&&i.jsx("div",{children:i.jsx(RJe,{spoolId:n.id})})]}):i.jsx(EJe,{formData:u,updateField:q,printersWithCalibrations:ee,selectedProfiles:Y,setSelectedProfiles:ae,expandedPrinters:$,setExpandedPrinters:W})}),i.jsxs("div",{className:"flex justify-end gap-2 p-4 border-t border-bambu-dark-tertiary flex-shrink-0",children:[i.jsx(Ce,{variant:"secondary",onClick:e,children:s("common.cancel")}),i.jsx(Ce,{onClick:le,disabled:Fe,children:Fe?i.jsxs(i.Fragment,{children:[i.jsx(it,{className:"w-4 h-4 animate-spin"}),s("common.saving")]}):i.jsxs(i.Fragment,{children:[i.jsx(ps,{className:"w-4 h-4"}),s(c?"common.save":"inventory.addSpool")]})})]})]})]})}function LJe({isOpen:t,onClose:e,columns:n,defaultColumns:r,onSave:a}){const{t:s}=Ut(),[o,l]=w.useState(n),[c,u]=w.useState(null),d=w.useRef(null);if(w.useEffect(()=>{t&&l(n.map(k=>({...k})))},[t,n]),w.useEffect(()=>{if(!t)return;const k=A=>{A.key==="Escape"&&e()};return window.addEventListener("keydown",k),()=>window.removeEventListener("keydown",k)},[t,e]),!t)return null;const h=k=>{l(A=>A.map((M,C)=>C===k?{...M,visible:!M.visible}:M))},f=(k,A)=>{A<0||A>=o.length||l(M=>{const C=[...M],[j]=C.splice(k,1);return C.splice(A,0,j),C})},p=(k,A)=>{d.current=A,u(A),k.dataTransfer.effectAllowed="move"},x=(k,A)=>{k.preventDefault(),k.dataTransfer.dropEffect="move";const M=d.current;M!==null&&M!==A&&(f(M,A),d.current=A,u(A))},v=k=>{k.preventDefault()},g=()=>{d.current=null,u(null)},y=()=>{l(r.map(k=>({...k})))},_=()=>{a(o),e()},N=o.filter(k=>k.visible).length;return i.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",onClick:e,children:i.jsx(vt,{className:"w-full max-w-md max-h-[80vh] flex flex-col",onClick:k=>k.stopPropagation(),children:i.jsxs(_t,{className:"p-6 flex flex-col min-h-0",children:[i.jsx("h3",{className:"text-lg font-semibold text-white mb-2",children:s("inventory.configureColumns")}),i.jsxs("p",{className:"text-sm text-bambu-gray mb-4",children:[s("inventory.configureColumnsDesc"),i.jsxs("span",{className:"ml-2 text-bambu-gray/60",children:["(",N," ",s("inventory.of")," ",o.length," ",s("inventory.visible"),")"]})]}),i.jsx("div",{className:"space-y-1 overflow-y-auto flex-1 min-h-0 pr-1",children:o.map((k,A)=>i.jsxs("div",{className:`flex items-center gap-2 p-2 rounded-lg border transition-colors ${c===A?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary bg-bambu-dark-tertiary/50"} ${k.visible?"":"opacity-50"}`,draggable:!0,onDragStart:M=>p(M,A),onDragOver:M=>x(M,A),onDrop:v,onDragEnd:g,children:[i.jsx("div",{className:"cursor-grab text-bambu-gray/50 hover:text-bambu-gray",children:i.jsx(Ph,{className:"w-4 h-4"})}),i.jsx("span",{className:"flex-1 font-medium text-sm text-white",children:k.label}),i.jsxs("div",{className:"flex items-center gap-0.5",children:[i.jsx("button",{onClick:()=>f(A,A-1),disabled:A===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:i.jsx(yl,{className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>f(A,A+1),disabled:A===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:i.jsx(Un,{className:"w-4 h-4"})})]}),i.jsx("button",{onClick:()=>h(A),className:`p-1.5 rounded transition-colors ${k.visible?"text-bambu-green hover:bg-bambu-green/10":"text-bambu-gray/50 hover:bg-bambu-dark-secondary"}`,title:k.visible?s("inventory.hideColumn"):s("inventory.showColumn"),children:k.visible?i.jsx(Ql,{className:"w-4 h-4"}):i.jsx(o0,{className:"w-4 h-4"})})]},k.id))}),i.jsxs("div",{className:"flex items-center gap-3 mt-4 pt-4 border-t border-bambu-dark-tertiary",children:[i.jsxs(Ce,{variant:"secondary",onClick:y,className:"mr-auto",children:[i.jsx(Fo,{className:"w-4 h-4"}),s("inventory.reset")]}),i.jsx(Ce,{variant:"secondary",onClick:e,children:s("inventory.cancel")}),i.jsx(Ce,{onClick:_,children:s("inventory.applyChanges")})]})]})})})}const Vie="bambuddy-inventory-columns",c1=[{id:"id",label:"#",visible:!0},{id:"added_time",label:"Added",visible:!0},{id:"encode_time",label:"Encoded",visible:!1},{id:"last_used_time",label:"Last Used",visible:!1},{id:"rgba",label:"Color",visible:!0},{id:"material",label:"Material",visible:!0},{id:"subtype",label:"Subtype",visible:!0},{id:"color_name",label:"Color Name",visible:!1},{id:"brand",label:"Brand",visible:!0},{id:"slicer_filament",label:"Slicer Filament",visible:!1},{id:"location",label:"Location",visible:!0},{id:"label_weight",label:"Label",visible:!0},{id:"net",label:"Net",visible:!0},{id:"gross",label:"Gross",visible:!1},{id:"added_full",label:"Full",visible:!1},{id:"used",label:"Used",visible:!1},{id:"printed_total",label:"Printed Total",visible:!1},{id:"printed_since_weight",label:"Printed Since Weight",visible:!1},{id:"note",label:"Note",visible:!1},{id:"pa_k",label:"PA(K)",visible:!0},{id:"tag_id",label:"Tag ID",visible:!1},{id:"data_origin",label:"Data Origin",visible:!1},{id:"tag_type",label:"Linked Tag Type",visible:!1},{id:"remaining",label:"Remaining",visible:!0},{id:"cost_per_kg",label:"Cost/kg",visible:!1}];function OJe(){try{const t=localStorage.getItem(Vie);if(t){const e=JSON.parse(t),n=new Set(c1.map(o=>o.id)),r=new Set(e.map(o=>o.id)),a=e.filter(o=>n.has(o.id)),s=c1.filter(o=>!r.has(o.id));return[...a,...s]}}catch{}return c1.map(t=>({...t}))}function IJe(t){try{localStorage.setItem(Vie,JSON.stringify(t))}catch{}}function Ru(t,e=!1){return e&&t>=1e3?`${(t/1e3).toFixed(1)}kg`:`${Math.round(t)}g`}const zJe={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 jj(t,e="system"){if(!t)return"-";const n=di(t);return n?o3(n,e):"-"}const UJe={id:()=>"#",added_time:()=>"Added",encode_time:()=>"Encoded",last_used_time:()=>"Last Used",rgba:t=>t("inventory.color"),material:t=>t("inventory.material"),subtype:t=>t("inventory.subtype"),color_name:t=>t("inventory.colorName"),brand:t=>t("inventory.brand"),slicer_filament:t=>t("inventory.slicerFilament"),location:()=>"Location",label_weight:t=>t("inventory.labelWeight"),net:t=>t("inventory.net"),gross:()=>"Gross",added_full:()=>"Full",used:t=>t("inventory.weightUsed"),printed_total:()=>"Printed Total",printed_since_weight:()=>"Printed Since Weight",note:t=>t("inventory.note"),pa_k:()=>"PA(K)",tag_id:()=>"Tag ID",data_origin:()=>"Data Origin",tag_type:()=>"Linked Tag Type",remaining:t=>t("inventory.remaining"),cost_per_kg:t=>t("inventory.costPerKg")},BJe={id:({spool:t})=>i.jsx("span",{className:"text-sm font-medium text-white",children:t.id}),added_time:({spool:t,dateFormat:e})=>i.jsx("span",{className:"text-sm text-bambu-gray",children:jj(t.created_at,e)}),encode_time:({spool:t,dateFormat:e})=>i.jsx("span",{className:"text-sm text-bambu-gray",children:jj(t.encode_time,e)}),last_used_time:({spool:t,dateFormat:e})=>i.jsx("span",{className:"text-sm text-bambu-gray",children:t.last_used?jj(t.last_used,e):"Never"}),rgba:({spool:t})=>i.jsx("div",{className:"flex items-center justify-center",children:i.jsx("span",{className:"w-5 h-5 rounded-full border border-white/20 flex-shrink-0",style:{backgroundColor:t.rgba?`#${t.rgba.substring(0,6)}`:"#808080"},title:t.rgba?`#${t.rgba.substring(0,6)}`:void 0})}),material:({spool:t})=>i.jsx("span",{className:"text-sm text-white",children:t.material}),subtype:({spool:t})=>i.jsx("span",{className:"text-sm text-bambu-gray",children:t.subtype||"-"}),color_name:({spool:t})=>i.jsx("span",{className:"text-sm text-bambu-gray",children:one(t.color_name,t.rgba)||"-"}),brand:({spool:t})=>i.jsx("span",{className:"text-sm text-bambu-gray",children:t.brand||"-"}),slicer_filament:({spool:t})=>i.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 i.jsx("span",{className:"text-sm text-bambu-gray",children:"-"});const r=n.printer_name||`Printer ${n.printer_id}`,a=n.ams_id===254||n.ams_id===255,s=!a&&n.ams_id>=128,o=cI(n.ams_id,n.tray_id,s,a);return i.jsxs("span",{className:"inline-flex items-center px-1.5 py-0.5 rounded text-xs font-medium bg-purple-500/20 text-purple-400",children:[r," ",o]})},label_weight:({spool:t})=>i.jsx("span",{className:"text-sm text-white",children:Ru(t.label_weight)}),net:({remaining:t})=>i.jsx("span",{className:"text-sm text-white",children:Ru(t)}),gross:({spool:t,remaining:e})=>i.jsx("span",{className:"text-sm text-bambu-gray",children:Ru(e+t.core_weight)}),added_full:({spool:t})=>i.jsx("span",{className:"text-sm text-bambu-gray",children:t.added_full==null?"-":t.added_full?"Yes":"No"}),used:({spool:t})=>i.jsx("span",{className:"text-sm text-bambu-gray",children:t.weight_used>0?Ru(t.weight_used):"-"}),printed_total:()=>i.jsx("span",{className:"text-sm text-bambu-gray/50",children:"-"}),printed_since_weight:()=>i.jsx("span",{className:"text-sm text-bambu-gray/50",children:"-"}),note:({spool:t})=>i.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?i.jsx("span",{className:"text-sm text-bambu-gray",children:"-"}):i.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?i.jsx("span",{className:"text-sm text-bambu-gray font-mono",title:e,children:e.length>12?`${e.slice(0,6)}...${e.slice(-4)}`:e}):i.jsx("span",{className:"text-sm text-bambu-gray/50",children:"-"})},data_origin:({spool:t})=>i.jsx("span",{className:"text-sm text-bambu-gray",children:t.data_origin||"-"}),tag_type:({spool:t})=>i.jsx("span",{className:"text-sm text-bambu-gray",children:t.tag_type||"-"}),remaining:({remaining:t,pct:e})=>i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("div",{className:"flex-1 h-2 bg-bambu-dark-tertiary rounded-full overflow-hidden",children:i.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)}%`}})}),i.jsxs("span",{className:"text-xs text-bambu-gray min-w-[40px] text-right",children:[Math.round(t),"g"]})]}),cost_per_kg:({spool:t,currencySymbol:e})=>i.jsx("span",{className:"text-sm text-bambu-gray",children:t.cost_per_kg!=null?`${e}${t.cost_per_kg.toFixed(2)}`:"-"})},Dj={id:t=>t.id,added_time:t=>t.created_at||"",encode_time:t=>t.encode_time||"",last_used_time:t=>t.last_used||"",material:t=>(t.material||"").toLowerCase(),subtype:t=>(t.subtype||"").toLowerCase(),color_name:t=>(t.color_name||"").toLowerCase(),brand:t=>(t.brand||"").toLowerCase(),slicer_filament:t=>(t.slicer_filament_name||t.slicer_filament||"").toLowerCase(),location:(t,e)=>{const n=e[t.id];if(!n)return"";const r=n.ams_id===254||n.ams_id===255,a=!r&&n.ams_id>=128;return`${n.printer_name||""} ${cI(n.ams_id,n.tray_id,a,r)}`},label_weight:t=>t.label_weight,net:t=>Math.max(0,t.label_weight-t.weight_used),gross:t=>Math.max(0,t.label_weight-t.weight_used)+t.core_weight,used:t=>t.weight_used,remaining:t=>t.label_weight>0?Math.max(0,t.label_weight-t.weight_used)/t.label_weight:0,note:t=>(t.note||"").toLowerCase(),data_origin:t=>(t.data_origin||"").toLowerCase(),tag_type:t=>(t.tag_type||"").toLowerCase(),cost_per_kg:t=>t.cost_per_kg??0},nF="bambuddy-inventory-sort";function HJe(){try{const t=localStorage.getItem(nF);if(t)return JSON.parse(t)}catch{}return null}function $Je(t){try{t?localStorage.setItem(nF,JSON.stringify(t)):localStorage.removeItem(nF)}catch{}}function VJe(){const{t}=Ut(),e=tn(),{showToast:n}=cn(),[r,a]=w.useState(null),[s,o]=w.useState(null),[l,c]=w.useState("active"),[u,d]=w.useState("all"),[h,f]=w.useState(""),[p,x]=w.useState(""),[v,g]=w.useState(""),[y,_]=w.useState("table"),[N,k]=w.useState(HJe),[A,M]=w.useState(OJe),[C,j]=w.useState(!1),[P,E]=w.useState(0),[B,O]=w.useState(()=>{try{const Q=localStorage.getItem("bambuddy-inventory-pageSize");if(Q){const L=Number(Q);if([15,30,50,100,-1].includes(L))return L}}catch{}return 15}),{data:U}=Je({queryKey:["settings"],queryFn:ne.getSettings}),R=U?.date_format||"system",{data:V,isLoading:G}=Je({queryKey:["inventory-spools"],queryFn:()=>ne.getSpools(!0),refetchInterval:3e4}),{data:z}=Je({queryKey:["spool-assignments"],queryFn:()=>ne.getAssignments(),refetchInterval:3e4}),K=ot({mutationFn:Q=>ne.deleteSpool(Q),onSuccess:()=>{e.invalidateQueries({queryKey:["inventory-spools"]}),n(t("inventory.spoolDeleted"),"success")}}),Y=ot({mutationFn:Q=>ne.archiveSpool(Q),onSuccess:()=>{e.invalidateQueries({queryKey:["inventory-spools"]}),n(t("inventory.spoolArchived"),"success")}}),ae=ot({mutationFn:Q=>ne.restoreSpool(Q),onSuccess:()=>{e.invalidateQueries({queryKey:["inventory-spools"]}),n(t("inventory.spoolRestored"),"success")}}),$=w.useMemo(()=>{if(!V)return null;let Q=0,L=0,D=0,H=0;const he={};for(const be of V){if(be.archived_at)continue;H++;const fe=Math.max(0,be.label_weight-be.weight_used);Q+=fe,L+=be.weight_used,(be.label_weight>0?fe/be.label_weight*100:0)<20&&D++;const Ie=be.material||"Unknown";he[Ie]||(he[Ie]={count:0,weight:0}),he[Ie].count++,he[Ie].weight+=fe}return{totalWeight:Q,totalConsumed:L,lowStock:D,byMaterial:he,totalSpools:H}},[V]),W=z?.length??0,ee=rl(U?.currency||"USD"),J=w.useMemo(()=>{const Q={};for(const L of z||[])Q[L.spool_id]=L;return Q},[z]),ye=w.useMemo(()=>$?Object.entries($.byMaterial).sort((Q,L)=>L[1].weight-Q[1].weight).slice(0,4):[],[$]),me=w.useMemo(()=>{let Q=V||[];if(l==="active"?Q=Q.filter(L=>!L.archived_at):Q=Q.filter(L=>!!L.archived_at),u==="used"?Q=Q.filter(L=>L.weight_used>0):u==="new"&&(Q=Q.filter(L=>L.weight_used===0)),h&&(Q=Q.filter(L=>L.material===h)),p&&(Q=Q.filter(L=>L.brand===p)),v){const L=v.toLowerCase();Q=Q.filter(D=>D.brand?.toLowerCase().includes(L)||D.material.toLowerCase().includes(L)||D.color_name?.toLowerCase().includes(L)||D.subtype?.toLowerCase().includes(L)||D.note?.toLowerCase().includes(L)||D.slicer_filament_name?.toLowerCase().includes(L))}return Q},[V,l,u,h,p,v]),te=()=>E(0),je=[...new Set(V?.map(Q=>Q.material)||[])].sort(),ue=[...new Set(V?.map(Q=>Q.brand).filter(Boolean)||[])].sort(),oe=l!=="active"||u!=="all"||!!h||!!p||!!v,_e=Q=>{M(Q),IJe(Q)},se=w.useMemo(()=>A.filter(Q=>Q.visible).map(Q=>Q.id),[A]),Oe=Q=>{Dj[Q]&&(k(L=>{let D;return L?.column===Q?D=L.direction==="asc"?{column:Q,direction:"desc"}:null:D={column:Q,direction:"asc"},$Je(D),D}),te())},q=w.useMemo(()=>{if(!N)return me;const Q=Dj[N.column];return Q?[...me].sort((D,H)=>{const he=Q(D,J),be=Q(H,J);return hebe?N.direction==="asc"?1:-1:0}):me},[me,N,J]),X=B===-1,de=X?q.length||1:B,Z=Math.max(1,Math.ceil(q.length/de)),ie=X?0:Math.min(P,Z-1),le=X?q:q.slice(ie*de,(ie+1)*de),Fe=Q=>{O(Q),E(0);try{localStorage.setItem("bambuddy-inventory-pageSize",String(Q))}catch{}},pe=()=>{c("active"),d("all"),f(""),x(""),g(""),te()};return i.jsxs("div",{className:"p-4 md:p-6 space-y-6",children:[i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx(fi,{className:"w-6 h-6 text-bambu-green"}),i.jsx("h1",{className:"text-2xl font-bold text-white",children:t("inventory.title")})]}),i.jsx("p",{className:"text-sm text-bambu-gray mt-1 ml-9",children:(t("inventory.noSpools").split(".")[0],"")})]}),i.jsxs(Ce,{onClick:()=>a({spool:null}),children:[i.jsx(Xn,{className:"w-4 h-4"}),t("inventory.addSpool")]})]}),$&&!G&&i.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-5 gap-3",children:[i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg p-4",children:[i.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[i.jsx(fi,{className:"w-4 h-4 text-bambu-green"}),i.jsx("span",{className:"text-xs text-bambu-gray font-medium uppercase tracking-wide",children:t("inventory.totalInventory")})]}),i.jsx("div",{className:"text-xl font-bold text-white",children:Ru($.totalWeight,!0)}),i.jsxs("div",{className:"text-xs text-bambu-gray mt-1",children:[$.totalSpools," ",$.totalSpools!==1?t("inventory.spools"):t("inventory.spool")]})]}),i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg p-4",children:[i.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[i.jsx(CF,{className:"w-4 h-4 text-blue-400"}),i.jsx("span",{className:"text-xs text-bambu-gray font-medium uppercase tracking-wide",children:t("inventory.totalConsumed")})]}),i.jsx("div",{className:"text-xl font-bold text-white",children:Ru($.totalConsumed,!0)}),i.jsx("div",{className:"text-xs text-bambu-gray mt-1",children:t("inventory.sinceTracking")})]}),i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg p-4",children:[i.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[i.jsx(mi,{className:"w-4 h-4 text-green-400"}),i.jsx("span",{className:"text-xs text-bambu-gray font-medium uppercase tracking-wide",children:t("inventory.byMaterial")})]}),i.jsx("div",{className:"flex flex-wrap gap-1.5 mt-1",children:ye.map(([Q,L])=>i.jsxs("span",{className:`inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium ${zJe[Q]||"bg-bambu-dark-tertiary text-bambu-gray"}`,children:[Q," ",i.jsx("span",{className:"opacity-70",children:Ru(L.weight,!0)})]},Q))})]}),i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg p-4",children:[i.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[i.jsx(xr,{className:"w-4 h-4 text-purple-400"}),i.jsx("span",{className:"text-xs text-bambu-gray font-medium uppercase tracking-wide",children:t("inventory.inPrinter")})]}),i.jsx("div",{className:"text-xl font-bold text-white",children:W}),i.jsx("div",{className:"text-xs text-bambu-gray mt-1",children:t("inventory.loadedInAms")})]}),i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg p-4",children:[i.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[i.jsx(Tn,{className:"w-4 h-4 text-yellow-400"}),i.jsx("span",{className:"text-xs text-bambu-gray font-medium uppercase tracking-wide",children:t("inventory.lowStock")})]}),i.jsx("div",{className:`text-xl font-bold ${$.lowStock>0?"text-yellow-400":"text-white"}`,children:$.lowStock}),i.jsx("div",{className:"text-xs text-bambu-gray mt-1",children:t("inventory.lowStockThreshold")})]})]}),i.jsxs("div",{className:"flex flex-col sm:flex-row gap-3 items-start sm:items-center justify-between",children:[i.jsxs("div",{className:"relative flex-1 max-w-md",children:[i.jsx(kr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50"}),i.jsx("input",{type:"text",value:v,onChange:Q=>{g(Q.target.value),te()},placeholder:t("inventory.search"),className:"w-full pl-10 pr-8 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green"}),v&&i.jsx("button",{onClick:()=>{g(""),te()},className:"absolute right-3 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white",children:i.jsx(Ft,{className:"w-4 h-4"})})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[y==="table"&&i.jsxs("button",{onClick:()=>j(!0),className:"flex items-center gap-1.5 px-3 py-1.5 text-sm font-medium text-bambu-gray border border-bambu-dark-tertiary rounded-lg hover:bg-bambu-dark-tertiary transition-colors",title:t("inventory.configureColumns"),children:[i.jsx(Ehe,{className:"w-4 h-4"}),i.jsx("span",{className:"hidden sm:inline",children:t("inventory.columns")})]}),i.jsxs("div",{className:"flex bg-bambu-dark-primary border border-bambu-dark-tertiary rounded-lg overflow-hidden",children:[i.jsxs("button",{onClick:()=>_("table"),className:`flex items-center gap-1.5 px-3 py-1.5 text-sm font-medium transition-colors ${y==="table"?"bg-bambu-green text-white":"text-bambu-gray hover:bg-bambu-dark-tertiary"}`,children:[i.jsx(mpe,{className:"w-4 h-4"}),i.jsx("span",{className:"hidden sm:inline",children:t("inventory.table")})]}),i.jsxs("button",{onClick:()=>_("cards"),className:`flex items-center gap-1.5 px-3 py-1.5 text-sm font-medium transition-colors ${y==="cards"?"bg-bambu-green text-white":"text-bambu-gray hover:bg-bambu-dark-tertiary"}`,children:[i.jsx(c0,{className:"w-4 h-4"}),i.jsx("span",{className:"hidden sm:inline",children:t("inventory.cards")})]})]})]})]}),i.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[i.jsxs("div",{className:"flex items-center rounded-lg border border-bambu-dark-tertiary overflow-hidden",children:[i.jsxs("button",{onClick:()=>{c("active"),te()},className:`flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium transition-colors ${l==="active"?"bg-bambu-green/20 text-bambu-green":"text-bambu-gray hover:bg-bambu-dark-tertiary"}`,children:[i.jsx(fi,{className:"w-3.5 h-3.5"}),t("inventory.active")]}),i.jsxs("button",{onClick:()=>{c("archived"),te()},className:`flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium transition-colors ${l==="archived"?"bg-bambu-green/20 text-bambu-green":"text-bambu-gray hover:bg-bambu-dark-tertiary"}`,children:[i.jsx(js,{className:"w-3.5 h-3.5"}),t("inventory.archived")]})]}),i.jsx("div",{className:"w-px h-5 bg-bambu-dark-tertiary"}),i.jsxs("div",{className:"flex items-center rounded-lg border border-bambu-dark-tertiary overflow-hidden",children:[i.jsx("button",{onClick:()=>{d("all"),te()},className:`px-3 py-1.5 text-xs font-medium transition-colors ${u==="all"?"bg-bambu-green/20 text-bambu-green":"text-bambu-gray hover:bg-bambu-dark-tertiary"}`,children:t("inventory.all")}),i.jsxs("button",{onClick:()=>{d("used"),te()},className:`flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium transition-colors ${u==="used"?"bg-bambu-green/20 text-bambu-green":"text-bambu-gray hover:bg-bambu-dark-tertiary"}`,children:[i.jsx(Gn,{className:"w-3.5 h-3.5"}),t("inventory.used")]}),i.jsx("button",{onClick:()=>{d("new"),te()},className:`px-3 py-1.5 text-xs font-medium transition-colors ${u==="new"?"bg-bambu-green/20 text-bambu-green":"text-bambu-gray hover:bg-bambu-dark-tertiary"}`,children:t("inventory.new")})]}),i.jsx("div",{className:"w-px h-5 bg-bambu-dark-tertiary"}),i.jsxs("select",{value:h,onChange:Q=>{f(Q.target.value),te()},className:`px-3 py-1.5 rounded-lg border text-xs font-medium transition-colors cursor-pointer focus:outline-none ${h?"bg-bambu-green/20 text-bambu-green border-bambu-green/30":"bg-transparent text-bambu-gray border-bambu-dark-tertiary hover:bg-bambu-dark-tertiary"}`,children:[i.jsx("option",{value:"",children:t("inventory.material")}),je.map(Q=>i.jsx("option",{value:Q,children:Q},Q))]}),i.jsxs("select",{value:p,onChange:Q=>{x(Q.target.value),te()},className:`px-3 py-1.5 rounded-lg border text-xs font-medium transition-colors cursor-pointer focus:outline-none ${p?"bg-bambu-green/20 text-bambu-green border-bambu-green/30":"bg-transparent text-bambu-gray border-bambu-dark-tertiary hover:bg-bambu-dark-tertiary"}`,children:[i.jsx("option",{value:"",children:t("inventory.brand")}),ue.map(Q=>i.jsx("option",{value:Q,children:Q},Q))]}),oe&&i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"w-px h-5 bg-bambu-dark-tertiary"}),i.jsxs("button",{onClick:pe,className:"flex items-center gap-1 text-xs text-bambu-gray hover:text-bambu-green transition-colors",children:[i.jsx(Ft,{className:"w-3.5 h-3.5"}),t("inventory.clearFilters")]})]}),i.jsxs("span",{className:"ml-auto text-xs text-bambu-gray",children:[q.length," ",q.length!==1?t("inventory.spools"):t("inventory.spool")]})]}),G?i.jsx("div",{className:"flex justify-center py-16",children:i.jsx(it,{className:"w-8 h-8 text-bambu-green animate-spin"})}):y==="cards"?le.length>0?i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4",children:le.map(Q=>{const L=Math.max(0,Q.label_weight-Q.weight_used),D=Q.label_weight>0?L/Q.label_weight*100:0,H=Q.rgba?`#${Q.rgba.substring(0,6)}`:"#808080";return i.jsxs("div",{className:`bg-bambu-dark-secondary rounded-lg overflow-hidden border border-bambu-dark-tertiary hover:border-bambu-green transition-colors cursor-pointer ${Q.archived_at?"opacity-50":""}`,onClick:()=>a({spool:Q}),children:[i.jsx("div",{className:"h-14 flex items-center justify-center",style:{backgroundColor:H},children:i.jsx("span",{className:"bg-white/90 text-gray-800 px-3 py-0.5 rounded-full text-sm font-medium",children:one(Q.color_name,Q.rgba)||"-"})}),i.jsxs("div",{className:"p-4 space-y-3",children:[i.jsxs("div",{className:"flex items-start justify-between gap-2",children:[i.jsxs("div",{children:[i.jsxs("h3",{className:"font-semibold text-white",children:[Q.material,Q.subtype?` ${Q.subtype}`:""]}),i.jsx("p",{className:"text-sm text-bambu-gray",children:Q.brand||"-"})]}),i.jsxs("span",{className:"text-xs font-mono text-bambu-gray bg-bambu-dark-tertiary px-2 py-1 rounded",children:["#",Q.id]})]}),i.jsxs("div",{children:[i.jsxs("div",{className:"flex justify-between text-xs text-bambu-gray mb-1",children:[i.jsx("span",{children:t("inventory.remaining")}),i.jsxs("span",{children:[Math.round(D),"%"]})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("div",{className:"flex-1 h-2 bg-bambu-dark-tertiary rounded-full overflow-hidden",children:i.jsx("div",{className:`h-full rounded-full ${D>50?"bg-bambu-green":D>20?"bg-yellow-500":"bg-red-500"}`,style:{width:`${Math.min(D,100)}%`}})}),i.jsxs("span",{className:"text-xs text-bambu-gray min-w-[40px] text-right",children:[Math.round(L),"g"]})]})]}),i.jsxs("div",{className:"grid grid-cols-2 gap-2 text-xs",children:[i.jsxs("div",{children:[i.jsxs("span",{className:"text-bambu-gray/60",children:[t("inventory.labelWeight"),": "]}),i.jsx("span",{className:"text-bambu-gray",children:Ru(Q.label_weight)})]}),i.jsxs("div",{children:[i.jsxs("span",{className:"text-bambu-gray/60",children:[t("inventory.weightUsed"),": "]}),i.jsx("span",{className:"text-bambu-gray",children:Q.weight_used>0?Ru(Q.weight_used):"-"})]})]}),Q.note&&i.jsx("div",{className:"text-xs text-bambu-gray/60 pt-2 border-t border-bambu-dark-tertiary truncate",title:Q.note,children:Q.note})]})]},Q.id)})}),i.jsx(qJe,{pageIndex:ie,pageSize:B,totalRows:q.length,totalPages:Z,onPageChange:E,onPageSizeChange:Fe,t})]}):i.jsx(aK,{hasFilters:oe,onAddSpool:()=>a({spool:null}),t}):le.length>0?i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg overflow-hidden border border-bambu-dark-tertiary",children:[i.jsx("div",{className:"overflow-x-auto",children:i.jsxs("table",{className:"w-full",children:[i.jsx("thead",{children:i.jsxs("tr",{className:"border-b border-bambu-dark-tertiary bg-bambu-dark-tertiary/30",children:[se.map(Q=>{const L=!!Dj[Q],D=N?.column===Q;return i.jsx("th",{className:`text-left py-3 px-4 text-xs font-medium uppercase tracking-wide select-none ${Q==="remaining"?"min-w-[150px]":""} ${L?"cursor-pointer hover:text-bambu-green transition-colors":""} ${D?"text-bambu-green":"text-bambu-gray"}`,onClick:L?()=>Oe(Q):void 0,children:i.jsxs("span",{className:"inline-flex items-center gap-1",children:[UJe[Q]?.(t)??Q,L&&(D?N.direction==="asc"?i.jsx(Af,{className:"w-3 h-3"}):i.jsx(ib,{className:"w-3 h-3"}):i.jsx(vF,{className:"w-3 h-3 opacity-30"}))]})},Q)}),i.jsx("th",{className:"text-right py-3 px-4 text-xs font-medium text-bambu-gray uppercase tracking-wide",children:t("common.actions")})]})}),i.jsx("tbody",{children:le.map(Q=>{const L=Math.max(0,Q.label_weight-Q.weight_used),D=Q.label_weight>0?L/Q.label_weight*100:0;return i.jsxs("tr",{className:`border-b border-bambu-dark-tertiary/50 hover:bg-bambu-dark-tertiary/30 transition-colors cursor-pointer ${Q.archived_at?"opacity-50":""}`,onClick:()=>a({spool:Q}),children:[se.map(H=>i.jsx("td",{className:"py-3 px-4",children:BJe[H]?.({spool:Q,remaining:L,pct:D,assignmentMap:J,currencySymbol:ee,dateFormat:R})},H)),i.jsx("td",{className:"py-3 px-4",children:i.jsxs("div",{className:"flex items-center justify-end gap-1",onClick:H=>H.stopPropagation(),children:[i.jsx("button",{onClick:()=>a({spool:Q}),className:"p-1.5 text-bambu-gray hover:text-white rounded transition-colors",title:t("inventory.editSpool"),children:i.jsx(Jm,{className:"w-4 h-4"})}),Q.archived_at?i.jsx("button",{onClick:()=>ae.mutate(Q.id),className:"p-1.5 text-bambu-gray hover:text-bambu-green rounded transition-colors",title:t("inventory.restore"),children:i.jsx(Fo,{className:"w-4 h-4"})}):i.jsx("button",{onClick:()=>o({type:"archive",spoolId:Q.id}),className:"p-1.5 text-bambu-gray hover:text-yellow-400 rounded transition-colors",title:t("inventory.archive"),children:i.jsx(js,{className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>o({type:"delete",spoolId:Q.id}),className:"p-1.5 text-bambu-gray hover:text-red-400 rounded transition-colors",title:t("common.delete"),children:i.jsx(Jt,{className:"w-4 h-4"})})]})})]},Q.id)})})]})}),i.jsxs("div",{className:"flex items-center justify-between px-4 py-3 bg-bambu-dark-tertiary/50 border-t border-bambu-dark-tertiary text-sm",children:[i.jsx("span",{className:"text-bambu-gray",children:X?`${q.length} ${q.length!==1?t("inventory.spools"):t("inventory.spool")}`:i.jsxs(i.Fragment,{children:[t("inventory.showing")," ",ie*de+1," ",t("inventory.to")," ",Math.min((ie+1)*de,q.length)," ",t("inventory.of")," ",q.length," ",t("inventory.spools")]})}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"text-bambu-gray",children:t("inventory.show")}),i.jsxs("select",{value:B,onChange:Q=>Fe(Number(Q.target.value)),className:"px-2 py-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:outline-none focus:border-bambu-green",children:[[15,30,50,100].map(Q=>i.jsx("option",{value:Q,children:Q},Q)),i.jsx("option",{value:-1,children:t("inventory.all")})]}),!X&&i.jsxs(i.Fragment,{children:[i.jsx("button",{onClick:()=>E(0),disabled:ie===0,className:"p-1.5 rounded text-bambu-gray hover:text-white disabled:opacity-30 disabled:cursor-not-allowed transition-colors",title:"First page",children:i.jsx(eX,{className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>E(Q=>Math.max(0,Q-1)),disabled:ie===0,className:"p-1.5 rounded text-bambu-gray hover:text-white disabled:opacity-30 disabled:cursor-not-allowed transition-colors",children:i.jsx(Xl,{className:"w-4 h-4"})}),i.jsxs("span",{className:"text-bambu-gray px-2 whitespace-nowrap",children:[t("inventory.page")," ",ie+1," ",t("inventory.of")," ",Z]}),i.jsx("button",{onClick:()=>E(Q=>Math.min(Z-1,Q+1)),disabled:ie>=Z-1,className:"p-1.5 rounded text-bambu-gray hover:text-white disabled:opacity-30 disabled:cursor-not-allowed transition-colors",children:i.jsx(pi,{className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>E(Z-1),disabled:ie>=Z-1,className:"p-1.5 rounded text-bambu-gray hover:text-white disabled:opacity-30 disabled:cursor-not-allowed transition-colors",title:"Last page",children:i.jsx(tX,{className:"w-4 h-4"})})]})]})]})]}):i.jsx(aK,{hasFilters:oe,onAddSpool:()=>a({spool:null}),t}),r!==null&&i.jsx(FJe,{isOpen:!0,onClose:()=>a(null),spool:r.spool,currencySymbol:ee}),s&&i.jsx(gn,{title:s.type==="delete"?t("common.delete"):t("inventory.archive"),message:s.type==="delete"?t("inventory.deleteConfirm"):t("inventory.archiveConfirm"),confirmText:s.type==="delete"?t("common.delete"):t("inventory.archive"),variant:s.type==="delete"?"danger":"warning",onConfirm:()=>{s.type==="delete"?K.mutate(s.spoolId):Y.mutate(s.spoolId),o(null)},onCancel:()=>o(null)}),i.jsx(LJe,{isOpen:C,onClose:()=>j(!1),columns:A,defaultColumns:c1,onSave:_e})]})}function qJe({pageIndex:t,pageSize:e,totalRows:n,totalPages:r,onPageChange:a,onPageSizeChange:s,t:o}){const l=e===-1;if(r<=1&&!l)return null;const c=l?n||1:e;return i.jsxs("div",{className:"flex items-center justify-between pt-2 text-sm",children:[i.jsx("span",{className:"text-bambu-gray",children:l?`${n} ${o(n!==1?"inventory.spools":"inventory.spool")}`:i.jsxs(i.Fragment,{children:[o("inventory.showing")," ",t*c+1," ",o("inventory.to")," ",Math.min((t+1)*c,n)," ",o("inventory.of")," ",n," ",o("inventory.spools")]})}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"text-bambu-gray",children:o("inventory.show")}),i.jsxs("select",{value:e,onChange:u=>s(Number(u.target.value)),className:"px-2 py-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:outline-none focus:border-bambu-green",children:[[15,30,50,100].map(u=>i.jsx("option",{value:u,children:u},u)),i.jsx("option",{value:-1,children:o("inventory.all")})]}),!l&&i.jsxs(i.Fragment,{children:[i.jsx("button",{onClick:()=>a(0),disabled:t===0,className:"p-1.5 rounded text-bambu-gray hover:text-white disabled:opacity-30 disabled:cursor-not-allowed transition-colors",children:i.jsx(eX,{className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>a(Math.max(0,t-1)),disabled:t===0,className:"p-1.5 rounded text-bambu-gray hover:text-white disabled:opacity-30 disabled:cursor-not-allowed transition-colors",children:i.jsx(Xl,{className:"w-4 h-4"})}),i.jsxs("span",{className:"text-bambu-gray px-2 whitespace-nowrap",children:[o("inventory.page")," ",t+1," ",o("inventory.of")," ",r]}),i.jsx("button",{onClick:()=>a(Math.min(r-1,t+1)),disabled:t>=r-1,className:"p-1.5 rounded text-bambu-gray hover:text-white disabled:opacity-30 disabled:cursor-not-allowed transition-colors",children:i.jsx(pi,{className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>a(r-1),disabled:t>=r-1,className:"p-1.5 rounded text-bambu-gray hover:text-white disabled:opacity-30 disabled:cursor-not-allowed transition-colors",children:i.jsx(tX,{className:"w-4 h-4"})})]})]})]})}function aK({hasFilters:t,onAddSpool:e,t:n}){return i.jsxs("div",{className:"flex flex-col items-center justify-center py-16 px-4",children:[i.jsxs("div",{className:"relative mb-6",children:[i.jsx("div",{className:"absolute inset-0 -m-4 bg-bambu-green/5 rounded-full blur-2xl"}),i.jsxs("div",{className:"relative flex items-center justify-center w-24 h-24 rounded-2xl bg-gradient-to-br from-bambu-dark-secondary to-bambu-dark-tertiary border border-bambu-dark-tertiary shadow-lg",children:[i.jsx("div",{className:"absolute -top-1 -right-1 w-3 h-3 rounded-full bg-bambu-green/30"}),i.jsx("div",{className:"absolute -bottom-2 -left-2 w-2 h-2 rounded-full bg-bambu-green/20"}),t?i.jsx(kr,{className:"w-10 h-10 text-bambu-gray/40",strokeWidth:1.5}):i.jsxs("div",{className:"relative",children:[i.jsx("div",{className:"w-14 h-14 rounded-full border-4 border-bambu-gray/20 flex items-center justify-center",children:i.jsx("div",{className:"w-6 h-6 rounded-full bg-bambu-gray/10 border-2 border-bambu-gray/20"})}),i.jsx("div",{className:"absolute -bottom-1 -right-1 w-6 h-6 rounded-full bg-bambu-green flex items-center justify-center shadow-md",children:i.jsx("span",{className:"text-white text-lg font-bold leading-none",children:"+"})})]})]})]}),i.jsx("h3",{className:"text-lg font-semibold text-white mb-2 text-center",children:t?n("inventory.noSpoolsMatch"):n("inventory.noSpools").split(".")[0]}),i.jsx("p",{className:"text-sm text-bambu-gray text-center max-w-sm mb-6",children:n(t?"inventory.noSpoolsMatchDesc":"inventory.noSpools")}),!t&&i.jsxs(Ce,{onClick:e,children:[i.jsx(fi,{className:"w-4 h-4"}),n("inventory.addSpool")]})]})}const iK=["DEBUG","INFO","WARNING","ERROR"],Rj={DEBUG:"text-gray-400",INFO:"text-blue-400",WARNING:"text-yellow-400",ERROR:"text-red-400"},GJe={DEBUG:OC,INFO:Zs,WARNING:Tn,ERROR:Ba};function WJe(){const t=tn(),[e,n]=w.useState(!0),[r,a]=w.useState(new Set),[s,o]=w.useState(""),[l,c]=w.useState("ALL"),[u,d]=w.useState(!1),[h,f]=w.useState(!1),p=w.useRef(null),{data:x,isLoading:v,refetch:g}=Je({queryKey:["application-logs",l,s],queryFn:()=>qg.getLogs({limit:200,level:l==="ALL"?void 0:l,search:s||void 0}),refetchInterval:h?2e3:!1,enabled:u});w.useEffect(()=>{u||f(!1)},[u]);const y=ot({mutationFn:()=>qg.clearLogs(),onSuccess:()=>{t.invalidateQueries({queryKey:["application-logs"]})}});w.useEffect(()=>{e&&p.current&&x?.entries&&(p.current.scrollTop=p.current.scrollHeight)},[x?.entries,e]);const _=C=>{a(j=>{const P=new Set(j);return P.has(C)?P.delete(C):P.add(C),P})},N=C=>{const j=C.split(" ");return j.length>=2?j[1]:C},k=w.useMemo(()=>x?.entries??[],[x?.entries]),A=w.useMemo(()=>[...k].reverse(),[k]),M=({level:C})=>{const j=GJe[C]||Zs;return i.jsx(j,{className:`w-3.5 h-3.5 ${Rj[C]||"text-gray-400"}`})};return i.jsxs("div",{className:"bg-bambu-dark rounded-lg overflow-hidden",children:[i.jsxs("button",{onClick:()=>d(!u),className:"w-full flex items-center justify-between p-4 hover:bg-bambu-dark-tertiary/50 transition-colors",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("div",{className:`p-2 rounded-lg ${h?"bg-bambu-green/20 text-bambu-green":"bg-bambu-dark-tertiary text-bambu-gray"}`,children:i.jsx(OC,{className:"w-5 h-5"})}),i.jsxs("div",{className:"text-left",children:[i.jsx("p",{className:"font-medium text-white",children:"Application Logs"}),i.jsx("p",{className:"text-sm text-bambu-gray",children:h?`Live streaming - ${x?.filtered_count??0} entries`:"View and filter application logs"})]})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[h&&i.jsxs("span",{className:"flex items-center gap-1.5 px-2 py-1 bg-bambu-green/20 rounded text-bambu-green text-xs",children:[i.jsx("span",{className:"w-1.5 h-1.5 bg-bambu-green rounded-full animate-pulse"}),"Live"]}),u?i.jsx(yl,{className:"w-5 h-5 text-bambu-gray"}):i.jsx(Un,{className:"w-5 h-5 text-bambu-gray"})]})]}),u&&i.jsxs("div",{className:"border-t border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex flex-col gap-2 p-4 border-b border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[h?i.jsxs("button",{onClick:C=>{C.stopPropagation(),f(!1)},className:"flex items-center gap-1.5 px-3 py-1.5 text-sm bg-red-500/20 text-red-400 hover:bg-red-500/30 rounded transition-colors",children:[i.jsx(vl,{className:"w-4 h-4"}),"Stop"]}):i.jsxs("button",{onClick:C=>{C.stopPropagation(),f(!0),g()},className:"flex items-center gap-1.5 px-3 py-1.5 text-sm bg-bambu-green/20 text-bambu-green hover:bg-bambu-green/30 rounded transition-colors",children:[i.jsx(io,{className:"w-4 h-4"}),"Start"]}),i.jsxs("button",{onClick:()=>y.mutate(),disabled:y.isPending||k.length===0,className:"flex items-center gap-1.5 px-3 py-1.5 text-sm bg-bambu-dark-tertiary text-bambu-gray hover:text-white hover:bg-bambu-dark-secondary rounded transition-colors disabled:opacity-50",children:[i.jsx(Jt,{className:"w-4 h-4"}),"Clear"]}),i.jsx("button",{onClick:()=>g(),disabled:v,className:"flex items-center gap-1.5 px-3 py-1.5 text-sm bg-bambu-dark-tertiary text-bambu-gray hover:text-white hover:bg-bambu-dark-secondary rounded transition-colors disabled:opacity-50",children:i.jsx(Cr,{className:`w-4 h-4 ${v?"animate-spin":""}`})}),i.jsx("div",{className:"flex-1"}),i.jsxs("label",{className:"flex items-center gap-2 text-sm text-bambu-gray cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:e,onChange:C=>n(C.target.checked),className:"rounded border-bambu-dark-tertiary bg-bambu-dark-tertiary"}),"Auto-scroll"]}),i.jsxs("span",{className:"text-sm text-bambu-gray",children:[x?.filtered_count??0,"/",x?.total_in_file??0]})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsxs("div",{className:"relative flex-1",children:[i.jsx(kr,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),i.jsx("input",{type:"text",placeholder:"Search message or logger name...",value:s,onChange:C=>o(C.target.value),className:"w-full pl-8 pr-8 py-1.5 text-sm bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"}),s&&i.jsx("button",{onClick:()=>o(""),className:"absolute right-2 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white",children:i.jsx(Ft,{className:"w-4 h-4"})})]}),i.jsxs("div",{className:"flex items-center gap-1 bg-bambu-dark-secondary rounded border border-bambu-dark-tertiary",children:[i.jsx("button",{onClick:()=>c("ALL"),className:`px-2 py-1.5 text-xs rounded-l transition-colors ${l==="ALL"?"bg-bambu-green text-white":"text-bambu-gray hover:text-white"}`,children:"All"}),iK.map((C,j)=>i.jsx("button",{onClick:()=>c(C),className:`px-2 py-1.5 text-xs transition-colors flex items-center gap-1 ${j===iK.length-1?"rounded-r":""} ${l===C?`${Rj[C]} bg-bambu-dark-tertiary`:"text-bambu-gray hover:text-white"}`,children:C},C))]})]})]}),i.jsx("div",{ref:p,className:"overflow-auto font-mono text-xs bg-black min-h-[300px] max-h-[500px]",children:k.length===0?i.jsxs("div",{className:"flex flex-col items-center justify-center h-[300px] text-bambu-gray",children:[i.jsx("p",{className:"mb-2",children:"No log entries found"}),i.jsx("p",{className:"text-sm",children:"Log file may be empty or cleared"})]}):i.jsx("div",{className:"divide-y divide-bambu-dark-tertiary/30",children:A.map((C,j)=>{const P=r.has(j),E=C.message.includes(` `);return i.jsx("div",{className:`p-2 cursor-pointer hover:bg-bambu-dark-secondary/50 transition-colors ${P?"bg-bambu-dark-secondary/30":""}`,onClick:()=>E&&_(j),children:i.jsxs("div",{className:"flex items-start gap-2",children:[i.jsx("span",{className:"text-bambu-gray/70 shrink-0 w-20",children:N(C.timestamp)}),i.jsx("span",{className:"shrink-0",children:i.jsx(M,{level:C.level})}),i.jsxs("span",{className:"text-purple-400/80 shrink-0 max-w-[200px] truncate",title:C.logger_name,children:["[",C.logger_name,"]"]}),i.jsx("span",{className:`flex-1 ${Rj[C.level]||"text-white/80"} ${!P&&E?"truncate":""}`,children:P?i.jsx("pre",{className:"whitespace-pre-wrap break-all",children:C.message}):C.message.split(` -`)[0]}),E&&i.jsx("span",{className:"text-bambu-gray/50 shrink-0",children:P?i.jsx(yl,{className:"w-3.5 h-3.5"}):i.jsx(Un,{className:"w-3.5 h-3.5"})})]})},j)})})}),i.jsx("div",{className:"flex items-center justify-between p-3 border-t border-bambu-dark-tertiary text-sm text-bambu-gray",children:h?i.jsxs("span",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"w-2 h-2 bg-green-500 rounded-full animate-pulse"}),"Auto-refreshing every 2 seconds"]}):i.jsx("span",{children:"Click Start to enable live log streaming"})})]})]})}function KJe(t){return t<1024?`${t} B`:t<1024*1024?`${(t/1024).toFixed(1)} KB`:t<1024*1024*1024?`${(t/(1024*1024)).toFixed(1)} MB`:`${(t/(1024*1024*1024)).toFixed(2)} GB`}function ka({icon:t,label:e,value:n,subValue:r,color:a="text-bambu-green"}){return i.jsxs("div",{className:"flex items-start gap-3 p-4 bg-bambu-dark rounded-lg",children:[i.jsx("div",{className:`p-2 rounded-lg bg-bambu-dark-tertiary ${a}`,children:i.jsx(t,{className:"w-5 h-5"})}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsx("p",{className:"text-sm text-bambu-gray",children:e}),i.jsx("p",{className:"text-lg font-semibold text-white truncate",children:n}),r&&i.jsx("p",{className:"text-xs text-bambu-gray mt-0.5",children:r})]})]})}function sK({percent:t,color:e="bg-bambu-green"}){return i.jsx("div",{className:"w-full h-2 bg-bambu-dark rounded-full overflow-hidden",children:i.jsx("div",{className:`h-full ${e} transition-all duration-300`,style:{width:`${Math.min(100,t)}%`}})})}function nh({title:t,icon:e,children:n}){return i.jsxs(vt,{className:"p-6",children:[i.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[i.jsx(e,{className:"w-5 h-5 text-bambu-green"}),i.jsx("h2",{className:"text-lg font-semibold text-white",children:t})]}),n]})}function XJe(){const{t}=Ut(),e=tn(),[n,r]=w.useState(null),[a,s]=w.useState(!1),[o,l]=w.useState(!1),{data:c,isLoading:u,refetch:d,isFetching:h}=Je({queryKey:["systemInfo"],queryFn:ne.getSystemInfo,refetchInterval:3e4}),{data:f}=Je({queryKey:["debugLogging"],queryFn:qg.getDebugLoggingState,staleTime:10*1e3,refetchInterval:10*1e3}),{data:p}=Je({queryKey:["settings"],queryFn:ne.getSettings}),{data:x}=Je({queryKey:["library-stats"],queryFn:ne.getLibraryStats}),v=p?.time_format||"system",g=async()=>{l(!0);try{const k=await qg.setDebugLogging(!f?.enabled);e.setQueryData(["debugLogging"],k)}catch(k){console.error("Failed to toggle debug logging:",k)}finally{l(!1)}},y=async()=>{r(null),s(!0);try{await qg.downloadSupportBundle()}catch(k){r(k instanceof Error?k.message:"Failed to download support bundle")}finally{s(!1)}};if(u)return i.jsx("div",{className:"flex items-center justify-center h-64",children:i.jsx(it,{className:"w-8 h-8 text-bambu-green animate-spin"})});if(!c)return i.jsx("div",{className:"p-6 text-center text-bambu-gray",children:t("system.failedToLoad","Failed to load system information")});const _=c.storage.disk_percent_used>90?"bg-red-500":c.storage.disk_percent_used>75?"bg-yellow-500":"bg-bambu-green",N=c.memory.percent_used>90?"bg-red-500":c.memory.percent_used>75?"bg-yellow-500":"bg-bambu-green";return i.jsxs("div",{className:"p-6 space-y-6",children:[i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{children:[i.jsx("h1",{className:"text-2xl font-bold text-white",children:t("system.title","System Information")}),i.jsx("p",{className:"text-bambu-gray mt-1",children:t("system.subtitle","Monitor system resources and database statistics")})]}),i.jsxs("button",{onClick:()=>d(),disabled:h,className:"flex items-center gap-2 px-4 py-2 bg-bambu-dark-secondary hover:bg-bambu-dark-tertiary rounded-lg transition-colors disabled:opacity-50",children:[i.jsx(Cr,{className:`w-4 h-4 ${h?"animate-spin":""}`}),t("common.refresh","Refresh")]})]}),i.jsx(nh,{title:t("system.application","Application"),icon:Um,children:i.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[i.jsx(ka,{icon:Um,label:t("system.version","Version"),value:`v${c.app.version}`}),i.jsx(ka,{icon:Gn,label:t("system.uptime","System Uptime"),value:c.system.uptime_formatted}),i.jsx(ka,{icon:Um,label:t("system.hostname","Hostname"),value:c.system.hostname})]})}),i.jsx(nh,{title:t("support.title","Support & Troubleshooting"),icon:Mme,children:i.jsxs("div",{className:"space-y-4",children:[i.jsx("p",{className:"text-sm text-bambu-gray",children:t("support.description","Enable debug logging to capture detailed information, then download a support bundle to share when reporting issues.")}),i.jsxs("div",{className:"flex items-center justify-between p-4 bg-bambu-dark rounded-lg",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("div",{className:`p-2 rounded-lg ${f?.enabled?"bg-amber-500/20 text-amber-500":"bg-bambu-dark-tertiary text-bambu-gray"}`,children:i.jsx(OC,{className:"w-5 h-5"})}),i.jsxs("div",{children:[i.jsx("p",{className:"font-medium text-white",children:t("support.debugLogging","Debug Logging")}),i.jsxs("p",{className:"text-sm text-bambu-gray",children:[f?.enabled?t("support.debugLoggingEnabled","Capturing detailed logs"):t("support.debugLoggingDisabled","Normal logging level"),f?.enabled&&f.duration_seconds!==null&&i.jsxs("span",{className:"text-amber-400 ml-2",children:["(",Math.floor(f.duration_seconds/60),"m ",f.duration_seconds%60,"s)"]})]})]})]}),i.jsxs("button",{onClick:g,disabled:o,className:`px-4 py-2 rounded-lg font-medium transition-colors flex items-center gap-2 ${f?.enabled?"bg-amber-500/20 text-amber-400 hover:bg-amber-500/30":"bg-bambu-green/20 text-bambu-green hover:bg-bambu-green/30"} disabled:opacity-50`,children:[o&&i.jsx(it,{className:"w-4 h-4 animate-spin"}),f?.enabled?t("support.disableDebug","Disable"):t("support.enableDebug","Enable")]})]}),i.jsxs("div",{className:"flex items-center justify-between p-4 bg-bambu-dark rounded-lg",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("div",{className:"p-2 rounded-lg bg-bambu-dark-tertiary text-bambu-green",children:i.jsx(ua,{className:"w-5 h-5"})}),i.jsxs("div",{children:[i.jsx("p",{className:"font-medium text-white",children:t("support.supportBundle","Support Bundle")}),i.jsx("p",{className:"text-sm text-bambu-gray",children:t("support.supportBundleDescription","Download system info and logs as a ZIP file")})]})]}),i.jsxs("button",{onClick:y,disabled:a||!f?.enabled,className:"px-4 py-2 rounded-lg font-medium bg-bambu-green/20 text-bambu-green hover:bg-bambu-green/30 transition-colors flex items-center gap-2 disabled:opacity-50 disabled:cursor-not-allowed",title:f?.enabled?void 0:t("support.enableDebugFirst","Enable debug logging first"),children:[a&&i.jsx(it,{className:"w-4 h-4 animate-spin"}),t("common.download","Download")]})]}),n&&i.jsx("div",{className:"p-3 bg-red-500/20 border border-red-500/30 rounded-lg text-red-400 text-sm",children:n}),!f?.enabled&&i.jsx("div",{className:"p-4 bg-bambu-dark-tertiary/50 rounded-lg",children:i.jsxs("p",{className:"text-sm text-bambu-gray",children:[i.jsx("span",{className:"text-amber-400 font-medium",children:t("support.instructions","To report an issue:")}),i.jsx("br",{}),"1. ",t("support.step1","Enable debug logging"),i.jsx("br",{}),"2. ",t("support.step2","Reproduce the issue"),i.jsx("br",{}),"3. ",t("support.step3","Download the support bundle"),i.jsx("br",{}),"4. ",t("support.step4","Attach the ZIP file to your issue report")]})}),i.jsxs("div",{className:"p-4 bg-bambu-dark rounded-lg space-y-3",children:[i.jsx("p",{className:"text-sm font-medium text-white",children:t("support.privacyTitle","What's in the support bundle?")}),i.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4 text-sm",children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-bambu-green font-medium mb-1",children:t("support.collected","Collected:")}),i.jsxs("ul",{className:"text-bambu-gray space-y-0.5",children:[i.jsxs("li",{children:["• ",t("support.collectItem1","App version and debug mode")]}),i.jsxs("li",{children:["• ",t("support.collectItem2","OS, architecture, Python version")]}),i.jsxs("li",{children:["• ",t("support.collectItem3","Database statistics (counts only)")]}),i.jsxs("li",{children:["• ",t("support.collectItem4","Printer models and nozzle counts")]}),i.jsxs("li",{children:["• ",t("support.collectItem5","Non-sensitive settings (themes, formats)")]}),i.jsxs("li",{children:["• ",t("support.collectItem6","Debug logs (sanitized)")]}),i.jsxs("li",{children:["• ",t("support.collectItem7","Printer connectivity and firmware versions")]}),i.jsxs("li",{children:["• ",t("support.collectItem8","Integration status (Spoolman, MQTT, HA)")]}),i.jsxs("li",{children:["• ",t("support.collectItem9","Network interfaces (subnets only)")]}),i.jsxs("li",{children:["• ",t("support.collectItem10","Python package versions")]}),i.jsxs("li",{children:["• ",t("support.collectItem11","Database health checks")]}),i.jsxs("li",{children:["• ",t("support.collectItem12","Docker environment details")]})]})]}),i.jsxs("div",{children:[i.jsx("p",{className:"text-red-400 font-medium mb-1",children:t("support.notCollected","NOT collected:")}),i.jsxs("ul",{className:"text-bambu-gray space-y-0.5",children:[i.jsxs("li",{children:["• ",t("support.notItem1","Printer names, IPs, serial numbers")]}),i.jsxs("li",{children:["• ",t("support.notItem2","Access codes and passwords")]}),i.jsxs("li",{children:["• ",t("support.notItem3","Email addresses")]}),i.jsxs("li",{children:["• ",t("support.notItem4","API keys and tokens")]}),i.jsxs("li",{children:["• ",t("support.notItem5","Webhook URLs")]}),i.jsxs("li",{children:["• ",t("support.notItem6","Your hostname or username")]})]})]})]}),i.jsx("p",{className:"text-xs text-bambu-gray/70",children:t("support.privacyNote","IP addresses in logs are replaced with [IP] and email addresses with [EMAIL].")})]}),i.jsx(WJe,{})]})}),i.jsxs(nh,{title:t("system.database","Database"),icon:Pc,children:[i.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4 mb-4",children:[i.jsx(ka,{icon:js,label:t("system.totalArchives","Total Archives"),value:c.database.archives}),i.jsx(ka,{icon:ob,label:t("system.completed","Completed"),value:c.database.archives_completed,color:"text-green-500"}),i.jsx(ka,{icon:hi,label:t("system.failed","Failed"),value:c.database.archives_failed,color:"text-red-500"}),i.jsx(ka,{icon:it,label:t("system.printing","Printing"),value:c.database.archives_printing,color:"text-yellow-500"})]}),i.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[i.jsx(ka,{icon:xr,label:t("system.printers","Printers"),value:c.database.printers}),i.jsx(ka,{icon:VC,label:t("system.filaments","Filaments"),value:c.database.filaments}),i.jsx(ka,{icon:gs,label:t("system.projects","Projects"),value:c.database.projects}),i.jsx(ka,{icon:fl,label:t("system.smartPlugs","Smart Plugs"),value:c.database.smart_plugs})]}),i.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4 mt-4",children:[i.jsx(ka,{icon:Gn,label:t("system.totalPrintTime","Total Print Time"),value:c.database.total_print_time_formatted}),i.jsx(ka,{icon:js,label:t("system.totalFilament","Total Filament Used"),value:`${c.database.total_filament_kg} kg`,subValue:`${c.database.total_filament_grams.toLocaleString()} g`})]})]}),i.jsxs(nh,{title:t("system.connectedPrinters","Connected Printers"),icon:xr,children:[i.jsxs("div",{className:"flex items-center gap-4 mb-4",children:[i.jsx("div",{className:"text-3xl font-bold text-bambu-green",children:c.printers.connected}),i.jsx("div",{className:"text-bambu-gray",children:t("system.ofTotal","of {{total}} printers connected",{total:c.printers.total})})]}),c.printers.connected_list.length>0?i.jsx("div",{className:"space-y-2",children:c.printers.connected_list.map(k=>i.jsxs("div",{className:"flex items-center justify-between p-3 bg-bambu-dark rounded-lg",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("div",{className:"w-2 h-2 rounded-full bg-bambu-green"}),i.jsx("span",{className:"font-medium text-white",children:k.name})]}),i.jsxs("div",{className:"flex items-center gap-4 text-sm text-bambu-gray",children:[i.jsx("span",{children:k.model}),i.jsx("span",{className:`px-2 py-0.5 rounded ${k.state==="RUNNING"?"bg-bambu-green/20 text-bambu-green":k.state==="IDLE"?"bg-blue-500/20 text-blue-400":"bg-bambu-dark-tertiary"}`,children:k.state})]})]},k.id))}):i.jsx("p",{className:"text-bambu-gray",children:t("system.noPrintersConnected","No printers connected")})]}),i.jsx(nh,{title:t("system.storage","Storage"),icon:Ub,children:i.jsxs("div",{className:"space-y-4",children:[i.jsxs("div",{children:[i.jsxs("div",{className:"flex justify-between text-sm mb-1",children:[i.jsx("span",{className:"text-bambu-gray",children:t("system.diskUsage","Disk Usage")}),i.jsxs("span",{className:"text-white",children:[c.storage.disk_used_formatted," / ",c.storage.disk_total_formatted]})]}),i.jsx(sK,{percent:c.storage.disk_percent_used,color:_}),i.jsxs("p",{className:"text-xs text-bambu-gray mt-1",children:[c.storage.disk_free_formatted," ",t("system.free","free")," (",(100-c.storage.disk_percent_used).toFixed(1),"%)"]})]}),i.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[i.jsx(ka,{icon:js,label:t("system.archiveStorage","Archive Storage"),value:c.storage.archive_size_formatted}),i.jsx(ka,{icon:Pc,label:t("system.databaseSize","Database Size"),value:c.storage.database_size_formatted}),x&&i.jsx(ka,{icon:Zl,label:t("system.fileManagerStorage","File Manager"),value:KJe(x.total_size_bytes),subValue:`${x.total_files} files, ${x.total_folders} folders`})]})]})}),i.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6",children:[i.jsx(nh,{title:t("system.memory","Memory"),icon:ofe,children:i.jsx("div",{className:"space-y-4",children:i.jsxs("div",{children:[i.jsxs("div",{className:"flex justify-between text-sm mb-1",children:[i.jsx("span",{className:"text-bambu-gray",children:t("system.memoryUsage","Memory Usage")}),i.jsxs("span",{className:"text-white",children:[c.memory.used_formatted," / ",c.memory.total_formatted]})]}),i.jsx(sK,{percent:c.memory.percent_used,color:N}),i.jsxs("p",{className:"text-xs text-bambu-gray mt-1",children:[c.memory.available_formatted," ",t("system.available","available")]})]})})}),i.jsx(nh,{title:t("system.cpu","CPU"),icon:Jw,children:i.jsx("div",{className:"space-y-4",children:i.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[i.jsx(ka,{icon:Jw,label:t("system.cores","Cores"),value:c.cpu.count,subValue:`${c.cpu.count_logical} logical`}),i.jsx(ka,{icon:Jw,label:t("system.usage","Usage"),value:`${c.cpu.percent}%`})]})})})]}),i.jsx(nh,{title:t("system.systemDetails","System Details"),icon:Um,children:i.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[i.jsx(ka,{icon:Um,label:t("system.os","Operating System"),value:c.system.platform,subValue:c.system.platform_release}),i.jsx(ka,{icon:Jw,label:t("system.architecture","Architecture"),value:c.system.architecture}),i.jsx(ka,{icon:Um,label:t("system.python","Python"),value:c.system.python_version}),i.jsx(ka,{icon:Gn,label:t("system.bootTime","Boot Time"),value:jf(c.system.boot_time,v)})]})})]})}function YJe(){const t=rc(),{t:e}=Ut(),{login:n}=Or(),{showToast:r}=cn(),{mode:a}=Jf(),[s,o]=w.useState(""),[l,c]=w.useState(""),[u,d]=w.useState(!1),[h,f]=w.useState(""),{data:p}=Je({queryKey:["advancedAuthStatus"],queryFn:()=>ne.getAdvancedAuthStatus()}),x=ot({mutationFn:()=>n(s,l),onSuccess:()=>{r(e("login.loginSuccess")),t("/")},onError:_=>{r(_.message||e("login.loginFailed"),"error")}}),v=ot({mutationFn:_=>ne.forgotPassword({email:_}),onSuccess:_=>{r(_.message,"success"),d(!1),f("")},onError:_=>{r(_.message,"error")}}),g=_=>{if(_.preventDefault(),!s||!l){r(e("login.enterCredentials"),"error");return}x.mutate()},y=_=>{if(_.preventDefault(),!h){r("Please enter your email address","error");return}v.mutate(h)};return i.jsxs("div",{className:"min-h-screen flex items-center justify-center bg-bambu-dark p-4",children:[i.jsxs("div",{className:"max-w-md w-full space-y-8 p-8 bg-gradient-to-br from-bambu-card to-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary shadow-lg",children:[i.jsxs("div",{className:"text-center",children:[i.jsx("div",{className:"flex items-center justify-center mb-6",children:i.jsx("img",{src:a==="dark"?"/img/bambuddy_logo_dark_transparent.png":"/img/bambuddy_logo_light.png",alt:"Bambuddy",className:"h-16"})}),i.jsx("h2",{className:"text-3xl font-bold text-white",children:e("login.title")}),i.jsx("p",{className:"mt-2 text-sm text-bambu-gray",children:e("login.subtitle")})]}),i.jsxs("form",{className:"mt-8 space-y-6",onSubmit:g,children:[i.jsxs("div",{className:"space-y-4",children:[i.jsxs("div",{children:[i.jsx("label",{htmlFor:"username",className:"block text-sm font-medium text-white mb-2",children:p?.advanced_auth_enabled?e("login.usernameOrEmail")||"Username or Email":e("login.username")}),i.jsx("input",{id:"username",type:"text",required:!0,value:s,onChange:_=>o(_.target.value),className:"block 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:p?.advanced_auth_enabled?e("login.usernameOrEmailPlaceholder")||"Enter your username or email":e("login.usernamePlaceholder"),autoComplete:"username"})]}),i.jsxs("div",{children:[i.jsx("label",{htmlFor:"password",className:"block text-sm font-medium text-white mb-2",children:e("login.password")}),i.jsx("input",{id:"password",type:"password",required:!0,value:l,onChange:_=>c(_.target.value),className:"block 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:e("login.passwordPlaceholder"),autoComplete:"current-password"})]})]}),i.jsx("div",{children:i.jsx("button",{type:"submit",disabled:x.isPending,className:"w-full flex justify-center py-3 px-4 bg-bambu-green hover:bg-bambu-green-light text-white font-medium rounded-lg shadow-lg shadow-bambu-green/20 hover:shadow-bambu-green/30 focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:ring-offset-2 focus:ring-offset-bambu-dark-secondary transition-all disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:bg-bambu-green",children:x.isPending?e("login.signingIn"):e("login.signIn")})}),p?.advanced_auth_enabled&&i.jsx("div",{className:"text-center",children:i.jsx("button",{type:"button",onClick:()=>d(!0),className:"text-sm text-bambu-gray hover:text-bambu-green transition-colors",children:e("login.forgotPassword")})})]})]}),u&&i.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:()=>d(!1),children:i.jsxs(vt,{className:"w-full max-w-md",onClick:_=>_.stopPropagation(),children:[i.jsx(In,{children:i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(fv,{className:"w-5 h-5 text-bambu-green"}),i.jsx("h2",{className:"text-lg font-semibold text-white",children:e("login.forgotPasswordTitle")})]}),i.jsx(Ce,{variant:"ghost",size:"sm",onClick:()=>{d(!1),f("")},children:i.jsx(Ft,{className:"w-5 h-5"})})]})}),i.jsx(_t,{children:p?.advanced_auth_enabled?i.jsxs("form",{onSubmit:y,className:"space-y-4",children:[i.jsx("p",{className:"text-bambu-gray text-sm",children:e("login.forgotPasswordEmailMessage")||"Enter your email address and we'll send you a new password."}),i.jsxs("div",{children:[i.jsx("label",{htmlFor:"forgot-email",className:"block text-sm font-medium text-white mb-2",children:e("login.emailAddress")||"Email Address"}),i.jsx("input",{id:"forgot-email",type:"email",required:!0,value:h,onChange:_=>f(_.target.value),className:"block 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:e("login.emailPlaceholder")||"your.email@example.com"})]}),i.jsxs("div",{className:"flex gap-2",children:[i.jsx(Ce,{type:"button",variant:"secondary",className:"flex-1",onClick:()=>{d(!1),f("")},children:e("login.cancel")||"Cancel"}),i.jsx(Ce,{type:"submit",className:"flex-1",disabled:v.isPending,children:v.isPending?e("login.sending")||"Sending...":e("login.sendResetEmail")||"Send Reset Email"})]})]}):i.jsxs("div",{className:"space-y-4",children:[i.jsx("p",{className:"text-bambu-gray",children:e("login.forgotPasswordMessage")}),i.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4 space-y-2",children:[i.jsx("p",{className:"text-sm text-white font-medium",children:e("login.howToReset")}),i.jsxs("ol",{className:"text-sm text-bambu-gray space-y-1 list-decimal list-inside",children:[i.jsx("li",{children:e("login.resetStep1")}),i.jsx("li",{children:e("login.resetStep2")}),i.jsx("li",{children:e("login.resetStep3")}),i.jsx("li",{children:e("login.resetStep4")})]})]}),i.jsx(Ce,{variant:"secondary",className:"w-full",onClick:()=>d(!1),children:e("login.gotIt")})]})})]})})]})}function QJe(){const t=rc(),{t:e}=Ut(),{showToast:n}=cn(),{mode:r}=Jf(),{refreshAuth:a}=Or(),[s,o]=w.useState(!1),[l,c]=w.useState(""),[u,d]=w.useState(""),[h,f]=w.useState(""),p=ot({mutationFn:()=>ne.setupAuth({auth_enabled:s,admin_username:s?l:void 0,admin_password:s?u:void 0}),onSuccess:async v=>{await a(),v.auth_enabled?v.admin_created?(n(e("setup.toast.authEnabledAdminCreated")),t("/login")):(n(e("setup.toast.authEnabledExistingAdmins")),t("/login")):(n(e("setup.toast.setupCompleted")),t("/"))},onError:v=>{n(v.message,"error")}}),x=v=>{if(v.preventDefault(),s&&(l||u)){if(!l||!u){n(e("setup.toast.enterBothCredentials"),"error");return}if(u!==h){n(e("setup.toast.passwordsDoNotMatch"),"error");return}if(u.length<6){n(e("setup.toast.passwordTooShort"),"error");return}}p.mutate()};return i.jsx("div",{className:"min-h-screen flex items-center justify-center bg-bambu-dark p-4",children:i.jsxs("div",{className:"max-w-md w-full space-y-8 p-8 bg-gradient-to-br from-bambu-card to-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary shadow-lg",children:[i.jsxs("div",{className:"text-center",children:[i.jsx("div",{className:"flex items-center justify-center mb-6",children:i.jsx("img",{src:r==="dark"?"/img/bambuddy_logo_dark_transparent.png":"/img/bambuddy_logo_light.png",alt:"Bambuddy",className:"h-16"})}),i.jsx("h2",{className:"text-3xl font-bold text-white",children:e("setup.title")}),i.jsx("p",{className:"mt-2 text-sm text-bambu-gray",children:e("setup.subtitle")})]}),i.jsxs("form",{className:"mt-8 space-y-6",onSubmit:x,children:[i.jsxs("div",{className:"space-y-4",children:[i.jsxs("div",{className:"flex items-center p-4 bg-bambu-dark-secondary/50 rounded-lg border border-bambu-dark-tertiary",children:[i.jsx("input",{id:"auth-enabled",type:"checkbox",checked:s,onChange:v=>o(v.target.checked),className:"h-4 w-4 text-bambu-green focus:ring-bambu-green border-bambu-dark-tertiary rounded bg-bambu-dark-secondary"}),i.jsx("label",{htmlFor:"auth-enabled",className:"ml-3 block text-sm font-medium text-white",children:e("setup.enableAuth")})]}),s&&i.jsxs("div",{className:"space-y-4 mt-4",children:[i.jsx("div",{className:"p-3 bg-bambu-dark-secondary/50 border border-bambu-dark-tertiary rounded-lg",children:i.jsxs("div",{className:"flex items-start gap-2",children:[i.jsx(Zs,{className:"w-4 h-4 text-bambu-green mt-0.5 flex-shrink-0"}),i.jsxs("div",{className:"text-sm text-bambu-gray",children:[i.jsx("p",{className:"text-white font-medium mb-1",children:e("setup.adminAccount")}),i.jsx("p",{children:e("setup.adminAccountDesc")})]})]})}),i.jsxs("div",{children:[i.jsxs("label",{htmlFor:"admin-username",className:"block text-sm font-medium text-white mb-2",children:[e("setup.adminUsername")," ",i.jsx("span",{className:"text-bambu-gray text-xs",children:e("setup.optionalIfAdminExists")})]}),i.jsx("input",{id:"admin-username",type:"text",value:l,onChange:v=>c(v.target.value),className:"block 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:e("setup.adminUsernamePlaceholder"),autoComplete:"username"})]}),i.jsxs("div",{children:[i.jsxs("label",{htmlFor:"admin-password",className:"block text-sm font-medium text-white mb-2",children:[e("setup.adminPassword")," ",i.jsx("span",{className:"text-bambu-gray text-xs",children:e("setup.optionalIfAdminExists")})]}),i.jsx("input",{id:"admin-password",type:"password",value:u,onChange:v=>d(v.target.value),className:"block 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:e("setup.adminPasswordPlaceholder"),minLength:6,autoComplete:"new-password"})]}),u&&i.jsxs("div",{children:[i.jsx("label",{htmlFor:"confirm-password",className:"block text-sm font-medium text-white mb-2",children:e("setup.confirmPassword")}),i.jsx("input",{id:"confirm-password",type:"password",value:h,onChange:v=>f(v.target.value),className:"block 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:e("setup.confirmPasswordPlaceholder"),minLength:6,autoComplete:"new-password"})]})]})]}),i.jsx("div",{children:i.jsx("button",{type:"submit",disabled:p.isPending,className:"w-full flex justify-center py-3 px-4 bg-bambu-green hover:bg-bambu-green-light text-white font-medium rounded-lg shadow-lg shadow-bambu-green/20 hover:shadow-bambu-green/30 focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:ring-offset-2 focus:ring-offset-bambu-dark-secondary transition-all disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:bg-bambu-green",children:p.isPending?e("setup.settingUp"):e("setup.completeSetup")})})]})]})})}function ZJe(){const t=w.useRef(null),e=w.useRef(null),n=tn(),[r,a]=w.useState(!1),s=w.useRef(new Set),o=w.useRef(null),l=w.useRef(new Map),c=w.useRef(null),u=w.useRef([]),d=w.useRef(!1),h=w.useRef(()=>{}),f=w.useCallback(()=>{if(d.current||u.current.length===0)return;d.current=!0;const _=()=>{const N=u.current.shift();N?requestAnimationFrame(()=>{h.current(N),u.current.length>0?setTimeout(_,16):d.current=!1}):d.current=!1};_()},[]),p=w.useCallback(()=>{if(t.current?.readyState===WebSocket.OPEN)return;const N=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/api/v1/ws`,k=new WebSocket(N);let A=null;k.onopen=()=>{console.log("[WebSocket] Connected"),a(!0),A=window.setInterval(()=>{k.readyState===WebSocket.OPEN&&k.send(JSON.stringify({type:"ping"}))},3e4)},k.onmessage=M=>{try{const C=JSON.parse(M.data);C.type==="printer_status"&&C.printer_id!==void 0&&C.data?h.current(C):(u.current.push(C),f())}catch{}},k.onclose=M=>{console.log("[WebSocket] Closed",M.code,M.reason),A&&(clearInterval(A),A=null),a(!1),t.current=null,e.current=window.setTimeout(()=>{p()},3e3)},k.onerror=M=>{console.error("[WebSocket] Error",M),k.close()},t.current=k},[f]),x=w.useCallback((_,N)=>{const k=l.current.get(_)||{};l.current.set(_,{...k,...N}),c.current||(c.current=window.setTimeout(()=>{const A=new Map(l.current);l.current.clear(),c.current=null,requestAnimationFrame(()=>{A.forEach((M,C)=>{n.setQueryData(["printerStatus",C],j=>{const P={...j,...M};return P.wifi_signal==null&&j?.wifi_signal!=null&&(P.wifi_signal=j.wifi_signal),P})})})},100))},[n]),v=w.useCallback(_=>{s.current.add(_),o.current&&clearTimeout(o.current),o.current=window.setTimeout(()=>{const N=Array.from(s.current);s.current.clear(),o.current=null;let k=0;N.forEach(A=>{setTimeout(()=>{requestAnimationFrame(()=>{n.invalidateQueries({queryKey:[A]})})},k),k+=500})},3e3)},[n]),g=w.useCallback(_=>{switch(_.type){case"printer_status":_.printer_id!==void 0&&_.data&&x(_.printer_id,_.data);break;case"print_start":_.printer_id!==void 0&&n.invalidateQueries({queryKey:["printerStatus",_.printer_id]});break;case"print_complete":v("archives"),v("archiveStats");break;case"archive_created":v("archives"),v("archiveStats");break;case"archive_updated":v("archives");break;case"pong":break;case"plate_not_empty":window.dispatchEvent(new CustomEvent("plate-not-empty",{detail:{printer_id:_.printer_id,printer_name:_.printer_name,message:_.message}}));break;case"spool_auto_assigned":v("inventory-spools"),v("spool-assignments");break;case"spool_usage_logged":v("inventory-spools");break;case"unknown_tag":window.dispatchEvent(new CustomEvent("unknown-tag",{detail:{printer_id:_.printer_id,ams_id:_.ams_id,tray_id:_.tray_id,tag_uid:_.tag_uid,tray_uuid:_.tray_uuid}}));break;case"background_dispatch":window.dispatchEvent(new CustomEvent("background-dispatch",{detail:_.data||{}}));break}},[n,v,x]);w.useEffect(()=>{h.current=g},[g]),w.useEffect(()=>(p(),()=>{e.current&&clearTimeout(e.current),o.current&&clearTimeout(o.current),c.current&&clearTimeout(c.current),t.current&&t.current.close()}),[p]);const y=w.useCallback(_=>{t.current?.readyState===WebSocket.OPEN&&t.current.send(JSON.stringify(_))},[]);return{isConnected:r,sendMessage:y}}const JJe=new ode({defaultOptions:{queries:{staleTime:1e3*60,retry:1}}});function eet({children:t}){return ZJe(),i.jsx(i.Fragment,{children:t})}function tet({children:t}){const{authEnabled:e,loading:n,user:r}=Or();return n?i.jsx("div",{className:"min-h-screen flex items-center justify-center",children:"Loading..."}):e&&!r?i.jsx(ab,{to:"/login",replace:!0}):i.jsx(i.Fragment,{children:t})}function Fj({children:t}){const{authEnabled:e,loading:n,user:r,isAdmin:a}=Or();return n?i.jsx("div",{className:"min-h-screen flex items-center justify-center",children:"Loading..."}):e?r?a?i.jsx(i.Fragment,{children:t}):i.jsx(ab,{to:"/",replace:!0}):i.jsx(ab,{to:"/login",replace:!0}):i.jsx(i.Fragment,{children:t})}function net({children:t}){const{authEnabled:e,loading:n}=Or();return n?i.jsx("div",{className:"min-h-screen flex items-center justify-center",children:"Loading..."}):e?i.jsx(ab,{to:"/login",replace:!0}):i.jsx(i.Fragment,{children:t})}function ret(){return i.jsx(Zpe,{children:i.jsx(sge,{children:i.jsx(lde,{client:JJe,children:i.jsx(age,{children:i.jsx(Aue,{children:i.jsxs(nue,{children:[i.jsx(fa,{path:"/setup",element:i.jsx(net,{children:i.jsx(QJe,{})})}),i.jsx(fa,{path:"/login",element:i.jsx(YJe,{})}),i.jsx(fa,{path:"/camera/:printerId",element:i.jsx(cJe,{})}),i.jsx(fa,{path:"/overlay/:printerId",element:i.jsx(mJe,{})}),i.jsxs(fa,{element:i.jsx(tet,{children:i.jsx(eet,{children:i.jsx(uge,{})})}),children:[i.jsx(fa,{index:!0,element:i.jsx(c$e,{})}),i.jsx(fa,{path:"archives",element:i.jsx(XXe,{})}),i.jsx(fa,{path:"queue",element:i.jsx(DQe,{})}),i.jsx(fa,{path:"stats",element:i.jsx(WQe,{})}),i.jsx(fa,{path:"profiles",element:i.jsx(IZe,{})}),i.jsx(fa,{path:"maintenance",element:i.jsx($Ze,{})}),i.jsx(fa,{path:"projects",element:i.jsx(qZe,{})}),i.jsx(fa,{path:"projects/:id",element:i.jsx(ZZe,{})}),i.jsx(fa,{path:"inventory",element:i.jsx(VJe,{})}),i.jsx(fa,{path:"files",element:i.jsx(iJe,{})}),i.jsx(fa,{path:"settings",element:i.jsx(Fj,{children:i.jsx(NZe,{})})}),i.jsx(fa,{path:"groups/new",element:i.jsx(Fj,{children:i.jsx(tK,{})})}),i.jsx(fa,{path:"groups/:id/edit",element:i.jsx(Fj,{children:i.jsx(tK,{})})}),i.jsx(fa,{path:"users",element:i.jsx(ab,{to:"/settings?tab=users",replace:!0})}),i.jsx(fa,{path:"groups",element:i.jsx(ab,{to:"/settings?tab=users",replace:!0})}),i.jsx(fa,{path:"system",element:i.jsx(XJe,{})}),i.jsx(fa,{path:"external/:id",element:i.jsx(fJe,{})})]})]})})})})})})}Yoe.createRoot(document.getElementById("root")).render(i.jsx(w.StrictMode,{children:i.jsx(ret,{})})); +`)[0]}),E&&i.jsx("span",{className:"text-bambu-gray/50 shrink-0",children:P?i.jsx(yl,{className:"w-3.5 h-3.5"}):i.jsx(Un,{className:"w-3.5 h-3.5"})})]})},j)})})}),i.jsx("div",{className:"flex items-center justify-between p-3 border-t border-bambu-dark-tertiary text-sm text-bambu-gray",children:h?i.jsxs("span",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"w-2 h-2 bg-green-500 rounded-full animate-pulse"}),"Auto-refreshing every 2 seconds"]}):i.jsx("span",{children:"Click Start to enable live log streaming"})})]})]})}function KJe(t){return t<1024?`${t} B`:t<1024*1024?`${(t/1024).toFixed(1)} KB`:t<1024*1024*1024?`${(t/(1024*1024)).toFixed(1)} MB`:`${(t/(1024*1024*1024)).toFixed(2)} GB`}function ka({icon:t,label:e,value:n,subValue:r,color:a="text-bambu-green"}){return i.jsxs("div",{className:"flex items-start gap-3 p-4 bg-bambu-dark rounded-lg",children:[i.jsx("div",{className:`p-2 rounded-lg bg-bambu-dark-tertiary ${a}`,children:i.jsx(t,{className:"w-5 h-5"})}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsx("p",{className:"text-sm text-bambu-gray",children:e}),i.jsx("p",{className:"text-lg font-semibold text-white truncate",children:n}),r&&i.jsx("p",{className:"text-xs text-bambu-gray mt-0.5",children:r})]})]})}function sK({percent:t,color:e="bg-bambu-green"}){return i.jsx("div",{className:"w-full h-2 bg-bambu-dark rounded-full overflow-hidden",children:i.jsx("div",{className:`h-full ${e} transition-all duration-300`,style:{width:`${Math.min(100,t)}%`}})})}function nh({title:t,icon:e,children:n}){return i.jsxs(vt,{className:"p-6",children:[i.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[i.jsx(e,{className:"w-5 h-5 text-bambu-green"}),i.jsx("h2",{className:"text-lg font-semibold text-white",children:t})]}),n]})}function XJe(){const{t}=Ut(),e=tn(),[n,r]=w.useState(null),[a,s]=w.useState(!1),[o,l]=w.useState(!1),{data:c,isLoading:u,refetch:d,isFetching:h}=Je({queryKey:["systemInfo"],queryFn:ne.getSystemInfo,refetchInterval:3e4}),{data:f}=Je({queryKey:["debugLogging"],queryFn:qg.getDebugLoggingState,staleTime:10*1e3,refetchInterval:10*1e3}),{data:p}=Je({queryKey:["settings"],queryFn:ne.getSettings}),{data:x}=Je({queryKey:["library-stats"],queryFn:ne.getLibraryStats}),v=p?.time_format||"system",g=async()=>{l(!0);try{const k=await qg.setDebugLogging(!f?.enabled);e.setQueryData(["debugLogging"],k)}catch(k){console.error("Failed to toggle debug logging:",k)}finally{l(!1)}},y=async()=>{r(null),s(!0);try{await qg.downloadSupportBundle()}catch(k){r(k instanceof Error?k.message:"Failed to download support bundle")}finally{s(!1)}};if(u)return i.jsx("div",{className:"flex items-center justify-center h-64",children:i.jsx(it,{className:"w-8 h-8 text-bambu-green animate-spin"})});if(!c)return i.jsx("div",{className:"p-6 text-center text-bambu-gray",children:t("system.failedToLoad","Failed to load system information")});const _=c.storage.disk_percent_used>90?"bg-red-500":c.storage.disk_percent_used>75?"bg-yellow-500":"bg-bambu-green",N=c.memory.percent_used>90?"bg-red-500":c.memory.percent_used>75?"bg-yellow-500":"bg-bambu-green";return i.jsxs("div",{className:"p-6 space-y-6",children:[i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{children:[i.jsx("h1",{className:"text-2xl font-bold text-white",children:t("system.title","System Information")}),i.jsx("p",{className:"text-bambu-gray mt-1",children:t("system.subtitle","Monitor system resources and database statistics")})]}),i.jsxs("button",{onClick:()=>d(),disabled:h,className:"flex items-center gap-2 px-4 py-2 bg-bambu-dark-secondary hover:bg-bambu-dark-tertiary rounded-lg transition-colors disabled:opacity-50",children:[i.jsx(Cr,{className:`w-4 h-4 ${h?"animate-spin":""}`}),t("common.refresh","Refresh")]})]}),i.jsx(nh,{title:t("system.application","Application"),icon:Um,children:i.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[i.jsx(ka,{icon:Um,label:t("system.version","Version"),value:`v${c.app.version}`}),i.jsx(ka,{icon:Gn,label:t("system.uptime","System Uptime"),value:c.system.uptime_formatted}),i.jsx(ka,{icon:Um,label:t("system.hostname","Hostname"),value:c.system.hostname})]})}),i.jsx(nh,{title:t("support.title","Support & Troubleshooting"),icon:Mme,children:i.jsxs("div",{className:"space-y-4",children:[i.jsx("p",{className:"text-sm text-bambu-gray",children:t("support.description","Enable debug logging to capture detailed information, then download a support bundle to share when reporting issues.")}),i.jsxs("div",{className:"flex items-center justify-between p-4 bg-bambu-dark rounded-lg",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("div",{className:`p-2 rounded-lg ${f?.enabled?"bg-amber-500/20 text-amber-500":"bg-bambu-dark-tertiary text-bambu-gray"}`,children:i.jsx(OC,{className:"w-5 h-5"})}),i.jsxs("div",{children:[i.jsx("p",{className:"font-medium text-white",children:t("support.debugLogging","Debug Logging")}),i.jsxs("p",{className:"text-sm text-bambu-gray",children:[f?.enabled?t("support.debugLoggingEnabled","Capturing detailed logs"):t("support.debugLoggingDisabled","Normal logging level"),f?.enabled&&f.duration_seconds!==null&&i.jsxs("span",{className:"text-amber-400 ml-2",children:["(",Math.floor(f.duration_seconds/60),"m ",f.duration_seconds%60,"s)"]})]})]})]}),i.jsxs("button",{onClick:g,disabled:o,className:`px-4 py-2 rounded-lg font-medium transition-colors flex items-center gap-2 ${f?.enabled?"bg-amber-500/20 text-amber-400 hover:bg-amber-500/30":"bg-bambu-green/20 text-bambu-green hover:bg-bambu-green/30"} disabled:opacity-50`,children:[o&&i.jsx(it,{className:"w-4 h-4 animate-spin"}),f?.enabled?t("support.disableDebug","Disable"):t("support.enableDebug","Enable")]})]}),i.jsxs("div",{className:"flex items-center justify-between p-4 bg-bambu-dark rounded-lg",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("div",{className:"p-2 rounded-lg bg-bambu-dark-tertiary text-bambu-green",children:i.jsx(ua,{className:"w-5 h-5"})}),i.jsxs("div",{children:[i.jsx("p",{className:"font-medium text-white",children:t("support.supportBundle","Support Bundle")}),i.jsx("p",{className:"text-sm text-bambu-gray",children:t("support.supportBundleDescription","Download system info and logs as a ZIP file")})]})]}),i.jsxs("button",{onClick:y,disabled:a||!f?.enabled,className:"px-4 py-2 rounded-lg font-medium bg-bambu-green/20 text-bambu-green hover:bg-bambu-green/30 transition-colors flex items-center gap-2 disabled:opacity-50 disabled:cursor-not-allowed",title:f?.enabled?void 0:t("support.enableDebugFirst","Enable debug logging first"),children:[a&&i.jsx(it,{className:"w-4 h-4 animate-spin"}),t("common.download","Download")]})]}),n&&i.jsx("div",{className:"p-3 bg-red-500/20 border border-red-500/30 rounded-lg text-red-400 text-sm",children:n}),!f?.enabled&&i.jsx("div",{className:"p-4 bg-bambu-dark-tertiary/50 rounded-lg",children:i.jsxs("p",{className:"text-sm text-bambu-gray",children:[i.jsx("span",{className:"text-amber-400 font-medium",children:t("support.instructions","To report an issue:")}),i.jsx("br",{}),"1. ",t("support.step1","Enable debug logging"),i.jsx("br",{}),"2. ",t("support.step2","Reproduce the issue"),i.jsx("br",{}),"3. ",t("support.step3","Download the support bundle"),i.jsx("br",{}),"4. ",t("support.step4","Attach the ZIP file to your issue report")]})}),i.jsxs("div",{className:"p-4 bg-bambu-dark rounded-lg space-y-3",children:[i.jsx("p",{className:"text-sm font-medium text-white",children:t("support.privacyTitle","What's in the support bundle?")}),i.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4 text-sm",children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-bambu-green font-medium mb-1",children:t("support.collected","Collected:")}),i.jsxs("ul",{className:"text-bambu-gray space-y-0.5",children:[i.jsxs("li",{children:["• ",t("support.collectItem1","App version and debug mode")]}),i.jsxs("li",{children:["• ",t("support.collectItem2","OS, architecture, Python version")]}),i.jsxs("li",{children:["• ",t("support.collectItem3","Database statistics (counts only)")]}),i.jsxs("li",{children:["• ",t("support.collectItem4","Printer models and nozzle counts")]}),i.jsxs("li",{children:["• ",t("support.collectItem5","Non-sensitive settings (themes, formats)")]}),i.jsxs("li",{children:["• ",t("support.collectItem6","Debug logs (sanitized)")]}),i.jsxs("li",{children:["• ",t("support.collectItem7","Printer connectivity and firmware versions")]}),i.jsxs("li",{children:["• ",t("support.collectItem8","Integration status (Spoolman, MQTT, HA)")]}),i.jsxs("li",{children:["• ",t("support.collectItem9","Network interfaces (subnets only)")]}),i.jsxs("li",{children:["• ",t("support.collectItem10","Python package versions")]}),i.jsxs("li",{children:["• ",t("support.collectItem11","Database health checks")]}),i.jsxs("li",{children:["• ",t("support.collectItem12","Docker environment details")]})]})]}),i.jsxs("div",{children:[i.jsx("p",{className:"text-red-400 font-medium mb-1",children:t("support.notCollected","NOT collected:")}),i.jsxs("ul",{className:"text-bambu-gray space-y-0.5",children:[i.jsxs("li",{children:["• ",t("support.notItem1","Printer names and serial numbers")]}),i.jsxs("li",{children:["• ",t("support.notItem2","Access codes and passwords")]}),i.jsxs("li",{children:["• ",t("support.notItem3","Email addresses")]}),i.jsxs("li",{children:["• ",t("support.notItem4","API keys and tokens")]}),i.jsxs("li",{children:["• ",t("support.notItem5","Webhook URLs")]}),i.jsxs("li",{children:["• ",t("support.notItem6","Your hostname or username")]})]})]})]}),i.jsx("p",{className:"text-xs text-bambu-gray/70",children:t("support.privacyNote","Email addresses in logs are replaced with [EMAIL], printer names with [PRINTER], and serial numbers with [SERIAL].")})]}),i.jsx(WJe,{})]})}),i.jsxs(nh,{title:t("system.database","Database"),icon:Pc,children:[i.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4 mb-4",children:[i.jsx(ka,{icon:js,label:t("system.totalArchives","Total Archives"),value:c.database.archives}),i.jsx(ka,{icon:ob,label:t("system.completed","Completed"),value:c.database.archives_completed,color:"text-green-500"}),i.jsx(ka,{icon:hi,label:t("system.failed","Failed"),value:c.database.archives_failed,color:"text-red-500"}),i.jsx(ka,{icon:it,label:t("system.printing","Printing"),value:c.database.archives_printing,color:"text-yellow-500"})]}),i.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[i.jsx(ka,{icon:xr,label:t("system.printers","Printers"),value:c.database.printers}),i.jsx(ka,{icon:VC,label:t("system.filaments","Filaments"),value:c.database.filaments}),i.jsx(ka,{icon:gs,label:t("system.projects","Projects"),value:c.database.projects}),i.jsx(ka,{icon:fl,label:t("system.smartPlugs","Smart Plugs"),value:c.database.smart_plugs})]}),i.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4 mt-4",children:[i.jsx(ka,{icon:Gn,label:t("system.totalPrintTime","Total Print Time"),value:c.database.total_print_time_formatted}),i.jsx(ka,{icon:js,label:t("system.totalFilament","Total Filament Used"),value:`${c.database.total_filament_kg} kg`,subValue:`${c.database.total_filament_grams.toLocaleString()} g`})]})]}),i.jsxs(nh,{title:t("system.connectedPrinters","Connected Printers"),icon:xr,children:[i.jsxs("div",{className:"flex items-center gap-4 mb-4",children:[i.jsx("div",{className:"text-3xl font-bold text-bambu-green",children:c.printers.connected}),i.jsx("div",{className:"text-bambu-gray",children:t("system.ofTotal","of {{total}} printers connected",{total:c.printers.total})})]}),c.printers.connected_list.length>0?i.jsx("div",{className:"space-y-2",children:c.printers.connected_list.map(k=>i.jsxs("div",{className:"flex items-center justify-between p-3 bg-bambu-dark rounded-lg",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("div",{className:"w-2 h-2 rounded-full bg-bambu-green"}),i.jsx("span",{className:"font-medium text-white",children:k.name})]}),i.jsxs("div",{className:"flex items-center gap-4 text-sm text-bambu-gray",children:[i.jsx("span",{children:k.model}),i.jsx("span",{className:`px-2 py-0.5 rounded ${k.state==="RUNNING"?"bg-bambu-green/20 text-bambu-green":k.state==="IDLE"?"bg-blue-500/20 text-blue-400":"bg-bambu-dark-tertiary"}`,children:k.state})]})]},k.id))}):i.jsx("p",{className:"text-bambu-gray",children:t("system.noPrintersConnected","No printers connected")})]}),i.jsx(nh,{title:t("system.storage","Storage"),icon:Ub,children:i.jsxs("div",{className:"space-y-4",children:[i.jsxs("div",{children:[i.jsxs("div",{className:"flex justify-between text-sm mb-1",children:[i.jsx("span",{className:"text-bambu-gray",children:t("system.diskUsage","Disk Usage")}),i.jsxs("span",{className:"text-white",children:[c.storage.disk_used_formatted," / ",c.storage.disk_total_formatted]})]}),i.jsx(sK,{percent:c.storage.disk_percent_used,color:_}),i.jsxs("p",{className:"text-xs text-bambu-gray mt-1",children:[c.storage.disk_free_formatted," ",t("system.free","free")," (",(100-c.storage.disk_percent_used).toFixed(1),"%)"]})]}),i.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[i.jsx(ka,{icon:js,label:t("system.archiveStorage","Archive Storage"),value:c.storage.archive_size_formatted}),i.jsx(ka,{icon:Pc,label:t("system.databaseSize","Database Size"),value:c.storage.database_size_formatted}),x&&i.jsx(ka,{icon:Zl,label:t("system.fileManagerStorage","File Manager"),value:KJe(x.total_size_bytes),subValue:`${x.total_files} files, ${x.total_folders} folders`})]})]})}),i.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6",children:[i.jsx(nh,{title:t("system.memory","Memory"),icon:ofe,children:i.jsx("div",{className:"space-y-4",children:i.jsxs("div",{children:[i.jsxs("div",{className:"flex justify-between text-sm mb-1",children:[i.jsx("span",{className:"text-bambu-gray",children:t("system.memoryUsage","Memory Usage")}),i.jsxs("span",{className:"text-white",children:[c.memory.used_formatted," / ",c.memory.total_formatted]})]}),i.jsx(sK,{percent:c.memory.percent_used,color:N}),i.jsxs("p",{className:"text-xs text-bambu-gray mt-1",children:[c.memory.available_formatted," ",t("system.available","available")]})]})})}),i.jsx(nh,{title:t("system.cpu","CPU"),icon:Jw,children:i.jsx("div",{className:"space-y-4",children:i.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[i.jsx(ka,{icon:Jw,label:t("system.cores","Cores"),value:c.cpu.count,subValue:`${c.cpu.count_logical} logical`}),i.jsx(ka,{icon:Jw,label:t("system.usage","Usage"),value:`${c.cpu.percent}%`})]})})})]}),i.jsx(nh,{title:t("system.systemDetails","System Details"),icon:Um,children:i.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[i.jsx(ka,{icon:Um,label:t("system.os","Operating System"),value:c.system.platform,subValue:c.system.platform_release}),i.jsx(ka,{icon:Jw,label:t("system.architecture","Architecture"),value:c.system.architecture}),i.jsx(ka,{icon:Um,label:t("system.python","Python"),value:c.system.python_version}),i.jsx(ka,{icon:Gn,label:t("system.bootTime","Boot Time"),value:jf(c.system.boot_time,v)})]})})]})}function YJe(){const t=rc(),{t:e}=Ut(),{login:n}=Or(),{showToast:r}=cn(),{mode:a}=Jf(),[s,o]=w.useState(""),[l,c]=w.useState(""),[u,d]=w.useState(!1),[h,f]=w.useState(""),{data:p}=Je({queryKey:["advancedAuthStatus"],queryFn:()=>ne.getAdvancedAuthStatus()}),x=ot({mutationFn:()=>n(s,l),onSuccess:()=>{r(e("login.loginSuccess")),t("/")},onError:_=>{r(_.message||e("login.loginFailed"),"error")}}),v=ot({mutationFn:_=>ne.forgotPassword({email:_}),onSuccess:_=>{r(_.message,"success"),d(!1),f("")},onError:_=>{r(_.message,"error")}}),g=_=>{if(_.preventDefault(),!s||!l){r(e("login.enterCredentials"),"error");return}x.mutate()},y=_=>{if(_.preventDefault(),!h){r("Please enter your email address","error");return}v.mutate(h)};return i.jsxs("div",{className:"min-h-screen flex items-center justify-center bg-bambu-dark p-4",children:[i.jsxs("div",{className:"max-w-md w-full space-y-8 p-8 bg-gradient-to-br from-bambu-card to-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary shadow-lg",children:[i.jsxs("div",{className:"text-center",children:[i.jsx("div",{className:"flex items-center justify-center mb-6",children:i.jsx("img",{src:a==="dark"?"/img/bambuddy_logo_dark_transparent.png":"/img/bambuddy_logo_light.png",alt:"Bambuddy",className:"h-16"})}),i.jsx("h2",{className:"text-3xl font-bold text-white",children:e("login.title")}),i.jsx("p",{className:"mt-2 text-sm text-bambu-gray",children:e("login.subtitle")})]}),i.jsxs("form",{className:"mt-8 space-y-6",onSubmit:g,children:[i.jsxs("div",{className:"space-y-4",children:[i.jsxs("div",{children:[i.jsx("label",{htmlFor:"username",className:"block text-sm font-medium text-white mb-2",children:p?.advanced_auth_enabled?e("login.usernameOrEmail")||"Username or Email":e("login.username")}),i.jsx("input",{id:"username",type:"text",required:!0,value:s,onChange:_=>o(_.target.value),className:"block 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:p?.advanced_auth_enabled?e("login.usernameOrEmailPlaceholder")||"Enter your username or email":e("login.usernamePlaceholder"),autoComplete:"username"})]}),i.jsxs("div",{children:[i.jsx("label",{htmlFor:"password",className:"block text-sm font-medium text-white mb-2",children:e("login.password")}),i.jsx("input",{id:"password",type:"password",required:!0,value:l,onChange:_=>c(_.target.value),className:"block 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:e("login.passwordPlaceholder"),autoComplete:"current-password"})]})]}),i.jsx("div",{children:i.jsx("button",{type:"submit",disabled:x.isPending,className:"w-full flex justify-center py-3 px-4 bg-bambu-green hover:bg-bambu-green-light text-white font-medium rounded-lg shadow-lg shadow-bambu-green/20 hover:shadow-bambu-green/30 focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:ring-offset-2 focus:ring-offset-bambu-dark-secondary transition-all disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:bg-bambu-green",children:x.isPending?e("login.signingIn"):e("login.signIn")})}),p?.advanced_auth_enabled&&i.jsx("div",{className:"text-center",children:i.jsx("button",{type:"button",onClick:()=>d(!0),className:"text-sm text-bambu-gray hover:text-bambu-green transition-colors",children:e("login.forgotPassword")})})]})]}),u&&i.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:()=>d(!1),children:i.jsxs(vt,{className:"w-full max-w-md",onClick:_=>_.stopPropagation(),children:[i.jsx(In,{children:i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(fv,{className:"w-5 h-5 text-bambu-green"}),i.jsx("h2",{className:"text-lg font-semibold text-white",children:e("login.forgotPasswordTitle")})]}),i.jsx(Ce,{variant:"ghost",size:"sm",onClick:()=>{d(!1),f("")},children:i.jsx(Ft,{className:"w-5 h-5"})})]})}),i.jsx(_t,{children:p?.advanced_auth_enabled?i.jsxs("form",{onSubmit:y,className:"space-y-4",children:[i.jsx("p",{className:"text-bambu-gray text-sm",children:e("login.forgotPasswordEmailMessage")||"Enter your email address and we'll send you a new password."}),i.jsxs("div",{children:[i.jsx("label",{htmlFor:"forgot-email",className:"block text-sm font-medium text-white mb-2",children:e("login.emailAddress")||"Email Address"}),i.jsx("input",{id:"forgot-email",type:"email",required:!0,value:h,onChange:_=>f(_.target.value),className:"block 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:e("login.emailPlaceholder")||"your.email@example.com"})]}),i.jsxs("div",{className:"flex gap-2",children:[i.jsx(Ce,{type:"button",variant:"secondary",className:"flex-1",onClick:()=>{d(!1),f("")},children:e("login.cancel")||"Cancel"}),i.jsx(Ce,{type:"submit",className:"flex-1",disabled:v.isPending,children:v.isPending?e("login.sending")||"Sending...":e("login.sendResetEmail")||"Send Reset Email"})]})]}):i.jsxs("div",{className:"space-y-4",children:[i.jsx("p",{className:"text-bambu-gray",children:e("login.forgotPasswordMessage")}),i.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4 space-y-2",children:[i.jsx("p",{className:"text-sm text-white font-medium",children:e("login.howToReset")}),i.jsxs("ol",{className:"text-sm text-bambu-gray space-y-1 list-decimal list-inside",children:[i.jsx("li",{children:e("login.resetStep1")}),i.jsx("li",{children:e("login.resetStep2")}),i.jsx("li",{children:e("login.resetStep3")}),i.jsx("li",{children:e("login.resetStep4")})]})]}),i.jsx(Ce,{variant:"secondary",className:"w-full",onClick:()=>d(!1),children:e("login.gotIt")})]})})]})})]})}function QJe(){const t=rc(),{t:e}=Ut(),{showToast:n}=cn(),{mode:r}=Jf(),{refreshAuth:a}=Or(),[s,o]=w.useState(!1),[l,c]=w.useState(""),[u,d]=w.useState(""),[h,f]=w.useState(""),p=ot({mutationFn:()=>ne.setupAuth({auth_enabled:s,admin_username:s?l:void 0,admin_password:s?u:void 0}),onSuccess:async v=>{await a(),v.auth_enabled?v.admin_created?(n(e("setup.toast.authEnabledAdminCreated")),t("/login")):(n(e("setup.toast.authEnabledExistingAdmins")),t("/login")):(n(e("setup.toast.setupCompleted")),t("/"))},onError:v=>{n(v.message,"error")}}),x=v=>{if(v.preventDefault(),s&&(l||u)){if(!l||!u){n(e("setup.toast.enterBothCredentials"),"error");return}if(u!==h){n(e("setup.toast.passwordsDoNotMatch"),"error");return}if(u.length<6){n(e("setup.toast.passwordTooShort"),"error");return}}p.mutate()};return i.jsx("div",{className:"min-h-screen flex items-center justify-center bg-bambu-dark p-4",children:i.jsxs("div",{className:"max-w-md w-full space-y-8 p-8 bg-gradient-to-br from-bambu-card to-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary shadow-lg",children:[i.jsxs("div",{className:"text-center",children:[i.jsx("div",{className:"flex items-center justify-center mb-6",children:i.jsx("img",{src:r==="dark"?"/img/bambuddy_logo_dark_transparent.png":"/img/bambuddy_logo_light.png",alt:"Bambuddy",className:"h-16"})}),i.jsx("h2",{className:"text-3xl font-bold text-white",children:e("setup.title")}),i.jsx("p",{className:"mt-2 text-sm text-bambu-gray",children:e("setup.subtitle")})]}),i.jsxs("form",{className:"mt-8 space-y-6",onSubmit:x,children:[i.jsxs("div",{className:"space-y-4",children:[i.jsxs("div",{className:"flex items-center p-4 bg-bambu-dark-secondary/50 rounded-lg border border-bambu-dark-tertiary",children:[i.jsx("input",{id:"auth-enabled",type:"checkbox",checked:s,onChange:v=>o(v.target.checked),className:"h-4 w-4 text-bambu-green focus:ring-bambu-green border-bambu-dark-tertiary rounded bg-bambu-dark-secondary"}),i.jsx("label",{htmlFor:"auth-enabled",className:"ml-3 block text-sm font-medium text-white",children:e("setup.enableAuth")})]}),s&&i.jsxs("div",{className:"space-y-4 mt-4",children:[i.jsx("div",{className:"p-3 bg-bambu-dark-secondary/50 border border-bambu-dark-tertiary rounded-lg",children:i.jsxs("div",{className:"flex items-start gap-2",children:[i.jsx(Zs,{className:"w-4 h-4 text-bambu-green mt-0.5 flex-shrink-0"}),i.jsxs("div",{className:"text-sm text-bambu-gray",children:[i.jsx("p",{className:"text-white font-medium mb-1",children:e("setup.adminAccount")}),i.jsx("p",{children:e("setup.adminAccountDesc")})]})]})}),i.jsxs("div",{children:[i.jsxs("label",{htmlFor:"admin-username",className:"block text-sm font-medium text-white mb-2",children:[e("setup.adminUsername")," ",i.jsx("span",{className:"text-bambu-gray text-xs",children:e("setup.optionalIfAdminExists")})]}),i.jsx("input",{id:"admin-username",type:"text",value:l,onChange:v=>c(v.target.value),className:"block 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:e("setup.adminUsernamePlaceholder"),autoComplete:"username"})]}),i.jsxs("div",{children:[i.jsxs("label",{htmlFor:"admin-password",className:"block text-sm font-medium text-white mb-2",children:[e("setup.adminPassword")," ",i.jsx("span",{className:"text-bambu-gray text-xs",children:e("setup.optionalIfAdminExists")})]}),i.jsx("input",{id:"admin-password",type:"password",value:u,onChange:v=>d(v.target.value),className:"block 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:e("setup.adminPasswordPlaceholder"),minLength:6,autoComplete:"new-password"})]}),u&&i.jsxs("div",{children:[i.jsx("label",{htmlFor:"confirm-password",className:"block text-sm font-medium text-white mb-2",children:e("setup.confirmPassword")}),i.jsx("input",{id:"confirm-password",type:"password",value:h,onChange:v=>f(v.target.value),className:"block 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:e("setup.confirmPasswordPlaceholder"),minLength:6,autoComplete:"new-password"})]})]})]}),i.jsx("div",{children:i.jsx("button",{type:"submit",disabled:p.isPending,className:"w-full flex justify-center py-3 px-4 bg-bambu-green hover:bg-bambu-green-light text-white font-medium rounded-lg shadow-lg shadow-bambu-green/20 hover:shadow-bambu-green/30 focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:ring-offset-2 focus:ring-offset-bambu-dark-secondary transition-all disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:bg-bambu-green",children:p.isPending?e("setup.settingUp"):e("setup.completeSetup")})})]})]})})}function ZJe(){const t=w.useRef(null),e=w.useRef(null),n=tn(),[r,a]=w.useState(!1),s=w.useRef(new Set),o=w.useRef(null),l=w.useRef(new Map),c=w.useRef(null),u=w.useRef([]),d=w.useRef(!1),h=w.useRef(()=>{}),f=w.useCallback(()=>{if(d.current||u.current.length===0)return;d.current=!0;const _=()=>{const N=u.current.shift();N?requestAnimationFrame(()=>{h.current(N),u.current.length>0?setTimeout(_,16):d.current=!1}):d.current=!1};_()},[]),p=w.useCallback(()=>{if(t.current?.readyState===WebSocket.OPEN)return;const N=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/api/v1/ws`,k=new WebSocket(N);let A=null;k.onopen=()=>{console.log("[WebSocket] Connected"),a(!0),A=window.setInterval(()=>{k.readyState===WebSocket.OPEN&&k.send(JSON.stringify({type:"ping"}))},3e4)},k.onmessage=M=>{try{const C=JSON.parse(M.data);C.type==="printer_status"&&C.printer_id!==void 0&&C.data?h.current(C):(u.current.push(C),f())}catch{}},k.onclose=M=>{console.log("[WebSocket] Closed",M.code,M.reason),A&&(clearInterval(A),A=null),a(!1),t.current=null,e.current=window.setTimeout(()=>{p()},3e3)},k.onerror=M=>{console.error("[WebSocket] Error",M),k.close()},t.current=k},[f]),x=w.useCallback((_,N)=>{const k=l.current.get(_)||{};l.current.set(_,{...k,...N}),c.current||(c.current=window.setTimeout(()=>{const A=new Map(l.current);l.current.clear(),c.current=null,requestAnimationFrame(()=>{A.forEach((M,C)=>{n.setQueryData(["printerStatus",C],j=>{const P={...j,...M};return P.wifi_signal==null&&j?.wifi_signal!=null&&(P.wifi_signal=j.wifi_signal),P})})})},100))},[n]),v=w.useCallback(_=>{s.current.add(_),o.current&&clearTimeout(o.current),o.current=window.setTimeout(()=>{const N=Array.from(s.current);s.current.clear(),o.current=null;let k=0;N.forEach(A=>{setTimeout(()=>{requestAnimationFrame(()=>{n.invalidateQueries({queryKey:[A]})})},k),k+=500})},3e3)},[n]),g=w.useCallback(_=>{switch(_.type){case"printer_status":_.printer_id!==void 0&&_.data&&x(_.printer_id,_.data);break;case"print_start":_.printer_id!==void 0&&n.invalidateQueries({queryKey:["printerStatus",_.printer_id]});break;case"print_complete":v("archives"),v("archiveStats");break;case"archive_created":v("archives"),v("archiveStats");break;case"archive_updated":v("archives");break;case"pong":break;case"plate_not_empty":window.dispatchEvent(new CustomEvent("plate-not-empty",{detail:{printer_id:_.printer_id,printer_name:_.printer_name,message:_.message}}));break;case"spool_auto_assigned":v("inventory-spools"),v("spool-assignments");break;case"spool_usage_logged":v("inventory-spools");break;case"unknown_tag":window.dispatchEvent(new CustomEvent("unknown-tag",{detail:{printer_id:_.printer_id,ams_id:_.ams_id,tray_id:_.tray_id,tag_uid:_.tag_uid,tray_uuid:_.tray_uuid}}));break;case"background_dispatch":window.dispatchEvent(new CustomEvent("background-dispatch",{detail:_.data||{}}));break}},[n,v,x]);w.useEffect(()=>{h.current=g},[g]),w.useEffect(()=>(p(),()=>{e.current&&clearTimeout(e.current),o.current&&clearTimeout(o.current),c.current&&clearTimeout(c.current),t.current&&t.current.close()}),[p]);const y=w.useCallback(_=>{t.current?.readyState===WebSocket.OPEN&&t.current.send(JSON.stringify(_))},[]);return{isConnected:r,sendMessage:y}}const JJe=new ode({defaultOptions:{queries:{staleTime:1e3*60,retry:1}}});function eet({children:t}){return ZJe(),i.jsx(i.Fragment,{children:t})}function tet({children:t}){const{authEnabled:e,loading:n,user:r}=Or();return n?i.jsx("div",{className:"min-h-screen flex items-center justify-center",children:"Loading..."}):e&&!r?i.jsx(ab,{to:"/login",replace:!0}):i.jsx(i.Fragment,{children:t})}function Fj({children:t}){const{authEnabled:e,loading:n,user:r,isAdmin:a}=Or();return n?i.jsx("div",{className:"min-h-screen flex items-center justify-center",children:"Loading..."}):e?r?a?i.jsx(i.Fragment,{children:t}):i.jsx(ab,{to:"/",replace:!0}):i.jsx(ab,{to:"/login",replace:!0}):i.jsx(i.Fragment,{children:t})}function net({children:t}){const{authEnabled:e,loading:n}=Or();return n?i.jsx("div",{className:"min-h-screen flex items-center justify-center",children:"Loading..."}):e?i.jsx(ab,{to:"/login",replace:!0}):i.jsx(i.Fragment,{children:t})}function ret(){return i.jsx(Zpe,{children:i.jsx(sge,{children:i.jsx(lde,{client:JJe,children:i.jsx(age,{children:i.jsx(Aue,{children:i.jsxs(nue,{children:[i.jsx(fa,{path:"/setup",element:i.jsx(net,{children:i.jsx(QJe,{})})}),i.jsx(fa,{path:"/login",element:i.jsx(YJe,{})}),i.jsx(fa,{path:"/camera/:printerId",element:i.jsx(cJe,{})}),i.jsx(fa,{path:"/overlay/:printerId",element:i.jsx(mJe,{})}),i.jsxs(fa,{element:i.jsx(tet,{children:i.jsx(eet,{children:i.jsx(uge,{})})}),children:[i.jsx(fa,{index:!0,element:i.jsx(c$e,{})}),i.jsx(fa,{path:"archives",element:i.jsx(XXe,{})}),i.jsx(fa,{path:"queue",element:i.jsx(DQe,{})}),i.jsx(fa,{path:"stats",element:i.jsx(WQe,{})}),i.jsx(fa,{path:"profiles",element:i.jsx(IZe,{})}),i.jsx(fa,{path:"maintenance",element:i.jsx($Ze,{})}),i.jsx(fa,{path:"projects",element:i.jsx(qZe,{})}),i.jsx(fa,{path:"projects/:id",element:i.jsx(ZZe,{})}),i.jsx(fa,{path:"inventory",element:i.jsx(VJe,{})}),i.jsx(fa,{path:"files",element:i.jsx(iJe,{})}),i.jsx(fa,{path:"settings",element:i.jsx(Fj,{children:i.jsx(NZe,{})})}),i.jsx(fa,{path:"groups/new",element:i.jsx(Fj,{children:i.jsx(tK,{})})}),i.jsx(fa,{path:"groups/:id/edit",element:i.jsx(Fj,{children:i.jsx(tK,{})})}),i.jsx(fa,{path:"users",element:i.jsx(ab,{to:"/settings?tab=users",replace:!0})}),i.jsx(fa,{path:"groups",element:i.jsx(ab,{to:"/settings?tab=users",replace:!0})}),i.jsx(fa,{path:"system",element:i.jsx(XJe,{})}),i.jsx(fa,{path:"external/:id",element:i.jsx(fJe,{})})]})]})})})})})})}Yoe.createRoot(document.getElementById("root")).render(i.jsx(w.StrictMode,{children:i.jsx(ret,{})})); diff --git a/static/index.html b/static/index.html index c904e0d47..e48b825f1 100644 --- a/static/index.html +++ b/static/index.html @@ -23,7 +23,7 @@ - +