diff --git a/CHANGELOG.md b/CHANGELOG.md
index 0c9306f34..bc9380ccd 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,7 @@ All notable changes to Bambuddy will be documented in this file.
## [0.2.5b1] - Unreleased
### Fixed
+- **Library G-code preview returned raw ZIP bytes as `text/plain` for sidecar-sliced rows (#1709, root cause + fix from @yanglei1980)** — `slice_and_persist` writes its output as a `.gcode.3mf` (a ZIP container with embedded G-code) but persisted the LibraryFile row with `file_type="gcode"`. The G-code preview endpoint at `library.py::get_gcode` short-circuits on `file_type == "gcode"` and streams the on-disk bytes with `media_type="text/plain"`, so every preview of a sidecar-sliced row handed the embedded viewer the raw ZIP body (`PK\x03\x04…`) instead of toolpath text — the viewer rendered nothing. External-folder scans (#1600) already typed `.gcode.3mf` rows correctly and hit the unzip branch, so the bug was specific to the sidecar slice path. Plain `.gcode` uploads were unaffected (their on-disk bytes really are text). **Fix:** (1) forward — `slice_and_persist` now persists `file_type="gcode.3mf"`, matching what `_classify_file_type` returns for the `.gcode.3mf` extension and what external-scan rows already use; (2) back-compat — `get_gcode` also routes to the unzip branch when the filename ends with `.gcode.3mf`, so rows already written under the bug self-heal on first preview without a DB migration. **UI gates:** three frontend call sites that gated badge colour or the preview-eye icon on `file_type == "gcode"` were extended to also accept `"gcode.3mf"` — `FileManagerPage.tsx` badge + viewer-affordance gate, `ProjectDetailPage.tsx` badge — so the new typing doesn't regress visuals. The print / queue / slice action buttons use filename-based helpers (`isSlicedFilename`, `isSliceableFilename`) that already accept `.gcode.3mf`, so they need no change. **Tests:** new `test_library_get_gcode_recovers_legacy_gcode_type_for_3mf` regression case in `test_library_api.py` constructs a row with `file_type="gcode"` + `.gcode.3mf` filename pointing at a real ZIP, asserts the response is `text/plain`, contains `G28`, and does NOT start with `PK` — pins the legacy-row recovery path. Existing `test_library_get_gcode_endpoint_accepts_compound_file_type` continues to cover the forward path. Full backend suite 5920/5920 green; ruff clean; frontend ESLint + `npm run build` clean; FileManagerPage / ProjectDetailPage / FileManagerExternalFolder vitests 69/69 green; i18n parity unchanged (no new keys). PR #1709 closed for CONTRIBUTING.md non-compliance (branched from main, no issue, template incomplete); root cause + fix shape preserved here on `dev`.
- **Cloud + Orca Cloud preset resolver: pin `type` and `from` to CLI-accepted values (#1712 follow-up, reported by maziggy on the Mecha Mewtwo slice)** — Removing bundle mode (entry above) routed every slot through the cross-tier preset resolver. Cloud-tier presets surfaced two latent shape mismatches that bundle dispatch had been masking by materialising preset JSONs from `.bbscfg`-on-disk. (1) **`type` field**: Bambu Cloud labels presets with `type: "printer"` / `"print"` / `"filament"`, but the BambuStudio CLI's `--load-settings` parser only accepts `"machine"` / `"process"` / `"filament"`. The user's first failing slice produced `operator(): unknown config type print of file preset.json in load-settings` with exit code -5; the sidecar surfaces this as a generic "The input preset file is invalid and can not be parsed." (2) **`from` field**: Bambu Cloud's filament detail endpoint routinely ships presets with empty `from` (or no `from` at all). The CLI's compatibility check rejects either with `operator(): file ... 's from unsupported` (the double space in stderr = empty value). Same -5 exit, same generic "input preset invalid" surface. The sidecar's `normalizeFromField` already maps `"User"` / `"System"` → `"system"`, but it doesn't touch empty / missing values. **Fix:** `_resolve_cloud` and `_resolve_orca_cloud` now force `type = _SLOT_TO_PROFILE_TYPE[slot]` and `from = "system"` on the payload before `json.dumps`, mirroring what `_resolve_standard` already does for the standard-tier stub. Both fields are unconditionally rewritten — idempotent on already-correct payloads, and pinning to "system" is consistent with how Bambuddy presents these post-flatten presets to the CLI (no parent walk needed, the cloud detail comes back fully expanded). **Tests:** new `test_cloud_rewrites_type_field_for_cli` (7 parametric cases covering all six type-name variants Bambu Cloud emits plus the missing-type case), `test_cloud_pins_from_field_to_system` (4 cases: empty, already-system, GUI User, GUI System), and `test_cloud_synthesises_from_field_when_missing` (the actual Mecha Mewtwo failure shape) pin the resolver-level contract. Existing happy-path assertions for `_resolve_cloud` / `_resolve_orca_cloud` updated to include the new fields. 28/28 preset-resolver tests green, full backend suite 5919/5919 green, ruff clean. **What this can NOT recover:** if Bambu Cloud later starts emitting a `from` value other than empty / "User" / "System" that genuinely means something (e.g. "project"), Bambuddy will silently flatten it to "system" too. We accept that trade-off because the alternative is leaving "input preset invalid" failures on every cloud slice, and "system" matches how the sidecar's own resolver normalises the post-flatten state.
### Removed
diff --git a/backend/app/api/routes/library.py b/backend/app/api/routes/library.py
index 3fe2c6379..2d3ed5c75 100644
--- a/backend/app/api/routes/library.py
+++ b/backend/app/api/routes/library.py
@@ -3576,11 +3576,13 @@ async def slice_and_persist(
folder_id=folder_id,
filename=out_filename,
file_path=to_relative_path(out_path),
- # Sliced output is a `.gcode.3mf` zip with embedded G-code, but the
- # user-facing meaning is "ready-to-print G-code" — using "gcode"
- # gives it the same badge as plain .gcode files and distinguishes
- # it from un-sliced `.3mf` source models.
- file_type="gcode",
+ # The on-disk payload is a ZIP container — the file_type must
+ # record that so the preview endpoint opens it as a 3MF instead
+ # of returning the ZIP bytes as text/plain (#1709 / yanglei1980).
+ # Earlier code mis-typed sliced rows as "gcode" to share the
+ # plain-G-code badge; that broke the embedded viewer. UI badges
+ # and gates for "gcode.3mf" are explicit at the call sites.
+ file_type="gcode.3mf",
file_size=len(result.content),
file_hash=hashlib.sha256(result.content).hexdigest(),
thumbnail_path=thumbnail_relative,
@@ -4332,15 +4334,14 @@ async def get_gcode(
if not abs_path or not abs_path.exists():
raise HTTPException(status_code=404, detail="File not found on disk")
- if file.file_type == "gcode":
- return FastAPIFileResponse(str(abs_path), media_type="text/plain")
- elif file.file_type in ("3mf", "gcode.3mf"):
- # Extract gcode from 3mf zip container. `.gcode.3mf` sliced outputs
- # carry the same `Metadata/plate_*.gcode` entries as a `.3mf`, so
- # the unzip path is identical — just had to expand the gate.
+ # Legacy sliced rows from before #1709 stored a `.gcode.3mf` ZIP body
+ # under file_type="gcode" — the on-disk filename is the truth in that
+ # case, so detect by suffix before checking the type column.
+ is_gcode_3mf = file.file_type in ("3mf", "gcode.3mf") or file.filename.lower().endswith(".gcode.3mf")
+
+ if is_gcode_3mf:
try:
with zipfile.ZipFile(str(abs_path), "r") as zf:
- # Find gcode file
gcode_files = [n for n in zf.namelist() if n.endswith(".gcode")]
if not gcode_files:
raise HTTPException(status_code=404, detail="No gcode found in 3MF file")
@@ -4350,6 +4351,8 @@ async def get_gcode(
return Response(content=gcode_content, media_type="text/plain")
except zipfile.BadZipFile:
raise HTTPException(status_code=400, detail="Invalid 3MF file")
+ elif file.file_type == "gcode":
+ return FastAPIFileResponse(str(abs_path), media_type="text/plain")
else:
raise HTTPException(status_code=400, detail="Unsupported file type")
diff --git a/backend/tests/integration/test_library_api.py b/backend/tests/integration/test_library_api.py
index 1864cbde0..bd3d36b7c 100644
--- a/backend/tests/integration/test_library_api.py
+++ b/backend/tests/integration/test_library_api.py
@@ -1274,6 +1274,40 @@ class TestPrintFileUploadValidation:
assert response.status_code == 200
assert b"G28" in response.content
+ @pytest.mark.asyncio
+ @pytest.mark.integration
+ async def test_library_get_gcode_recovers_legacy_gcode_type_for_3mf(self, async_client: AsyncClient, db_session):
+ """#1709 regression guard. Before the fix, ``slice_and_persist``
+ wrote a `.gcode.3mf` ZIP container to disk but stored the row with
+ ``file_type='gcode'`` — the preview endpoint then streamed the
+ ZIP body as ``text/plain`` and the embedded G-code viewer saw
+ ``PK\\x03\\x04...`` instead of the toolpath. New sliced rows now
+ store ``file_type='gcode.3mf'``; rows already written under the
+ bug self-heal because the endpoint also detects the ZIP via the
+ ``.gcode.3mf`` filename suffix when the column is still legacy."""
+ from backend.app.models.library import LibraryFile
+
+ with tempfile.NamedTemporaryFile(suffix=".gcode.3mf", delete=False) as tmp:
+ tmp.write(self._valid_3mf_bytes(name="Metadata/plate_1.gcode"))
+ tmp_path = tmp.name
+
+ lib_file = LibraryFile(
+ filename="legacy-sliced.gcode.3mf",
+ file_path=tmp_path,
+ file_type="gcode",
+ file_size=Path(tmp_path).stat().st_size,
+ )
+ db_session.add(lib_file)
+ await db_session.commit()
+ await db_session.refresh(lib_file)
+
+ response = await async_client.get(f"/api/v1/library/files/{lib_file.id}/gcode")
+ assert response.status_code == 200
+ assert response.headers["content-type"].startswith("text/plain")
+ assert b"G28" in response.content
+ # The whole point of #1709: must NOT be ZIP bytes shoved at the viewer.
+ assert not response.content.startswith(b"PK")
+
@pytest.mark.asyncio
@pytest.mark.integration
async def test_library_still_accepts_non_print_extensions(self, async_client: AsyncClient, db_session):
diff --git a/frontend/src/pages/FileManagerPage.tsx b/frontend/src/pages/FileManagerPage.tsx
index b3759986b..f1128d87f 100644
--- a/frontend/src/pages/FileManagerPage.tsx
+++ b/frontend/src/pages/FileManagerPage.tsx
@@ -2164,7 +2164,7 @@ export function FileManagerPage() {
@@ -2223,7 +2223,7 @@ export function FileManagerPage() {
)}
- {(file.file_type === '3mf' || file.file_type === 'gcode' || file.file_type === 'stl') && (
+ {(file.file_type === '3mf' || file.file_type === 'gcode' || file.file_type === 'gcode.3mf' || file.file_type === 'stl') && (
{
if (!hasPermission('library:read')) return;
diff --git a/frontend/src/pages/ProjectDetailPage.tsx b/frontend/src/pages/ProjectDetailPage.tsx
index 7663eb559..f96ec6ec5 100644
--- a/frontend/src/pages/ProjectDetailPage.tsx
+++ b/frontend/src/pages/ProjectDetailPage.tsx
@@ -949,7 +949,7 @@ export function ProjectDetailPage() {
{file.file_type.toUpperCase()}
diff --git a/static/assets/index-VyNhPxaj.js b/static/assets/index-C-AWhT3K.js
similarity index 97%
rename from static/assets/index-VyNhPxaj.js
rename to static/assets/index-C-AWhT3K.js
index 948f1becf..46d7ba52a 100644
--- a/static/assets/index-VyNhPxaj.js
+++ b/static/assets/index-C-AWhT3K.js
@@ -8728,7 +8728,7 @@ Accuracy: ${t.time_accuracy.toFixed(0)}%`:t.actual_time_seconds?`Actual: ${ds(t.
`+a+"]";if(typeof t=="object"){const n=Object.entries(t);return n.length===0?"{}":`{
`+n.map(([s,o])=>a+" "+JSON.stringify(s)+": "+fI(o,e+1)).join(`,
`)+`
-`+a+"}"}return String(t)}function ust({setting:t,onClose:e,onDeleted:a,onDuplicate:n,onEdit:i,hasPermission:s,t:o}){const{showToast:l}=da(),c=ia(),[d,u]=y.useState(!1),{data:m,isLoading:p}=$e({queryKey:["cloudSettingDetail",t.setting_id],queryFn:()=>ne.getCloudSettingDetail(t.setting_id)}),f=rt({mutationFn:()=>ne.deleteCloudSetting(t.setting_id),onSuccess:()=>{l(o("profiles.presets.toast.deleted")),c.invalidateQueries({queryKey:["cloudSettings"]}),a()},onError:b=>l(b.message,"error")}),g=MS(t.setting_id),v=T5(t.name,m?.setting?.inherits);return r.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:r.jsx(Tt,{className:"w-full max-w-3xl max-h-[90vh] flex flex-col overflow-hidden",children:r.jsxs(jt,{className:"p-0 flex flex-col min-h-0 flex-1",children:[r.jsxs("div",{className:"flex-shrink-0 flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("h2",{className:"text-xl font-semibold text-white truncate",children:t.name}),g&&r.jsx("span",{className:"px-2 py-0.5 text-xs font-medium bg-bambu-green/20 text-bambu-green rounded-full",children:o("profiles.presets.editable")})]}),r.jsxs("div",{className:"flex items-center gap-2 mt-1 text-sm text-bambu-gray",children:[r.jsx("span",{className:"capitalize",children:o(`profiles.presets.types.${t.type}`)}),v.printer&&r.jsxs(r.Fragment,{children:[r.jsx("span",{children:"•"}),r.jsx("span",{children:v.printer})]})]})]}),r.jsx("button",{onClick:e,className:"p-2 text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary rounded-lg transition-colors",children:r.jsx(Ht,{className:"w-5 h-5"})})]}),r.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto p-4",children:p?r.jsx("div",{className:"flex items-center justify-center py-16",children:r.jsx(lt,{className:"w-8 h-8 text-bambu-green animate-spin"})}):m?r.jsx("pre",{className:"text-xs text-bambu-gray font-mono whitespace-pre-wrap break-all bg-bambu-dark p-4 rounded-lg border border-bambu-dark-tertiary overflow-x-auto max-w-full",children:fI(m)}):r.jsx("div",{className:"text-center py-16 text-bambu-gray",children:o("profiles.presets.failedToLoadDetails")})}),d?r.jsxs("div",{className:"flex-shrink-0 p-4 border-t border-bambu-dark-tertiary bg-red-500/5",children:[r.jsxs("div",{className:"flex items-center gap-2 mb-3 text-red-400",children:[r.jsx(xa,{className:"w-5 h-5"}),r.jsx("span",{className:"font-medium",children:o("profiles.presets.deleteConfirm")})]}),r.jsx("p",{className:"text-sm text-bambu-gray mb-4",children:o("profiles.presets.deleteWarning",{name:t.name})}),r.jsxs("div",{className:"flex gap-2",children:[r.jsx(Le,{variant:"secondary",onClick:()=>u(!1),disabled:f.isPending,className:"flex-1",children:o("common.cancel")}),r.jsxs(Le,{variant:"danger",onClick:()=>f.mutate(),disabled:f.isPending,className:"flex-1",children:[f.isPending?r.jsx(lt,{className:"w-4 h-4 animate-spin"}):r.jsx(na,{className:"w-4 h-4"}),o("common.delete")]})]})]}):r.jsx("div",{className:"flex-shrink-0 p-4 border-t border-bambu-dark-tertiary",children:r.jsxs("div",{className:"flex gap-2",children:[r.jsx(Le,{variant:"secondary",onClick:e,className:"flex-1",children:o("common.close")}),r.jsxs(Le,{variant:"secondary",onClick:n,disabled:!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.presets.noDuplicatePermission"),children:[r.jsx(li,{className:"w-4 h-4"}),o("profiles.presets.duplicate")]}),g&&r.jsxs(r.Fragment,{children:[r.jsxs(Le,{variant:"secondary",onClick:i,disabled:p||!m||!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.presets.noEditPermission"),children:[r.jsx(ci,{className:"w-4 h-4"}),o("common.edit")]}),r.jsx(Le,{variant:"danger",onClick:()=>u(!0),disabled:!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.presets.noDeletePermission"),children:r.jsx(na,{className:"w-4 h-4"})})]})]})})]})})})}function Pde(){try{const t=localStorage.getItem("bambusy_preset_templates");return t?JSON.parse(t):[]}catch{return[]}}function Nde(t){localStorage.setItem("bambusy_preset_templates",JSON.stringify(t))}function mst({onClose:t,onApply:e,t:a}){const{showToast:n}=da(),[i,s]=y.useState(Pde),[o,l]=y.useState("all"),[c,d]=y.useState(null),[u,m]=y.useState(""),[p,f]=y.useState(""),[g,v]=y.useState("{}"),[b,x]=y.useState(null),[S,k]=y.useState(null),P=o==="all"?i:i.filter(O=>O.type===o),N=O=>{s(O),Nde(O)},T=O=>{const z=i.filter(X=>X.id!==O);N(z),k(null),n(a("profiles.templates.toast.deleted"))},j=O=>{d(O.id),m(O.name),f(O.description),v(JSON.stringify(O.settings,null,2)),x(null)},D=()=>{if(!(!c||!u.trim()))try{const O=JSON.parse(g),z=i.map(X=>X.id===c?{...X,name:u.trim(),description:p.trim(),settings:O}:X);N(z),d(null),n(a("profiles.templates.toast.updated"))}catch(O){x(O.message)}},C=()=>{d(null),m(""),f(""),v("{}"),x(null)},E=O=>{const z=i.map(X=>X.id===O?{...X,showInModal:!X.showInModal}:X);N(z)},R={filament:{label:a("profiles.presets.types.filament"),icon:RS,color:"text-amber-400"},print:{label:a("profiles.presets.types.process"),icon:xd,color:"text-blue-400"},printer:{label:a("profiles.presets.types.printer"),icon:xr,color:"text-purple-400"}},I=S?i.find(O=>O.id===S):null;return y.useEffect(()=>{const O=z=>{z.key==="Escape"&&(S?k(null):c?C():t())};return window.addEventListener("keydown",O),()=>window.removeEventListener("keydown",O)},[S,c,t]),r.jsxs("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:[I&&r.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-60",children:r.jsx(Tt,{className:"w-full max-w-md",children:r.jsxs(jt,{className:"p-6",children:[r.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[r.jsx("div",{className:"p-2 bg-red-500/20 rounded-lg",children:r.jsx(xa,{className:"w-6 h-6 text-red-400"})}),r.jsxs("div",{children:[r.jsx("h3",{className:"text-lg font-semibold text-white",children:a("profiles.templates.deleteTitle")}),r.jsx("p",{className:"text-sm text-bambu-gray",children:a("profiles.templates.deleteWarning")})]})]}),r.jsx("p",{className:"text-white mb-6",children:a("profiles.templates.deleteConfirm",{name:I.name})}),r.jsxs("div",{className:"flex gap-2",children:[r.jsx(Le,{variant:"secondary",onClick:()=>k(null),className:"flex-1",children:a("common.cancel")}),r.jsxs(Le,{onClick:()=>T(S),className:"flex-1 bg-red-500 hover:bg-red-600",children:[r.jsx(na,{className:"w-4 h-4"}),a("common.delete")]})]})]})})}),r.jsx(Tt,{className:"w-full max-w-2xl max-h-[80vh] flex flex-col",children:r.jsxs(jt,{className:"p-0 flex flex-col h-full",children:[r.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[r.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[r.jsx(Ug,{className:"w-5 h-5 text-amber-400"}),a("profiles.templates.title")]}),r.jsx("button",{onClick:t,className:"text-bambu-gray hover:text-white",children:r.jsx(Ht,{className:"w-5 h-5"})})]}),r.jsxs("div",{className:"flex items-center gap-2 p-4 border-b border-bambu-dark-tertiary",children:[r.jsx("span",{className:"text-sm text-bambu-gray",children:a("profiles.templates.typeFilter")}),["all","filament","print","printer"].map(O=>r.jsx("button",{onClick:()=>l(O),className:`px-3 py-1 text-sm rounded-lg transition-colors ${o===O?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:O==="all"?a("common.all"):R[O].label},O))]}),r.jsx("div",{className:"flex-1 overflow-y-auto p-4",children:P.length===0?r.jsxs("div",{className:"text-center py-12 text-bambu-gray",children:[r.jsx(Ug,{className:"w-12 h-12 mx-auto mb-4 opacity-30"}),r.jsx("p",{children:a("profiles.templates.noTemplates")}),r.jsx("p",{className:"text-sm mt-1",children:a("profiles.templates.createFirst")})]}):r.jsx("div",{className:"space-y-2",children:P.map(O=>{const z=R[O.type],X=z.icon;return c===O.id?r.jsxs("div",{className:"p-4 bg-bambu-dark rounded-lg border border-bambu-green",children:[r.jsxs("div",{className:"grid grid-cols-2 gap-3 mb-3",children:[r.jsx("input",{type:"text",value:u,onChange:ae=>m(ae.target.value),placeholder:a("profiles.templates.namePlaceholder"),className:"px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none",autoFocus:!0}),r.jsx("input",{type:"text",value:p,onChange:ae=>f(ae.target.value),placeholder:a("profiles.templates.descriptionPlaceholder"),className:"px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none"})]}),r.jsxs("div",{className:"mb-3",children:[r.jsx("label",{className:"text-xs text-bambu-gray mb-1 block",children:a("profiles.templates.settingsJson")}),r.jsx("textarea",{value:g,onChange:ae=>{v(ae.target.value),x(null)},rows:6,className:`w-full px-3 py-2 bg-bambu-dark-secondary border rounded text-white text-sm font-mono focus:outline-none ${b?"border-red-500":"border-bambu-dark-tertiary focus:border-bambu-green"}`}),b&&r.jsx("p",{className:"text-xs text-red-400 mt-1",children:b})]}),r.jsxs("div",{className:"flex gap-2",children:[r.jsxs(Le,{size:"sm",onClick:D,disabled:!u.trim(),children:[r.jsx(ms,{className:"w-4 h-4"}),"Save"]}),r.jsx(Le,{size:"sm",variant:"secondary",onClick:C,children:"Cancel"})]})]},O.id):r.jsxs("div",{className:"flex items-center gap-3 p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary hover:border-bambu-gray-dark transition-colors",children:[r.jsx(X,{className:`w-5 h-5 ${z.color} flex-shrink-0`}),r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsx("p",{className:"text-sm font-medium text-white",children:O.name}),r.jsx("p",{className:"text-xs text-bambu-gray truncate",children:O.description})]}),r.jsx("span",{className:"text-xs text-bambu-gray-dark px-2 py-1 bg-bambu-dark-secondary rounded",children:a("profiles.templates.fieldsCount",{count:Object.keys(O.settings).length})}),r.jsx("button",{onClick:()=>E(O.id),className:`p-1 transition-colors ${O.showInModal?"text-bambu-green hover:text-bambu-green/70":"text-bambu-gray hover:text-white"}`,title:O.showInModal?a("profiles.templates.shownInModals"):a("profiles.templates.hiddenInModals"),children:O.showInModal?r.jsx(tl,{className:"w-4 h-4"}):r.jsx(Zh,{className:"w-4 h-4"})}),r.jsx("button",{onClick:()=>e(O),className:"px-3 py-1 text-xs bg-bambu-green/20 text-bambu-green rounded hover:bg-bambu-green/30 transition-colors",children:a("profiles.templates.apply")}),r.jsx("button",{onClick:()=>j(O),className:"p-1 text-bambu-gray hover:text-white",title:a("common.edit"),children:r.jsx(ci,{className:"w-4 h-4"})}),r.jsx("button",{onClick:()=>k(O.id),className:"p-1 text-bambu-gray hover:text-red-400",title:a("common.delete"),children:r.jsx(na,{className:"w-4 h-4"})})]},O.id)})})})]})})]})}function Tde({onClose:t,leftPreset:e,rightPreset:a,leftLabel:n,rightLabel:i,t:s}){const[o,l]=y.useState("changes"),[c,d]=y.useState(""),u=y.useMemo(()=>{const g=new Set([...Object.keys(e),...Object.keys(a)]),v=[];for(const b of g){if(b==="inherits"||b==="version")continue;const x=e[b],S=a[b],k=b in e,P=b in a;let N;!k&&P?N="added":k&&!P?N="removed":JSON.stringify(x)!==JSON.stringify(S)?N="changed":N="same",v.push({key:b,left:x,right:S,status:N})}return v.sort((b,x)=>{const S={changed:0,added:1,removed:2,same:3};return S[b.status]!==S[x.status]?S[b.status]-S[x.status]:b.key.localeCompare(x.key)})},[e,a]),m=y.useMemo(()=>{let g=[...u];if(o==="changes"&&(g=g.filter(v=>v.status!=="same")),c){const v=c.toLowerCase();g=g.filter(b=>b.key.toLowerCase().includes(v)||String(b.left).toLowerCase().includes(v)||String(b.right).toLowerCase().includes(v))}return g},[u,o,c]),p=y.useMemo(()=>({added:u.filter(g=>g.status==="added").length,removed:u.filter(g=>g.status==="removed").length,changed:u.filter(g=>g.status==="changed").length,same:u.filter(g=>g.status==="same").length}),[u]),f=g=>{if(g===void 0)return"—";if(g===null)return"null";if(Array.isArray(g))return g.length===0?"[]":g.length===1?String(g[0]):g.join(", ");if(typeof g=="object")return JSON.stringify(g);const v=String(g);if(v.includes("\\n")||v.length>100){const b=v.split("\\n").length;if(b>1)return`[${b} lines of G-code/script]`;if(v.length>100)return v.substring(0,100)+"…"}return v};return y.useEffect(()=>{const g=v=>{v.key==="Escape"&&t()};return window.addEventListener("keydown",g),()=>window.removeEventListener("keydown",g)},[t]),r.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:r.jsx(Tt,{className:"w-full max-w-4xl max-h-[85vh] flex flex-col overflow-hidden",children:r.jsxs(jt,{className:"p-0 flex flex-col min-h-0 flex-1",children:[r.jsxs("div",{className:"flex-shrink-0 flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[r.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[r.jsx(sy,{className:"w-5 h-5 text-blue-400"}),s("profiles.diff.title")]}),r.jsx("button",{onClick:t,className:"text-bambu-gray hover:text-white",children:r.jsx(Ht,{className:"w-5 h-5"})})]}),r.jsxs("div",{className:"flex-shrink-0 grid grid-cols-2 gap-4 p-4 border-b border-bambu-dark-tertiary bg-bambu-dark",children:[r.jsxs("div",{className:"text-center",children:[r.jsx("span",{className:"text-sm text-bambu-gray",children:s("profiles.diff.left")}),r.jsx("p",{className:"text-white font-medium truncate",children:n})]}),r.jsxs("div",{className:"text-center",children:[r.jsx("span",{className:"text-sm text-bambu-gray",children:s("profiles.diff.right")}),r.jsx("p",{className:"text-white font-medium truncate",children:i})]})]}),r.jsxs("div",{className:"flex-shrink-0 flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"flex items-center gap-4 text-sm",children:[r.jsxs("span",{className:"flex items-center gap-1 text-green-400",children:[r.jsx(or,{className:"w-3.5 h-3.5"}),p.added," ",s("profiles.diff.added")]}),r.jsxs("span",{className:"flex items-center gap-1 text-red-400",children:[r.jsx(hN,{className:"w-3.5 h-3.5"}),p.removed," ",s("profiles.diff.removed")]}),r.jsxs("span",{className:"flex items-center gap-1 text-amber-400",children:[r.jsx(dN,{className:"w-3.5 h-3.5"}),p.changed," ",s("profiles.diff.changed")]}),r.jsxs("span",{className:"flex items-center gap-1 text-bambu-gray",children:[r.jsx(SE,{className:"w-3.5 h-3.5"}),p.same," ",s("profiles.diff.same")]})]}),r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsxs("div",{className:"relative",children:[r.jsx(br,{className:"absolute left-2 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),r.jsx("input",{type:"text",value:c,onChange:g=>d(g.target.value),placeholder:s("profiles.diff.searchFields"),className:"pl-8 pr-3 py-1.5 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none w-48"})]}),p.same>0&&r.jsxs("div",{className:"flex rounded overflow-hidden border border-bambu-dark-tertiary",children:[r.jsx("button",{onClick:()=>l("changes"),className:`px-3 py-1.5 text-sm transition-colors ${o==="changes"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:s("profiles.diff.changes")}),r.jsx("button",{onClick:()=>l("all"),className:`px-3 py-1.5 text-sm transition-colors ${o==="all"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:s("common.all")})]})]})]}),r.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto",children:m.length===0?r.jsxs("div",{className:"text-center py-12 text-bambu-gray",children:[r.jsx(SE,{className:"w-12 h-12 mx-auto mb-4 opacity-30"}),r.jsx("p",{children:s(o==="changes"?"profiles.diff.noDifferences":"profiles.diff.noFieldsMatch")})]}):r.jsxs("table",{className:"w-full",children:[r.jsx("thead",{className:"sticky top-0 bg-bambu-dark-secondary",children:r.jsxs("tr",{className:"text-sm text-bambu-gray border-b border-bambu-dark-tertiary",children:[r.jsx("th",{className:"text-left p-3 w-1/3",children:s("profiles.diff.field")}),r.jsx("th",{className:"text-left p-3 w-1/3",children:n}),r.jsx("th",{className:"text-left p-3 w-1/3",children:i})]})}),r.jsx("tbody",{children:m.map(g=>{const v={added:"bg-green-500/10",removed:"bg-red-500/10",changed:"bg-amber-500/10",same:""}[g.status],b={added:r.jsx(or,{className:"w-3.5 h-3.5 text-green-400"}),removed:r.jsx(hN,{className:"w-3.5 h-3.5 text-red-400"}),changed:r.jsx(dN,{className:"w-3.5 h-3.5 text-amber-400"}),same:r.jsx(SE,{className:"w-3.5 h-3.5 text-bambu-gray-dark"})}[g.status];return r.jsxs("tr",{className:`border-b border-bambu-dark-tertiary ${v}`,children:[r.jsx("td",{className:"p-3",children:r.jsxs("div",{className:"flex items-center gap-2",children:[b,r.jsx("span",{className:"text-sm text-white font-mono",children:g.key})]})}),r.jsx("td",{className:"p-3",children:r.jsx("span",{className:`text-sm font-mono break-all ${g.status==="removed"?"text-red-300":g.status==="changed"?"text-white":"text-bambu-gray"}`,children:f(g.left)})}),r.jsx("td",{className:"p-3",children:r.jsx("span",{className:`text-sm font-mono break-all ${g.status==="added"?"text-green-300":g.status==="changed"?"text-white":"text-bambu-gray"}`,children:f(g.right)})})]},g.key)})})]})})]})})})}function pst({onClose:t,initialData:e,allPresets:a,t:n}){const{showToast:i}=da(),s=ia(),o=!!e?.setting_id,[l,c]=y.useState("common"),[d,u]=y.useState(e?.type||"filament"),[m,p]=y.useState(e?.name?o?e.name:`${e.name} (Copy)`:""),[f,g]=y.useState(e?.base_id||""),[v,b]=y.useState(""),[x,S]=y.useState(e?.setting||{inherits:""}),[k,P]=y.useState(JSON.stringify(e?.setting||{inherits:""},null,2)),[N,T]=y.useState(null),[j,D]=y.useState(""),[C,E]=y.useState(!1),[R,I]=y.useState(""),[O,z]=y.useState(!1),[X,ae]=y.useState(Pde),[Y,ce]=y.useState(!1),[de,oe]=y.useState(""),[K,ie]=y.useState(""),[ue,he]=y.useState(!0),[ge,q]=y.useState(null),[Q,A]=y.useState(!1),F=y.useMemo(()=>({filament:a.filament,print:a.process,printer:a.printer})[d]||[],[a,d]),B=y.useMemo(()=>F.filter(Re=>MS(Re.setting_id)),[F]),{data:W}=$e({queryKey:["cloudFields",d],queryFn:()=>ne.getCloudFields(d==="print"?"process":d),staleTime:1e3*60*60}),{data:H}=$e({queryKey:["allPresetDetails",d,B.map(Re=>Re.setting_id).join(",")],queryFn:async()=>{const Re={};for(let ze=0;ze{try{const Fe=await ne.getCloudSettingDetail(tt.setting_id);return{id:tt.setting_id,detail:Fe}}catch{return null}}))).forEach(tt=>{tt&&(Re[tt.id]=tt.detail)})}return Re},enabled:B.length>0,staleTime:1e3*60*10}),{data:le,isLoading:U}=$e({queryKey:["cloudSettingDetail",f],queryFn:()=>ne.getCloudSettingDetail(f),enabled:!!f});y.useEffect(()=>{l!=="json"&&P(JSON.stringify(x,null,2))},[x,l]);const G=y.useMemo(()=>({filament:a.filament,print:a.process,printer:a.printer}[d]||[]).filter(Ue=>!MS(Ue.setting_id)).sort((Ue,ze)=>Ue.name.localeCompare(ze.name)),[a,d]);y.useEffect(()=>{if(!f)return;const Re=G.find(Ue=>Ue.setting_id===f);Re&&(b(Re.name),o||(S({inherits:Re.name}),P(JSON.stringify({inherits:Re.name},null,2))))},[f,G,o]);const Z=y.useMemo(()=>{const Re=W?.fields||[],Ue=new Set(Re.map(tt=>tt.key)),ze=new Set,it=new Set(["inherits","updated_time","compatible_printers","compatible_prints"]);H&&Object.values(H).forEach(tt=>{tt?.setting&&Object.keys(tt.setting).forEach(Fe=>{!Ue.has(Fe)&&!it.has(Fe)&&ze.add(Fe)})}),Object.keys(x).forEach(tt=>{!Ue.has(tt)&&!it.has(tt)&&ze.add(tt)});const Oe=Array.from(ze).sort().map(tt=>({key:tt,label:tt.replace(/_/g," ").replace(/\b\w/g,Fe=>Fe.toUpperCase()),type:"text",category:"discovered",description:n("profiles.presets.discoveredFromPresets")}));return[...Re,...Oe]},[W,H,x,n]),J=Z.filter(Re=>Re.label.toLowerCase().includes(j.toLowerCase())||Re.key.toLowerCase().includes(j.toLowerCase())),re=()=>{if(R.trim()){const Re=R.trim().toLowerCase().replace(/\s+/g,"_");se(Re,""),I(""),z(!1),i(n("profiles.presets.toast.fieldAdded",{key:Re}))}},se=(Re,Ue)=>{S(ze=>{const it={...ze};return Ue===""||Ue===void 0?delete it[Re]:it[Re]=Ue,it})},fe=Re=>{S(Ue=>({...Ue,...Re.settings})),q(Re.name),i(n("profiles.templates.toast.applied"))},me=()=>{if(!de.trim())return;const Re={...x};if(delete Re.inherits,Object.keys(Re).length===0){i(n("profiles.presets.noOverridesToSave"),"error");return}const Ue={id:Date.now().toString(),name:de.trim(),description:K.trim()||n("profiles.presets.customTemplate"),type:d,settings:Re,showInModal:ue},ze=[...X,Ue];ae(ze),Nde(ze),ce(!1),oe(""),ie(""),he(!0),i(n("profiles.templates.toast.created"))},pe=y.useMemo(()=>X.filter(Re=>Re.type===d&&Re.showInModal),[d,X]),V=Re=>{P(Re);try{const Ue=JSON.parse(Re);S(Ue),T(null)}catch(Ue){T(Ue.message)}},L=Re=>{Re.preventDefault(),E(!1);const Ue=Re.dataTransfer.files[0];if(Ue&&Ue.name.endsWith(".json")){const ze=new FileReader;ze.onload=it=>{try{const Oe=it.target?.result,tt=JSON.parse(Oe),Fe=tt.setting||tt;S(Ye=>({...Ye,...Fe})),P(JSON.stringify({...x,...Fe},null,2)),i(n("profiles.presets.fileImported"))}catch{i(n("profiles.presets.invalidJsonFile"),"error")}},ze.readAsText(Ue)}},te=rt({mutationFn:()=>{const Re={...x},Ue=d==="filament"?"filament_settings_id":d==="print"?"print_settings_id":"printer_settings_id";Re[Ue]=`"${m}"`;const ze={type:d,name:m,base_id:f,setting:Re};return ne.createCloudSetting(ze)},onSuccess:async()=>{i(n("profiles.presets.toast.created")),await s.refetchQueries({queryKey:["cloudSettings"]}),t()},onError:Re=>i(Re.message,"error")}),be=rt({mutationFn:()=>{if(!e?.setting_id)throw new Error(n("profiles.presets.noSettingId"));return ne.updateCloudSetting(e.setting_id,{name:m,setting:x})},onSuccess:async()=>{i(n("profiles.presets.toast.updated")),s.removeQueries({queryKey:["cloudSettingDetail"]}),await s.refetchQueries({queryKey:["cloudSettings"]}),t()},onError:Re=>i(Re.message,"error")}),xe=o?be:te,ve=le?.setting?.inherits,De=ve?G.find(Re=>Re.name===ve):void 0,{data:je}=$e({queryKey:["cloudSettingDetail",De?.setting_id],queryFn:()=>ne.getCloudSettingDetail(De.setting_id),enabled:!!De?.setting_id}),Te=y.useMemo(()=>{const Re=je?.setting||{},Ue=le?.setting||{},ze=f&&H?.[f]?.setting?H[f].setting:{};return{...Re,...Ue,...ze}},[f,le,je,H]),qe=Re=>{if(Re==null)return"";if(Array.isArray(Re)){const Ue=[...new Set(Re.map(ze=>String(ze)))];return Ue.length===1?Ue[0]:Re.join(", ")}return String(Re)},Pe=Re=>{const Ue=x[Re.key],ze=Te[Re.key],it=qe(ze),Oe=U?n("common.loading"):it||"",tt="w-full px-3 py-1.5 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none";if(Re.type==="boolean"){const Fe=Ue==="1"||Ue===void 0&&ze==="1";return r.jsx("button",{type:"button",onClick:()=>se(Re.key,Ue==="1"?"0":"1"),className:`w-8 h-5 rounded-full transition-colors ${Fe?"bg-bambu-green":"bg-bambu-dark-tertiary"}`,children:r.jsx("div",{className:`w-4 h-4 rounded-full bg-white shadow transition-transform ${Fe?"translate-x-3.5":"translate-x-0.5"}`})})}return Re.type==="select"?r.jsxs("select",{value:Ue||"",onChange:Fe=>se(Re.key,Fe.target.value),className:tt,children:[r.jsx("option",{value:"",children:Oe}),Re.options?.map(Fe=>r.jsx("option",{value:Fe.value,children:Fe.label},Fe.value))]}):r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("input",{type:Re.type==="number"?"number":"text",value:Ue!==void 0?String(Ue):"",onChange:Fe=>se(Re.key,Fe.target.value),step:Re.step,min:Re.min,max:Re.max,placeholder:Oe,className:tt}),Re.unit&&r.jsx("span",{className:"text-xs text-bambu-gray whitespace-nowrap",children:Re.unit})]})},Ie=y.useMemo(()=>le?.setting?le.setting:{},[le]);return r.jsxs("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",onDragOver:Re=>{Re.preventDefault(),E(!0)},onDragLeave:()=>E(!1),onDrop:L,children:[Q&&f&&r.jsx(Tde,{onClose:()=>A(!1),leftPreset:Ie,rightPreset:x,leftLabel:n("profiles.presets.baseLabel",{name:v||f}),rightLabel:n("profiles.presets.currentLabel",{name:m||n("profiles.presets.newPreset")}),t:n}),r.jsx(Tt,{className:"w-full max-w-6xl max-h-[90vh] flex flex-col overflow-y-auto",children:r.jsxs(jt,{className:"p-0 flex flex-col h-full",children:[r.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[r.jsxs("div",{children:[r.jsx("h2",{className:"text-xl font-semibold text-white",children:n(o?"profiles.presets.editPreset":e?"profiles.presets.duplicatePreset":"profiles.presets.createNewPreset")}),r.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:n("profiles.presets.customizeSettings")})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[f&&r.jsxs("button",{onClick:()=>A(!0),className:"flex items-center gap-2 px-3 py-2 text-sm text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary rounded-lg transition-colors",title:n("profiles.presets.compareWithBase"),children:[r.jsx(sy,{className:"w-4 h-4"}),n("profiles.presets.compare")]}),r.jsx("button",{onClick:t,className:"p-2 text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary rounded-lg transition-colors",children:r.jsx(Ht,{className:"w-5 h-5"})})]})]}),C&&r.jsx("div",{className:"absolute inset-0 bg-bambu-green/10 border-2 border-dashed border-bambu-green rounded-lg flex items-center justify-center z-10",children:r.jsxs("div",{className:"text-center",children:[r.jsx(Sn,{className:"w-12 h-12 text-bambu-green mx-auto mb-2"}),r.jsx("p",{className:"text-bambu-green font-medium",children:n("profiles.presets.dropJsonToImport")})]})}),r.jsxs("div",{className:"p-4 border-b border-bambu-dark-tertiary space-y-3",children:[r.jsxs("div",{className:"grid grid-cols-3 gap-4 max-[640px]:grid-cols-1",children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("common.type")}),r.jsxs("select",{value:d,onChange:Re=>{u(Re.target.value),g("")},className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[r.jsx("option",{value:"filament",children:n("profiles.presets.types.filament")}),r.jsx("option",{value:"print",children:n("profiles.presets.types.process")}),r.jsx("option",{value:"printer",children:n("profiles.presets.types.printer")})]})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("profiles.presets.basePreset")}),r.jsxs("select",{value:f,onChange:Re=>g(Re.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",children:[r.jsx("option",{value:"",children:n("profiles.presets.selectBasePreset")}),G.map(Re=>r.jsx("option",{value:Re.setting_id,children:Re.name},Re.setting_id))]})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("profiles.presets.presetName")}),r.jsx("input",{type:"text",value:m,onChange:Re=>p(Re.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",placeholder:n("profiles.presets.myCustomPreset")})]})]}),v&&r.jsx("div",{className:"text-xs text-bambu-gray",children:r.jsxs("p",{className:"flex items-center gap-1",children:[r.jsx(_r,{className:"w-3 h-3 text-bambu-green"}),n("profiles.presets.inheritsFrom")," ",r.jsx("span",{className:"text-white",children:v}),U&&r.jsx(lt,{className:"w-3 h-3 animate-spin ml-1"})]})})]}),r.jsxs("div",{className:"flex border-b border-bambu-dark-tertiary max-[640px]:flex-wrap max-[640px]:items-center",children:[r.jsxs("button",{onClick:()=>c("common"),className:`flex items-center gap-2 px-4 py-3 text-sm font-medium transition-colors border-b-2 -mb-px ${l==="common"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-white border-transparent"}`,children:[r.jsx(M8,{className:"w-4 h-4"}),n("profiles.presets.tabs.common")]}),r.jsxs("button",{onClick:()=>c("fields"),className:`flex items-center gap-2 px-4 py-3 text-sm font-medium transition-colors border-b-2 -mb-px ${l==="fields"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-white border-transparent"}`,children:[r.jsx(BS,{className:"w-4 h-4"}),n("profiles.presets.tabs.allFields")]}),r.jsxs("button",{onClick:()=>c("json"),className:`flex items-center gap-2 px-4 py-3 text-sm font-medium transition-colors border-b-2 -mb-px ${l==="json"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-white border-transparent"}`,children:[r.jsx(tv,{className:"w-4 h-4"}),"JSON",N&&r.jsx(wn,{className:"w-3 h-3 text-red-400"})]}),r.jsx("div",{className:"flex-1 max-[640px]:hidden"}),r.jsxs("button",{onClick:()=>{const Re={name:m,type:d,base_id:f,setting:x},Ue=new Blob([JSON.stringify(Re,null,2)],{type:"application/json"}),ze=URL.createObjectURL(Ue),it=document.createElement("a");it.href=ze,it.download=`${m||"preset"}.json`,document.body.appendChild(it),it.click(),document.body.removeChild(it),URL.revokeObjectURL(ze),i(n("profiles.presets.toast.exported"))},className:"flex items-center gap-2 px-4 py-3 text-sm text-bambu-gray hover:text-white transition-colors",title:n("profiles.presets.exportToJson"),children:[r.jsx(Ur,{className:"w-4 h-4"}),n("common.download")]}),r.jsxs("button",{onClick:()=>document.getElementById("file-import")?.click(),className:"flex items-center gap-2 px-4 py-3 text-sm text-bambu-gray hover:text-white transition-colors",title:n("profiles.presets.importFromJson"),children:[r.jsx(Sn,{className:"w-4 h-4"}),n("common.upload")]}),r.jsx("input",{id:"file-import",type:"file",accept:".json",className:"hidden",onChange:Re=>{const Ue=Re.target.files?.[0];if(Ue){const ze=new FileReader;ze.onload=it=>{try{const Oe=JSON.parse(it.target?.result),tt=Oe.setting||Oe;S(Fe=>({...Fe,...tt})),i(n("profiles.presets.fileImported"))}catch{i(n("profiles.presets.invalidJson"),"error")}},ze.readAsText(Ue)}}})]}),r.jsxs("div",{className:"flex-1 p-4",children:[l==="common"&&r.jsxs("div",{className:"space-y-6",children:[r.jsxs("div",{children:[r.jsxs("div",{className:"flex items-center justify-between mb-3",children:[r.jsxs("h3",{className:"text-sm font-medium text-white flex items-center gap-2",children:[r.jsx(Ug,{className:"w-4 h-4 text-amber-400"}),n("profiles.templates.title")]}),Object.keys(x).filter(Re=>Re!=="inherits").length>0&&r.jsxs("button",{onClick:()=>ce(!Y),className:"text-xs text-bambu-gray hover:text-white flex items-center gap-1 transition-colors",children:[r.jsx(ms,{className:"w-3 h-3"}),n("profiles.presets.saveAsTemplate")]})]}),Y&&r.jsxs("div",{className:"mb-3 p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"grid grid-cols-2 gap-2 mb-2",children:[r.jsx("input",{type:"text",value:de,onChange:Re=>oe(Re.target.value),placeholder:n("profiles.templates.namePlaceholder"),className:"px-3 py-1.5 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none",autoFocus:!0}),r.jsx("input",{type:"text",value:K,onChange:Re=>ie(Re.target.value),placeholder:n("profiles.templates.descriptionPlaceholder"),className:"px-3 py-1.5 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none"})]}),r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("div",{className:"flex gap-2",children:[r.jsxs(Le,{size:"sm",onClick:me,disabled:!de.trim(),children:[r.jsx(ms,{className:"w-3 h-3"}),n("common.save")]}),r.jsx(Le,{size:"sm",variant:"secondary",onClick:()=>ce(!1),children:n("common.cancel")})]}),r.jsxs("button",{onClick:()=>he(!ue),className:`flex items-center gap-1.5 text-xs transition-colors ${ue?"text-bambu-green":"text-bambu-gray hover:text-white"}`,children:[ue?r.jsx(tl,{className:"w-3.5 h-3.5"}):r.jsx(Zh,{className:"w-3.5 h-3.5"}),n(ue?"profiles.templates.shownInModals":"profiles.templates.hiddenInModals")]})]})]}),ge&&r.jsxs("div",{className:"mb-3 px-3 py-2 bg-bambu-green/10 border border-bambu-green/30 rounded-lg flex items-center gap-2",children:[r.jsx(_r,{className:"w-4 h-4 text-bambu-green"}),r.jsxs("span",{className:"text-sm text-bambu-green",children:[n("profiles.presets.templateApplied")," ",r.jsx("span",{className:"font-medium",children:ge})]}),r.jsx("button",{onClick:()=>q(null),className:"ml-auto text-bambu-green/70 hover:text-bambu-green",children:r.jsx(Ht,{className:"w-4 h-4"})})]}),r.jsxs("div",{className:"grid grid-cols-3 gap-2",children:[pe.map(Re=>r.jsxs("button",{onClick:()=>fe(Re),className:"p-3 text-left bg-bambu-dark border border-bambu-dark-tertiary rounded-lg hover:border-bambu-gray-dark transition-colors",children:[r.jsx("p",{className:"text-sm font-medium text-white",children:Re.name}),r.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:Re.description})]},Re.id)),pe.length===0&&r.jsx("p",{className:"col-span-3 text-center text-bambu-gray text-sm py-4",children:n("profiles.presets.noTemplatesSelected")})]}),r.jsx("p",{className:"text-xs text-bambu-gray-dark mt-2 text-center",children:n("profiles.presets.manageTemplatesHint")})]}),r.jsxs("div",{children:[r.jsx("h3",{className:"text-sm font-medium text-white mb-3",children:n("profiles.presets.commonSettings")}),r.jsx("div",{className:"grid grid-cols-2 gap-x-6 gap-y-3",children:Z.slice(0,10).map(Re=>r.jsxs("div",{className:"flex items-center justify-between gap-4 max-[640px]:flex-col max-[640px]:items-start",children:[r.jsx("label",{className:"text-sm text-bambu-gray flex-shrink-0",children:Re.label}),r.jsx("div",{className:"w-48 max-[640px]:w-full",children:Pe(Re)})]},Re.key))})]}),Object.keys(x).length>1&&r.jsxs("div",{children:[r.jsx("h3",{className:"text-sm font-medium text-white mb-3",children:n("profiles.presets.currentOverrides")}),r.jsx("div",{className:"flex flex-wrap gap-2",children:Object.entries(x).filter(([Re])=>Re!=="inherits").map(([Re,Ue])=>r.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-1 bg-bambu-green/10 text-bambu-green text-xs rounded",children:[Re,": ",String(Ue).slice(0,20),r.jsx("button",{onClick:()=>se(Re,void 0),className:"hover:text-white",children:r.jsx(Ht,{className:"w-3 h-3"})})]},Re))})]})]}),l==="fields"&&r.jsxs("div",{className:"grid grid-cols-2 gap-6",style:{height:"400px"},children:[r.jsxs("div",{className:"flex flex-col h-full overflow-hidden",children:[r.jsxs("div",{className:"flex items-center justify-between mb-3 flex-shrink-0",children:[r.jsx("h3",{className:"text-sm font-medium text-white",children:n("profiles.presets.availableFields")}),r.jsx("span",{className:"text-xs text-bambu-gray",children:H?n("profiles.templates.fieldsCount",{count:Z.length}):n("common.loading")})]}),r.jsxs("div",{className:"relative mb-3 flex-shrink-0",children:[r.jsx(br,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),r.jsx("input",{type:"text",value:j,onChange:Re=>D(Re.target.value),placeholder:n("profiles.presets.searchFieldsPlaceholder"),className:"w-full pl-10 pr-4 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder-bambu-gray-dark focus:border-bambu-green focus:outline-none"})]}),r.jsxs("div",{className:"flex-1 overflow-y-auto space-y-1 pr-2 min-h-0",children:[J.filter(Re=>!(Re.key in x)).map(Re=>{const Ue=Te[Re.key],ze=qe(Ue);return r.jsxs("div",{onClick:()=>{S(it=>({...it,[Re.key]:ze||""}))},className:"flex items-center justify-between gap-2 p-2 rounded-lg hover:bg-bambu-dark-tertiary transition-colors cursor-pointer group",children:[r.jsxs("div",{className:"min-w-0 flex-1",children:[r.jsx("p",{className:"text-sm text-white truncate",children:Re.label}),r.jsx("p",{className:"text-xs text-bambu-gray-dark truncate",children:Re.key})]}),r.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[ze&&r.jsxs("span",{className:"text-xs text-bambu-gray bg-bambu-dark px-2 py-0.5 rounded max-w-32 truncate",title:ze,children:[ze.slice(0,20),ze.length>20?"...":""]}),r.jsx("div",{className:"w-6 h-6 flex items-center justify-center rounded bg-bambu-dark-tertiary group-hover:bg-bambu-green/20 transition-colors",children:r.jsx(or,{className:"w-4 h-4 text-bambu-gray group-hover:text-bambu-green transition-colors"})})]})]},Re.key)}),J.filter(Re=>!(Re.key in x)).length===0&&r.jsx("p",{className:"text-center text-bambu-gray py-4 text-sm",children:n(j?"profiles.presets.noMatchingFields":"profiles.presets.allFieldsAdded")})]}),r.jsx("div",{className:"pt-3 mt-3 border-t border-bambu-dark-tertiary flex-shrink-0",children:O?r.jsxs("div",{className:"flex gap-2",children:[r.jsx("input",{type:"text",value:R,onChange:Re=>I(Re.target.value),onKeyDown:Re=>Re.key==="Enter"&&re(),placeholder:"custom_field_name",className:"flex-1 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white font-mono text-sm placeholder-bambu-gray-dark focus:border-bambu-green focus:outline-none",autoFocus:!0}),r.jsx(Le,{size:"sm",onClick:re,disabled:!R.trim(),children:r.jsx(or,{className:"w-4 h-4"})}),r.jsx(Le,{size:"sm",variant:"secondary",onClick:()=>{z(!1),I("")},children:r.jsx(Ht,{className:"w-4 h-4"})})]}):r.jsxs("button",{onClick:()=>z(!0),className:"w-full flex items-center justify-center gap-2 p-2 text-sm text-bambu-gray hover:text-white border border-dashed border-bambu-dark-tertiary hover:border-bambu-gray-dark rounded-lg transition-colors",children:[r.jsx(or,{className:"w-4 h-4"}),n("profiles.presets.addCustomField")]})})]}),r.jsxs("div",{className:"flex flex-col h-full overflow-hidden",children:[r.jsxs("div",{className:"flex items-center justify-between mb-3 flex-shrink-0",children:[r.jsx("h3",{className:"text-sm font-medium text-white",children:n("profiles.presets.yourOverrides")}),r.jsx("span",{className:"text-xs text-bambu-gray",children:n("profiles.templates.fieldsCount",{count:Object.keys(x).filter(Re=>Re!=="inherits").length})})]}),r.jsxs("div",{className:"flex-1 overflow-y-auto space-y-2 pr-2 min-h-0",children:[Object.entries(x).filter(([Re])=>Re!=="inherits").map(([Re,Ue])=>{const ze=Z.find(it=>it.key===Re);return r.jsxs("div",{className:"p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"flex items-center justify-between mb-2",children:[r.jsxs("div",{children:[r.jsx("p",{className:"text-sm font-medium text-white",children:ze?.label||Re}),r.jsx("p",{className:"text-xs text-bambu-gray-dark",children:Re})]}),r.jsx("button",{onClick:()=>se(Re,void 0),className:"p-1 text-bambu-gray hover:text-red-400 transition-colors",children:r.jsx(Ht,{className:"w-4 h-4"})})]}),ze?Pe(ze):r.jsx("input",{type:"text",value:String(Ue),onChange:it=>se(Re,it.target.value),className:"w-full px-3 py-1.5 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none"})]},Re)}),Object.keys(x).filter(Re=>Re!=="inherits").length===0&&r.jsxs("div",{className:"text-center py-8 text-bambu-gray",children:[r.jsx(M8,{className:"w-8 h-8 mx-auto mb-2 opacity-50"}),r.jsx("p",{className:"text-sm",children:n("profiles.presets.noOverridesYet")}),r.jsx("p",{className:"text-xs mt-1",children:n("profiles.presets.clickFieldsToAdd")})]})]}),Object.keys(x).filter(Re=>Re!=="inherits").length>0&&r.jsx("div",{className:"pt-3 mt-3 border-t border-bambu-dark-tertiary flex-shrink-0",children:r.jsxs("button",{onClick:()=>{ce(!0),c("common")},className:"w-full flex items-center justify-center gap-2 p-2 text-sm text-bambu-gray hover:text-white border border-dashed border-bambu-dark-tertiary hover:border-bambu-gray-dark rounded-lg transition-colors",children:[r.jsx(ms,{className:"w-4 h-4"}),n("profiles.presets.saveAsTemplate")]})})]})]}),l==="json"&&r.jsxs("div",{className:"space-y-2",children:[N&&r.jsxs("div",{className:"flex items-center gap-2 text-red-400 text-sm",children:[r.jsx(wn,{className:"w-4 h-4"}),N]}),r.jsx("textarea",{value:k,onChange:Re=>V(Re.target.value),className:`w-full h-80 px-3 py-2 bg-bambu-dark border rounded-lg text-white text-xs font-mono focus:outline-none resize-none ${N?"border-red-500 focus:border-red-500":"border-bambu-dark-tertiary focus:border-bambu-green"}`,spellCheck:!1}),r.jsx("p",{className:"text-xs text-bambu-gray",children:n("profiles.presets.jsonTip")})]})]}),r.jsxs("div",{className:"p-4 border-t border-bambu-dark-tertiary flex gap-2",children:[r.jsx(Le,{variant:"secondary",onClick:t,className:"flex-1",children:n("common.cancel")}),r.jsxs(Le,{onClick:()=>xe.mutate(),disabled:xe.isPending||!m.trim()||!o&&!f||!!N,className:"flex-1",children:[xe.isPending?r.jsx(lt,{className:"w-4 h-4 animate-spin"}):o?r.jsx(ms,{className:"w-4 h-4"}):r.jsx(or,{className:"w-4 h-4"}),n(o?"common.save":e?"common.duplicate":"common.create")]})]})]})})]})}function hst({settings:t,lastSyncTime:e,onRefresh:a,isRefreshing:n,printers:i,hasPermission:s,t:o}){const[l,c]=y.useState(""),[d,u]=y.useState("all"),[m,p]=y.useState("all"),[f,g]=y.useState("all"),[v,b]=y.useState("all"),[x,S]=y.useState("all"),[k,P]=y.useState("all"),[N,T]=y.useState(null),[j,D]=y.useState(!1),[C,E]=y.useState(!1),[R,I]=y.useState(null),[O,z]=y.useState(null),[X,ae]=y.useState(null),[Y,ce]=y.useState(!1),[de,oe]=y.useState([null,null]),[K,ie]=y.useState(!1),[ue,he]=y.useState(null),ge=ia(),q=y.useMemo(()=>[...t.filament.map(re=>({...re,type:"filament"})),...t.printer.map(re=>({...re,type:"printer"})),...t.process.map(re=>({...re,type:"process"}))].map(re=>({...re,meta:T5(re.name)})),[t]),Q=y.useMemo(()=>{const J=new Set,re=new Set,se=new Set;return q.forEach(fe=>{fe.meta.nozzle&&J.add(fe.meta.nozzle),fe.meta.filamentType&&re.add(fe.meta.filamentType),fe.meta.layerHeight&&se.add(fe.meta.layerHeight)}),{printers:i.map(fe=>({id:fe.id.toString(),name:fe.name})),nozzles:Array.from(J).sort((fe,me)=>parseFloat(fe)-parseFloat(me)),filaments:Array.from(re).sort(),layerHeights:Array.from(se).sort((fe,me)=>parseFloat(fe)-parseFloat(me))}},[q,i]),A=y.useMemo(()=>f==="all"?null:i.find(re=>re.id.toString()===f)?.model||null,[f,i]),F=y.useMemo(()=>q.filter(J=>d==="all"||J.type===d).filter(J=>{if(m==="all")return!0;const re=MS(J.setting_id);return m==="custom"?re:!re}).filter(J=>{if(f==="all"||!A)return!0;const re=J.meta.printer?.toLowerCase()||"",se=A.toLowerCase();return re.includes(se)||se.includes(re)}).filter(J=>v==="all"||J.meta.nozzle===v).filter(J=>x==="all"||J.meta.filamentType===x).filter(J=>k==="all"||J.meta.layerHeight===k).filter(J=>l===""||J.name.toLowerCase().includes(l.toLowerCase())).sort((J,re)=>J.name.localeCompare(re.name)),[q,d,m,f,A,v,x,k,l]),B=J=>{if(Y){const re=de[0]?.setting_id===J.setting_id,se=de[1]?.setting_id===J.setting_id;if(re)oe([de[1],null]);else if(se)oe([de[0],null]);else if(!de[0])oe([J,null]);else if(de[1]){if(de[0].type!==J.type)return;oe([de[0],J])}else{if(de[0].type!==J.type)return;oe([de[0],J])}}else T(J)},W=J=>{if(de[0]?.setting_id===J.setting_id)return 0;if(de[1]?.setting_id===J.setting_id)return 1},H=async J=>{try{const re=await ne.getCloudSettingDetail(J.setting_id),se=J.type==="process"?"print":J.type;I({type:se,name:J.name,base_id:re.base_id||"GFSA00",setting:re.setting||{}}),T(null)}catch(re){console.error("Failed to fetch preset details for duplication:",re)}},le=async J=>{try{ge.removeQueries({queryKey:["cloudSettingDetail",J.setting_id]});const re=await ne.getCloudSettingDetail(J.setting_id),se=J.type==="process"?"print":J.type;z({type:se,name:J.name,base_id:re.base_id||"GFSA00",setting:re.setting||{},setting_id:J.setting_id}),T(null)}catch(re){console.error("Failed to fetch preset details for editing:",re)}},U=()=>{u("all"),p("all"),g("all"),b("all"),S("all"),P("all"),c("")},G=d!=="all"||m!=="all"||f!=="all"||v!=="all"||x!=="all"||k!=="all"||l!=="",Z=t.filament.length+t.printer.length+t.process.length;return r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"space-y-4 mb-6",children:[r.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[r.jsxs("div",{className:"relative flex-1",children:[r.jsx(br,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),r.jsx("input",{type:"text",value:l,onChange:J=>c(J.target.value),placeholder:o("profiles.cloudView.searchPlaceholder"),className:"w-full pl-10 pr-4 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray-dark focus:border-bambu-green focus:outline-none"})]}),r.jsxs("div",{className:"flex gap-2 max-[550px]:flex-wrap max-[550px]:items-center",children:[r.jsxs(Le,{variant:Y?"primary":"secondary",onClick:()=>{Y?(ce(!1),oe([null,null])):ce(!0)},children:[r.jsx(sy,{className:"w-4 h-4"}),o(Y?"common.cancel":"profiles.presets.compare")]}),r.jsxs(Le,{variant:"secondary",onClick:()=>E(!0),disabled:!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.cloudView.noTemplatesPermission"),children:[r.jsx(Ug,{className:"w-4 h-4"}),o("profiles.cloudView.templates")]}),r.jsxs(Le,{variant:"secondary",onClick:a,disabled:n||!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.cloudView.noRefreshPermission"),children:[r.jsx(tr,{className:`w-4 h-4 ${n?"animate-spin":""}`}),o("profiles.cloudView.refresh")]}),r.jsxs(Le,{onClick:()=>D(!0),disabled:!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.cloudView.noCreatePermission"),children:[r.jsx(or,{className:"w-4 h-4"}),o("profiles.cloudView.newPreset")]})]})]}),r.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[r.jsx(av,{className:"w-4 h-4 text-bambu-gray"}),r.jsx(id,{label:o("profiles.cloudView.filters.type"),value:d,options:[{value:"all",label:o("profiles.cloudView.filters.all"),count:Z},{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:J=>u(J)}),r.jsx(id,{label:o("profiles.cloudView.filters.owner"),value:m,options:[{value:"all",label:o("profiles.cloudView.filters.all")},{value:"custom",label:o("profiles.cloudView.filters.myPresets")},{value:"builtin",label:o("profiles.cloudView.filters.builtIn")}],onChange:J=>p(J)}),Q.printers.length>0&&r.jsx(id,{label:o("profiles.cloudView.filters.printer"),value:f,options:[{value:"all",label:o("profiles.cloudView.filters.all")},...Q.printers.map(J=>({value:J.id,label:J.name}))],onChange:g}),Q.nozzles.length>0&&r.jsx(id,{label:o("profiles.cloudView.filters.nozzle"),value:v,options:[{value:"all",label:o("profiles.cloudView.filters.all")},...Q.nozzles.map(J=>({value:J,label:J}))],onChange:b}),Q.filaments.length>0&&(d==="all"||d==="filament")&&r.jsx(id,{label:o("profiles.cloudView.filters.filament"),value:x,options:[{value:"all",label:o("profiles.cloudView.filters.all")},...Q.filaments.map(J=>({value:J,label:J}))],onChange:S}),Q.layerHeights.length>0&&(d==="all"||d==="process")&&r.jsx(id,{label:o("profiles.cloudView.filters.layer"),value:k,options:[{value:"all",label:o("profiles.cloudView.filters.all")},...Q.layerHeights.map(J=>({value:J,label:J}))],onChange:P}),G&&r.jsx("button",{onClick:U,className:"px-3 py-2 text-sm text-bambu-gray hover:text-white transition-colors",children:o("profiles.cloudView.clearFilters")})]})]}),Y&&r.jsx("div",{className:"mb-4 p-3 bg-blue-500/10 border border-blue-500/30 rounded-lg",children:r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("div",{className:"flex items-center gap-4",children:[r.jsx(sy,{className:"w-5 h-5 text-blue-400"}),r.jsx("span",{className:"text-white font-medium",children:o("profiles.cloudView.compareMode")}),r.jsx("span",{className:"text-bambu-gray",children:de[0]?o("profiles.cloudView.selectAnotherPreset",{type:de[0].type}):o("profiles.cloudView.clickTwoPresets")})]}),r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("span",{className:`px-2 py-1 text-sm rounded truncate max-w-[200px] ${de[0]?"bg-blue-500/30 text-blue-700 dark:text-blue-300":"bg-bambu-dark text-bambu-gray"}`,children:de[0]?de[0].name:o("profiles.cloudView.selectFirst")}),r.jsx(dN,{className:"w-4 h-4 text-bambu-gray"}),r.jsx("span",{className:`px-2 py-1 text-sm rounded truncate max-w-[200px] ${de[1]?"bg-blue-500/30 text-blue-700 dark:text-blue-300":"bg-bambu-dark text-bambu-gray"}`,children:de[1]?de[1].name:o("profiles.cloudView.selectSecond")})]}),de[0]&&de[1]&&r.jsxs(Le,{size:"sm",onClick:async()=>{try{const[J,re]=await Promise.all([ne.getCloudSettingDetail(de[0].setting_id),ne.getCloudSettingDetail(de[1].setting_id)]);he([J.setting||{},re.setting||{}]),ie(!0)}catch{}},children:[r.jsx(sy,{className:"w-4 h-4"}),o("profiles.cloudView.compareNow")]})]})]})}),r.jsxs("div",{className:"flex flex-wrap items-center gap-4 mb-4 text-sm text-bambu-gray",children:[e&&r.jsxs("div",{className:"flex items-center gap-1",children:[r.jsx(ar,{className:"w-3 h-3"}),o("profiles.cloudView.lastSynced")," ",Om(e.toISOString(),"system",o)]}),r.jsx("span",{children:o("profiles.cloudView.showingCount",{showing:F.length,total:Z})}),r.jsxs("div",{className:"flex items-center gap-1",children:[r.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-bambu-green"}),r.jsxs("span",{children:["= ",o("profiles.presets.myPreset")]})]})]}),F.length===0?r.jsxs("div",{className:"text-center py-16",children:[r.jsx(tn,{className:"w-12 h-12 text-bambu-gray-dark mx-auto mb-4"}),r.jsx("p",{className:"text-bambu-gray",children:o("profiles.cloudView.noPresetsFound")}),G&&r.jsx("button",{onClick:U,className:"mt-2 text-sm text-bambu-green hover:text-bambu-green-light",children:o("profiles.cloudView.clearFilters")})]}):r.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-6",children:[r.jsxs("div",{children:[r.jsxs("div",{className:"flex items-center gap-2 mb-3 px-1",children:[r.jsx(RS,{className:"w-4 h-4 text-amber-400"}),r.jsx("h3",{className:"text-sm font-medium text-bambu-gray",children:o("profiles.cloudView.columns.filament")}),r.jsxs("span",{className:"text-xs text-bambu-gray-dark",children:["(",F.filter(J=>J.type==="filament").length,")"]})]}),r.jsxs("div",{className:"space-y-1 max-h-[calc(100vh-320px)] overflow-y-auto pr-1",children:[F.filter(J=>J.type==="filament").map(J=>r.jsx(EL,{setting:J,onClick:()=>B(J),onDuplicate:()=>H(J),compareMode:Y,isCompareSelected:W(J)!==void 0,compareIndex:W(J),compareDisabled:Y&&!!de[0]&&de[0].type!==J.type,t:o},J.setting_id)),F.filter(J=>J.type==="filament").length===0&&r.jsx("p",{className:"text-xs text-bambu-gray-dark px-3 py-2",children:o("profiles.cloudView.noFilamentPresets")})]})]}),r.jsxs("div",{children:[r.jsxs("div",{className:"flex items-center gap-2 mb-3 px-1",children:[r.jsx(xd,{className:"w-4 h-4 text-blue-400"}),r.jsx("h3",{className:"text-sm font-medium text-bambu-gray",children:o("profiles.cloudView.columns.process")}),r.jsxs("span",{className:"text-xs text-bambu-gray-dark",children:["(",F.filter(J=>J.type==="process").length,")"]})]}),r.jsxs("div",{className:"space-y-1 max-h-[calc(100vh-320px)] overflow-y-auto pr-1",children:[F.filter(J=>J.type==="process").map(J=>r.jsx(EL,{setting:J,onClick:()=>B(J),onDuplicate:()=>H(J),compareMode:Y,isCompareSelected:W(J)!==void 0,compareIndex:W(J),compareDisabled:Y&&!!de[0]&&de[0].type!==J.type,t:o},J.setting_id)),F.filter(J=>J.type==="process").length===0&&r.jsx("p",{className:"text-xs text-bambu-gray-dark px-3 py-2",children:o("profiles.cloudView.noProcessPresets")})]})]}),r.jsxs("div",{children:[r.jsxs("div",{className:"flex items-center gap-2 mb-3 px-1",children:[r.jsx(xr,{className:"w-4 h-4 text-purple-400"}),r.jsx("h3",{className:"text-sm font-medium text-bambu-gray",children:o("profiles.cloudView.columns.printer")}),r.jsxs("span",{className:"text-xs text-bambu-gray-dark",children:["(",F.filter(J=>J.type==="printer").length,")"]})]}),r.jsxs("div",{className:"space-y-1 max-h-[calc(100vh-320px)] overflow-y-auto pr-1",children:[F.filter(J=>J.type==="printer").map(J=>r.jsx(EL,{setting:J,onClick:()=>B(J),onDuplicate:()=>H(J),compareMode:Y,isCompareSelected:W(J)!==void 0,compareIndex:W(J),compareDisabled:Y&&!!de[0]&&de[0].type!==J.type,t:o},J.setting_id)),F.filter(J=>J.type==="printer").length===0&&r.jsx("p",{className:"text-xs text-bambu-gray-dark px-3 py-2",children:o("profiles.cloudView.noPrinterPresets")})]})]})]}),N&&r.jsx(ust,{setting:N,onClose:()=>T(null),onDeleted:()=>T(null),onDuplicate:()=>H(N),onEdit:()=>le(N),hasPermission:s,t:o}),(j||R||O||X)&&r.jsx(pst,{onClose:()=>{D(!1),I(null),z(null),ae(null)},initialData:O||R||(X?{type:X.type,name:"",base_id:"",setting:X.setting}:void 0),allPresets:t,t:o}),C&&r.jsx(mst,{onClose:()=>E(!1),onApply:J=>{ae({type:J.type,setting:J.settings}),E(!1)},t:o}),K&&ue&&de[0]&&de[1]&&r.jsx(Tde,{onClose:()=>{ie(!1),he(null)},leftPreset:ue[0],rightPreset:ue[1],leftLabel:de[0].name,rightLabel:de[1].name,t:o})]})}function fst(){const{t}=wt(),e=ia(),{showToast:a}=da(),{hasPermission:n}=lr(),[i,s]=y.useState("cloud"),[o,l]=y.useState(),{data:c,isLoading:d}=$e({queryKey:["cloudStatus"],queryFn:ne.getCloudStatus}),{data:u=[]}=$e({queryKey:["printers"],queryFn:ne.getPrinters}),{data:m,isLoading:p,refetch:f,dataUpdatedAt:g}=$e({queryKey:["cloudSettings"],queryFn:()=>ne.getCloudSettings(),enabled:!!c?.is_authenticated,retry:!1,staleTime:1e3*60*5});y.useEffect(()=>{g&&l(new Date(g))},[g]);const v=rt({mutationFn:ne.cloudLogout,onSuccess:()=>{e.invalidateQueries({queryKey:["cloudStatus"]}),e.removeQueries({queryKey:["cloudSettings"]}),a(t("profiles.toast.loggedOut"))}}),b=()=>{e.invalidateQueries({queryKey:["cloudStatus"]})};return d?r.jsx("div",{className:"p-4 md:p-8 flex items-center justify-center min-h-[400px]",children:r.jsx(lt,{className:"w-8 h-8 text-bambu-green animate-spin"})}):r.jsxs("div",{className:"p-4 md:p-8",children:[r.jsxs("div",{className:"mb-6",children:[r.jsxs("h1",{className:"text-2xl font-bold text-white flex items-center gap-3",children:[r.jsx(Im,{className:"w-7 h-7 text-bambu-green"}),t("profiles.title")]}),r.jsx("p",{className:"text-bambu-gray mt-1",children:t("profiles.subtitle")})]}),r.jsxs("div",{className:"flex border-b border-bambu-dark-tertiary mb-6",children:[r.jsxs("button",{onClick:()=>s("cloud"),className:`flex items-center gap-2 px-4 py-3 text-sm font-medium transition-colors border-b-2 -mb-px ${i==="cloud"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-white border-transparent"}`,children:[r.jsx(Im,{className:"w-4 h-4"}),t("profiles.tabs.bambuCloud")]}),r.jsxs("button",{onClick:()=>s("orca_cloud"),className:`flex items-center gap-2 px-4 py-3 text-sm font-medium transition-colors border-b-2 -mb-px ${i==="orca_cloud"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-white border-transparent"}`,children:[r.jsx(Im,{className:"w-4 h-4"}),t("profiles.tabs.orcaCloud")]}),r.jsxs("button",{onClick:()=>s("local"),className:`flex items-center gap-2 px-4 py-3 text-sm font-medium transition-colors border-b-2 -mb-px ${i==="local"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-white border-transparent"}`,children:[r.jsx(hb,{className:"w-4 h-4"}),t("profiles.tabs.local")]}),r.jsxs("button",{onClick:()=>s("kprofiles"),className:`flex items-center gap-2 px-4 py-3 text-sm font-medium transition-colors border-b-2 -mb-px ${i==="kprofiles"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-white border-transparent"}`,children:[r.jsx(zS,{className:"w-4 h-4"}),t("profiles.tabs.kprofiles")]})]}),i==="cloud"&&r.jsxs(r.Fragment,{children:[c?.is_authenticated&&r.jsxs("div",{className:"flex items-center justify-between p-3 mb-6 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("div",{className:"w-2 h-2 rounded-full bg-bambu-green animate-pulse"}),r.jsxs("span",{className:"text-sm text-bambu-gray",children:[t("profiles.connectedAs")," ",r.jsx("span",{className:"text-white",children:c.email}),c.region&&r.jsx("span",{className:"ml-2 px-2 py-0.5 text-xs rounded bg-bambu-dark-tertiary text-bambu-gray",children:c.region==="china"?t("profiles.login.regionChina"):t("profiles.login.regionGlobal")})]})]}),r.jsxs(Le,{variant:"secondary",size:"sm",onClick:()=>v.mutate(),disabled:v.isPending||!n("cloud:auth"),title:n("cloud:auth")?void 0:t("profiles.noLogoutPermission"),children:[r.jsx(Sg,{className:"w-4 h-4"}),t("profiles.logout")]})]}),c?.is_authenticated?p?r.jsx("div",{className:"flex items-center justify-center py-16",children:r.jsx(lt,{className:"w-8 h-8 text-bambu-green animate-spin"})}):m?r.jsx(hst,{settings:m,lastSyncTime:o,onRefresh:()=>f(),isRefreshing:p,printers:u,hasPermission:n,t}):r.jsxs("div",{className:"text-center py-16",children:[r.jsx("p",{className:"text-bambu-gray mb-4",children:t("profiles.failedToLoad")}),r.jsx(Le,{onClick:()=>f(),children:t("profiles.retry")})]}):r.jsx(cst,{onSuccess:b,t})]}),i==="orca_cloud"&&r.jsx(nst,{}),i==="local"&&r.jsx(Jit,{}),i==="kprofiles"&&r.jsx(Yit,{}),r.jsx(dst,{})]})}function gst(t,e){const a=(e||"").toUpperCase().replace(/[- ]/g,""),n=a.includes("X1"),i=a.includes("P1"),s=a.includes("A1MINI"),o=a.includes("A1")&&!s,l=a.includes("H2D"),c=a.includes("H2C"),d=a.includes("H2S"),u=l||c||d,m=a.includes("P2S"),p=a.includes("X2D"),f=m||p;switch(t){case"Lubricate Steel Rods":return f?"https://wiki.bambulab.com/en/p2s/maintenance/lubricate-x-y-z-axis":null;case"Clean Steel Rods":return f?"https://wiki.bambulab.com/en/p2s/maintenance/lubricate-x-y-z-axis":null;case"Lubricate Linear Rails":return s?"https://wiki.bambulab.com/en/a1-mini/maintenance/lubricate-y-axis":o?"https://wiki.bambulab.com/en/a1/maintenance/lubricate-y-axis":u?"https://wiki.bambulab.com/en/h2/maintenance/x-axis-lubrication":null;case"Clean Nozzle/Hotend":return n||i?"https://wiki.bambulab.com/en/x1/troubleshooting/nozzle-clog":s||o?"https://wiki.bambulab.com/en/a1-mini/troubleshooting/nozzle-clog":u?"https://wiki.bambulab.com/en/h2/maintenance/nozzl-cold-pull-maintenance-and-cleaning":f?"https://wiki.bambulab.com/en/p2s/maintenance/cold-pull-maintenance-hotend":"https://wiki.bambulab.com/en/x1/troubleshooting/nozzle-clog";case"Check Belt Tension":return n?"https://wiki.bambulab.com/en/x1/maintenance/belt-tension":i?"https://wiki.bambulab.com/en/p1/maintenance/p1p-maintenance":s?"https://wiki.bambulab.com/en/a1-mini/maintenance/belt_tension":o?"https://wiki.bambulab.com/en/a1/maintenance/belt_tension":l?"https://wiki.bambulab.com/en/h2/maintenance/belt-tension":c?"https://wiki.bambulab.com/en/h2c/maintenance/belt-tension":d?"https://wiki.bambulab.com/en/h2s/maintenance/belt-tension":f?"https://wiki.bambulab.com/en/p2s/maintenance/belt-tension":"https://wiki.bambulab.com/en/x1/maintenance/belt-tension";case"Clean Carbon Rods":return n||i?"https://wiki.bambulab.com/en/general/carbon-rods-clearance":null;case"Clean Linear Rails":return s?"https://wiki.bambulab.com/en/a1-mini/maintenance/lubricate-y-axis":o?"https://wiki.bambulab.com/en/a1/maintenance/lubricate-y-axis":u?"https://wiki.bambulab.com/en/h2/maintenance/x-axis-lubrication":null;case"Clean Build Plate":return"https://wiki.bambulab.com/en/filament-acc/acc/pei-plate-clean-guide";case"Check PTFE Tube":return n||i?"https://wiki.bambulab.com/en/x1/maintenance/replace-ptfe-tube":s||o?"https://wiki.bambulab.com/en/a1-mini/maintenance/ptfe-tube":l?"https://wiki.bambulab.com/en/h2/maintenance/replace-ptfe-tube-on-h2d-printer":d?"https://wiki.bambulab.com/en/h2s/maintenance/replace-ptfe-tube-on-h2s-printer":c?"https://wiki.bambulab.com/en/h2/maintenance/replace-ptfe-tube-on-h2d-printer":"https://wiki.bambulab.com/en/x1/maintenance/replace-ptfe-tube";case"Replace HEPA Filter":case"HEPA Filter":case"Replace Carbon Filter":case"Carbon Filter":return u?"https://wiki.bambulab.com/en/h2/maintenance/replace-smoke-purifier-air-filte":"https://wiki.bambulab.com/en/x1/maintenance/replace-carbon-filter";case"Lubricate Left Nozzle Rail":case"Left Nozzle Rail":return u?"https://wiki.bambulab.com/en/h2/maintenance/x-axis-lubrication":null;default:return null}}const nw={Droplet:RS,Flame:xm,Ruler:$ye,Sparkles:Ug,Square:so,Cable:RI,Wrench:Jm,Calendar:Cn,Timer:ru,Cog:bd,Fan:iJ,Zap:jc,Wind:xJ,Thermometer:VS,Layers:tn,Box:Ei,Target:fJ,RefreshCw:tr,Settings:Sy,Filter:av,CircleDot:Yge};function Dw(t){return t&&nw[t]||Jm}function qx(t,e,a){if(e==="days"){if(t<1)return a?a("common.today"):"Today";if(t===1)return a?a("maintenance.day"):"1 day";if(t<7){const i=Math.round(t);return a?a("maintenance.days",{count:i}):`${i} days`}if(t<180){const i=Math.round(t/7);return i===1?a?a("maintenance.week"):"1 week":a?a("maintenance.weeks",{count:i}):`${i} weeks`}const n=Math.round(t/30);return n===1?a?a("maintenance.month"):"1 month":a?a("maintenance.months",{count:n}):`${n} months`}else{if(t<1)return`${Math.round(t*60)}m`;if(t<24)return`${t<10?t.toFixed(1):Math.round(t)}h`;const n=t/24;if(n<7)return`${n<2?n.toFixed(1):Math.round(n)}d`;const i=n/7;return i<12?`${i<2?i.toFixed(1):Math.round(i)}w`:`${Math.round(i/4)}mo`}}function DL(t,e,a){return e==="days"?t===1?a?a("maintenance.day"):"1 day":t===7?a?a("maintenance.week"):"1 week":t===14?a?a("maintenance.weeks",{count:2}):"2 weeks":t===30?a?a("maintenance.month"):"1 month":t===60?a?a("maintenance.months",{count:2}):"2 months":t===90?a?a("maintenance.months",{count:3}):"3 months":t===180?a?a("maintenance.months",{count:6}):"6 months":t===365?a?a("maintenance.year"):"1 year":a?a("maintenance.days",{count:t}):`${t} days`:`${t}h`}function bst({item:t,onPerform:e,onToggle:a,hasPermission:n,t:i}){const s=Dw(t.maintenance_type_icon),o=t.interval_type||"hours",c=(()=>{if(o==="days"){const f=t.days_since_maintenance??0;return Math.max(0,Math.min(100,f/t.interval_hours*100))}return Math.max(0,Math.min(100,(t.interval_hours-t.hours_until_due)/t.interval_hours*100))})(),d=()=>t.enabled?t.is_due?"text-red-400":t.is_warning?"text-amber-400":"text-bambu-green":"text-bambu-gray",u=()=>t.enabled?t.is_due?"bg-red-500":t.is_warning?"bg-amber-500":"bg-bambu-green":"bg-bambu-gray/30",m=()=>t.enabled?t.is_due?"bg-red-500/5 border-red-500/20":t.is_warning?"bg-amber-500/5 border-amber-500/20":"bg-bambu-dark-secondary border-bambu-dark-tertiary":"bg-bambu-dark-secondary/50",p=()=>{if(!t.enabled)return i("common.disabled");if(o==="days"){const f=t.days_until_due??0;return t.is_due?i("maintenance.overdueBy",{duration:qx(Math.abs(f),"days",i)}):t.is_warning?i("maintenance.dueIn",{duration:qx(f,"days",i)}):i("maintenance.timeLeft",{duration:qx(f,"days",i)})}else return t.is_due?i("maintenance.overdueBy",{duration:qx(Math.abs(t.hours_until_due),"hours",i)}):t.is_warning?i("maintenance.dueIn",{duration:qx(t.hours_until_due,"hours",i)}):i("maintenance.timeLeft",{duration:qx(t.hours_until_due,"hours",i)})};return r.jsx("div",{className:`rounded-xl border p-4 transition-all ${m()}`,children:r.jsxs("div",{className:"flex items-start gap-3 max-[550px]:flex-wrap",children:[r.jsxs("div",{className:`relative p-2.5 rounded-lg shrink-0 ${t.is_due?"bg-red-500/20":t.is_warning?"bg-amber-500/20":t.enabled?"bg-bambu-dark":"bg-bambu-dark/50"}`,children:[r.jsx(s,{className:`w-5 h-5 ${d()}`}),t.enabled&&(t.is_due||t.is_warning)&&r.jsx("span",{className:`absolute -top-1 -right-1 w-2.5 h-2.5 rounded-full ${t.is_due?"bg-red-500":"bg-amber-500"} animate-pulse`})]}),r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("h3",{className:`font-medium truncate ${t.enabled?"text-white":"text-bambu-gray"}`,children:t.maintenance_type_name}),o==="days"&&r.jsx("span",{title:i("maintenance.timeBasedInterval"),children:r.jsx(Cn,{className:"w-3.5 h-3.5 text-bambu-gray shrink-0"})}),(()=>{const f=t.maintenance_type_wiki_url||gst(t.maintenance_type_name,t.printer_model);return f?r.jsx("a",{href:f,target:"_blank",rel:"noopener noreferrer",className:"text-bambu-gray hover:text-bambu-green transition-colors shrink-0",title:i("maintenance.viewDocumentation"),onClick:g=>g.stopPropagation(),children:r.jsx(Tr,{className:"w-3.5 h-3.5"})}):null})()]}),r.jsx("div",{className:"mt-2 mb-1.5",children:r.jsx("div",{className:"w-full h-1.5 bg-bambu-dark rounded-full overflow-hidden",children:r.jsx("div",{className:`h-full rounded-full transition-all duration-500 ${u()}`,style:{width:`${c}%`}})})}),r.jsxs("div",{className:`text-xs flex items-center gap-1 ${d()}`,children:[t.is_due&&r.jsx(xa,{className:"w-3 h-3"}),t.is_warning&&!t.is_due&&r.jsx(ar,{className:"w-3 h-3"}),!t.is_due&&!t.is_warning&&t.enabled&&r.jsx(_r,{className:"w-3 h-3"}),p()]})]}),r.jsxs("div",{className:"flex items-center gap-2 shrink-0 max-[550px]:w-full max-[550px]:justify-end max-[550px]:mt-1",children:[r.jsx("span",{title:n("maintenance:update")?void 0:i("maintenance.noPermissionUpdate"),children:r.jsx(Fa,{checked:t.enabled,onChange:f=>a(t.id,f),disabled:!n("maintenance:update")})}),r.jsxs(Le,{size:"sm",variant:t.is_due?"primary":"secondary",onClick:()=>e(t.id),disabled:!t.enabled||!n("maintenance:update"),title:n("maintenance:update")?void 0:i("maintenance.noPermissionPerform"),className:"!px-3",children:[r.jsx(bs,{className:"w-3.5 h-3.5"}),i("common.reset")]})]})]})})}function xst({overview:t,onPerform:e,onToggle:a,onSetHours:n,hasPermission:i,t:s}){const[o,l]=y.useState(!1),[c,d]=y.useState(!1),[u,m]=y.useState(t.total_print_hours.toFixed(1)),p=[...t.maintenance_items].sort((v,b)=>v.is_due&&!b.is_due?-1:!v.is_due&&b.is_due?1:v.is_warning&&!b.is_warning?-1:!v.is_warning&&b.is_warning?1:v.maintenance_type_id-b.maintenance_type_id),f=p.find(v=>v.enabled&&(v.is_due||v.is_warning)),g=()=>{const v=parseFloat(u);!isNaN(v)&&v>=0&&(n(t.printer_id,v),d(!1))};return r.jsxs(Tt,{className:"overflow-hidden",children:[r.jsxs("div",{className:"p-5",children:[r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("div",{className:"flex items-center gap-4",children:[r.jsx("h2",{className:"text-xl font-semibold text-white",children:t.printer_name}),r.jsxs("div",{className:"flex items-center gap-2",children:[t.due_count>0&&r.jsxs("span",{className:"px-2.5 py-1 bg-red-500/20 text-red-400 text-xs font-medium rounded-full flex items-center gap-1.5",children:[r.jsx(xa,{className:"w-3 h-3"}),s("maintenance.overdueCount",{count:t.due_count})]}),t.warning_count>0&&r.jsxs("span",{className:"px-2.5 py-1 bg-amber-500/20 text-amber-400 text-xs font-medium rounded-full flex items-center gap-1.5",children:[r.jsx(ar,{className:"w-3 h-3"}),s("maintenance.dueSoonCount",{count:t.warning_count})]}),t.due_count===0&&t.warning_count===0&&r.jsxs("span",{className:"px-2.5 py-1 bg-bambu-green/20 text-bambu-green text-xs font-medium rounded-full flex items-center gap-1.5",children:[r.jsx(_r,{className:"w-3 h-3"}),s("maintenance.allGood")]})]})]}),r.jsxs("button",{onClick:()=>l(!o),className:"flex items-center gap-1.5 px-3 py-1.5 text-sm text-bambu-gray hover:text-white hover:bg-bambu-dark rounded-lg transition-colors",children:[o?r.jsx(el,{className:"w-4 h-4"}):r.jsx(za,{className:"w-4 h-4"}),s(o?"common.collapse":"common.expand")]})]}),r.jsxs("div",{className:"flex items-center gap-6 mt-4",children:[r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("div",{className:"p-2 bg-bambu-dark/50 rounded-lg",children:r.jsx(ru,{className:"w-4 h-4 text-bambu-gray"})}),c?r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("input",{type:"number",value:u,onChange:v=>m(v.target.value),onKeyDown:v=>{v.key==="Enter"&&g(),v.key==="Escape"&&d(!1)},className:"w-24 px-2 py-1 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-sm",min:"0",step:"1",autoFocus:!0}),r.jsx("span",{className:"text-xs text-bambu-gray",children:s("common.hours")}),r.jsx(Le,{size:"sm",onClick:g,children:s("common.save")}),r.jsx(Le,{size:"sm",variant:"secondary",onClick:()=>d(!1),children:s("common.cancel")})]}):r.jsxs("button",{onClick:()=>{i("maintenance:update")&&(m(Math.round(t.total_print_hours).toString()),d(!0))},className:`group ${i("maintenance:update")?"":"cursor-not-allowed opacity-60"}`,title:i("maintenance:update")?void 0:s("maintenance.noPermissionEditHours"),children:[r.jsxs("div",{className:`text-sm font-medium text-white ${i("maintenance:update")?"group-hover:text-bambu-green":""} transition-colors flex items-center gap-1`,children:[Math.round(t.total_print_hours)," ",s("common.hours"),r.jsx(Bg,{className:`w-3 h-3 text-bambu-gray ${i("maintenance:update")?"group-hover:text-bambu-green":""}`})]}),r.jsx("div",{className:"text-xs text-bambu-gray",children:s("maintenance.totalPrintTime")})]})]}),r.jsx("div",{className:"w-px h-10 bg-bambu-dark-tertiary"}),f&&r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("div",{className:`p-2 rounded-lg ${f.is_due?"bg-red-500/20":"bg-amber-500/20"}`,children:(()=>{const v=Dw(f.maintenance_type_icon);return r.jsx(v,{className:`w-4 h-4 ${f.is_due?"text-red-400":"text-amber-400"}`})})()}),r.jsxs("div",{children:[r.jsx("div",{className:`text-sm font-medium ${f.is_due?"text-red-400":"text-amber-400"}`,children:f.maintenance_type_name}),r.jsx("div",{className:`text-xs ${f.is_due?"text-red-400/70":"text-amber-400/70"}`,children:f.is_due?s("common.overdue"):s("maintenance.dueSoon")})]})]})]})]}),o&&r.jsx(jt,{className:"pt-0 border-t border-bambu-dark-tertiary",children:r.jsx("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-3 pt-4",children:p.map(v=>r.jsx(bst,{item:v,onPerform:e,onToggle:a,hasPermission:i,t:s},v.id))})})]})}function yst({overview:t,types:e,onUpdateInterval:a,onAddType:n,onUpdateType:i,onDeleteType:s,onRestoreDefaults:o,isRestoringDefaults:l,onAssignType:c,onRemoveItem:d,hasPermission:u,t:m}){const[p,f]=y.useState(null),[g,v]=y.useState(""),[b,x]=y.useState("hours"),[S,k]=y.useState(!1),[P,N]=y.useState(""),[T,j]=y.useState("100"),[D,C]=y.useState("hours"),[E,R]=y.useState("Wrench"),[I,O]=y.useState(""),[z,X]=y.useState(new Set),[ae,Y]=y.useState(null),[ce,de]=y.useState(null),oe=y.useMemo(()=>t?t.map(V=>({id:V.printer_id,name:V.printer_name})):[],[t]),K=V=>t?t.filter(L=>L.maintenance_items.some(te=>te.maintenance_type_id===V)).map(L=>({printerId:L.printer_id,printerName:L.printer_name,itemId:L.maintenance_items.find(te=>te.maintenance_type_id===V)?.id})):[],ie=V=>{if(!t)return[];const L=new Set(K(V).map(te=>te.printerId));return oe.filter(te=>!L.has(te.id))},[ue,he]=y.useState(null),[ge,q]=y.useState(""),[Q,A]=y.useState(""),[F,B]=y.useState("hours"),[W,H]=y.useState("Wrench"),[le,U]=y.useState(""),G=V=>{he(V),q(V.name),A(V.default_interval_hours.toString()),B(V.interval_type||"hours"),H(V.icon||"Wrench"),U(V.wiki_url||"")},Z=()=>{ue&&ge.trim()&&parseFloat(Q)>0&&(i(ue.id,{name:ge.trim(),default_interval_hours:parseFloat(Q),interval_type:F,icon:W,wiki_url:le.trim()||null}),he(null))},J=(V,L,te)=>{const be=parseFloat(g);if(!isNaN(be)&&be>0){const xe=Math.abs(be-L)<.01?null:be;a(V,{custom_interval_hours:xe,custom_interval_type:b!==te?b:null})}f(null)},re=V=>{V.preventDefault(),P.trim()&&parseFloat(T)>0&&z.size>0&&(n({name:P.trim(),default_interval_hours:parseFloat(T),interval_type:D,icon:E,wiki_url:I.trim()||null},Array.from(z)),N(""),j("100"),C("hours"),O(""),X(new Set),k(!1))},se=V=>{X(L=>{const te=new Set(L);return te.has(V)?te.delete(V):te.add(V),te})},fe=t?.map(V=>({printerId:V.printer_id,printerName:V.printer_name,items:V.maintenance_items.sort((L,te)=>L.maintenance_type_id-te.maintenance_type_id)})).sort((V,L)=>V.printerName.localeCompare(L.printerName))||[],me=e.filter(V=>V.is_system),pe=e.filter(V=>!V.is_system);return r.jsxs("div",{className:"space-y-8",children:[r.jsxs("div",{children:[r.jsxs("div",{className:"flex items-center justify-between mb-4",children:[r.jsxs("div",{children:[r.jsx("h2",{className:"text-lg font-semibold text-white",children:m("maintenance.maintenanceTypes")}),r.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:m("maintenance.maintenanceTypesDescription")})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(Le,{variant:"secondary",onClick:o,disabled:!u("maintenance:delete")||l,title:u("maintenance:delete")?void 0:m("maintenance.noPermissionDeleteTypes"),children:m("maintenance.restoreDefaults")}),r.jsxs(Le,{onClick:()=>k(!S),disabled:!u("maintenance:create"),title:u("maintenance:create")?void 0:m("maintenance.noPermissionEditTypes"),children:[r.jsx(or,{className:"w-4 h-4"}),m("maintenance.addCustomType")]})]})]}),S&&r.jsx(Tt,{className:"mb-6",children:r.jsx(jt,{className:"py-4",children:r.jsxs("form",{onSubmit:re,children:[r.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4",children:[r.jsxs("div",{className:"lg:col-span-2",children:[r.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:m("common.name")}),r.jsx("input",{type:"text",value:P,onChange:V=>N(V.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",placeholder:m("maintenance.exampleName"),autoFocus:!0})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:m("maintenance.intervalType")}),r.jsxs("select",{value:D,onChange:V=>{C(V.target.value),V.target.value==="days"?j("30"):j("100")},className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",children:[r.jsx("option",{value:"hours",children:m("maintenance.printHours")}),r.jsx("option",{value:"days",children:m("maintenance.calendarDays")})]})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:m("maintenance.intervalValue",{type:D==="days"?m("maintenance.calendarDays").toLowerCase():m("common.hours")})}),r.jsx("input",{type:"number",value:T,onChange:V=>j(V.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",min:"1"})]})]}),r.jsx("div",{className:"mt-4 flex items-end justify-between",children:r.jsxs("div",{children:[r.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:m("maintenance.icon")}),r.jsx("div",{className:"flex gap-1",children:Object.keys(nw).map(V=>{const L=nw[V];return r.jsx("button",{type:"button",onClick:()=>R(V),className:`p-2 rounded-lg transition-colors ${E===V?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary"}`,children:r.jsx(L,{className:"w-4 h-4"})},V)})})]})}),r.jsxs("div",{className:"mt-4",children:[r.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:m("maintenance.documentationLink")}),r.jsx("input",{type:"url",value:I,onChange:V=>O(V.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",placeholder:"https://wiki.bambulab.com/..."})]}),r.jsxs("div",{className:"mt-4",children:[r.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:m("maintenance.assignToPrinters")}),r.jsx("div",{className:"flex flex-wrap gap-2",children:oe.map(V=>r.jsx("button",{type:"button",onClick:()=>se(V.id),className:`px-3 py-1.5 rounded-lg text-sm transition-colors ${z.has(V.id)?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary"}`,children:V.name},V.id))}),z.size===0&&r.jsx("p",{className:"text-xs text-orange-400 mt-1",children:m("maintenance.selectAtLeastOnePrinter")})]}),r.jsxs("div",{className:"mt-4 flex justify-end gap-2",children:[r.jsx(Le,{type:"button",variant:"secondary",onClick:()=>{k(!1),X(new Set)},children:m("common.cancel")}),r.jsx(Le,{type:"submit",disabled:!P.trim()||z.size===0,children:m("maintenance.addType")})]})]})})}),r.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3",children:[me.map(V=>{const L=Dw(V.icon),te=V.interval_type||"hours";return r.jsx("div",{className:"bg-bambu-dark-secondary rounded-xl p-4 border border-bambu-dark-tertiary",children:r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("div",{className:"p-2.5 bg-bambu-dark rounded-lg",children:r.jsx(L,{className:"w-5 h-5 text-bambu-gray"})}),r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsx("div",{className:"text-sm font-medium text-white truncate",children:V.name}),r.jsxs("div",{className:"text-xs text-bambu-gray mt-0.5 flex items-center gap-1",children:[te==="days"?r.jsx(Cn,{className:"w-3 h-3"}):r.jsx(ru,{className:"w-3 h-3"}),DL(V.default_interval_hours,te,m)]})]}),r.jsx("button",{onClick:()=>{u("maintenance:delete")&&de(V)},disabled:!u("maintenance:delete"),title:u("maintenance:delete")?void 0:m("maintenance.noPermissionDeleteTypes"),className:`p-2 rounded-lg hover:bg-bambu-dark text-bambu-gray hover:text-red-400 transition-colors ${u("maintenance:delete")?"":"opacity-50 cursor-not-allowed"}`,children:r.jsx(na,{className:"w-4 h-4"})})]})},V.id)}),pe.map(V=>{const L=Dw(V.icon),te=V.interval_type||"hours";if(ue?.id===V.id)return r.jsx("div",{className:"bg-bambu-dark-secondary rounded-xl p-4 border border-bambu-green",children:r.jsxs("div",{className:"space-y-3",children:[r.jsx("input",{type:"text",value:ge,onChange:je=>q(je.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",placeholder:m("common.name"),autoFocus:!0}),r.jsxs("div",{className:"flex gap-2",children:[r.jsxs("select",{value:F,onChange:je=>B(je.target.value),className:"flex-1 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",children:[r.jsx("option",{value:"hours",children:m("maintenance.printHours")}),r.jsx("option",{value:"days",children:m("maintenance.calendarDays")})]}),r.jsx("input",{type:"number",value:Q,onChange:je=>A(je.target.value),className:"w-24 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",min:"1"})]}),r.jsx("div",{className:"flex flex-wrap gap-1",children:Object.keys(nw).map(je=>{const Te=nw[je];return r.jsx("button",{type:"button",onClick:()=>H(je),className:`p-1.5 rounded transition-colors ${W===je?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:r.jsx(Te,{className:"w-3.5 h-3.5"})},je)})}),r.jsx("input",{type:"url",value:le,onChange:je=>U(je.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",placeholder:m("maintenance.documentationLink")}),r.jsxs("div",{className:"flex gap-2",children:[r.jsx(Le,{size:"sm",onClick:Z,disabled:!ge.trim(),children:m("common.save")}),r.jsx(Le,{size:"sm",variant:"secondary",onClick:()=>he(null),children:m("common.cancel")})]})]})},V.id);const xe=K(V.id),ve=ie(V.id),De=ae===V.id;return r.jsxs("div",{className:"bg-bambu-dark-secondary rounded-xl p-4 border border-bambu-green/30",children:[r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("div",{className:"p-2.5 bg-bambu-green/20 rounded-lg",children:r.jsx(L,{className:"w-5 h-5 text-bambu-green"})}),r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("span",{className:"text-sm font-medium text-white truncate",children:V.name}),r.jsx("span",{className:"px-1.5 py-0.5 bg-bambu-green/20 text-bambu-green text-[10px] font-medium rounded",children:m("maintenance.custom")})]}),r.jsxs("div",{className:"text-xs text-bambu-gray mt-0.5 flex items-center gap-1",children:[te==="days"?r.jsx(Cn,{className:"w-3 h-3"}):r.jsx(ru,{className:"w-3 h-3"}),DL(V.default_interval_hours,te,m)]})]}),r.jsxs("button",{onClick:()=>Y(De?null:V.id),className:`px-2 py-1 rounded-lg border transition-colors flex items-center gap-1 ${xe.length>0?"border-bambu-green/50 bg-bambu-green/10 text-bambu-green hover:bg-bambu-green/20":"border-orange-400/50 bg-orange-400/10 text-orange-400 hover:bg-orange-400/20"}`,title:m("maintenance.printersAssignedClick",{count:xe.length}),children:[r.jsx(xr,{className:"w-3 h-3"}),r.jsx("span",{className:"text-xs font-medium",children:xe.length}),r.jsx(za,{className:`w-3 h-3 transition-transform ${De?"rotate-180":""}`})]}),r.jsx("button",{onClick:()=>G(V),disabled:!u("maintenance:update"),title:u("maintenance:update")?void 0:m("maintenance.noPermissionEditTypes"),className:`p-2 rounded-lg hover:bg-bambu-dark text-bambu-gray hover:text-white transition-colors ${u("maintenance:update")?"":"opacity-50 cursor-not-allowed"}`,children:r.jsx(Bg,{className:"w-4 h-4"})}),r.jsx("button",{onClick:()=>{confirm(m("maintenance.deleteTypeConfirm",{name:V.name}))&&s(V.id)},disabled:!u("maintenance:delete"),title:u("maintenance:delete")?void 0:m("maintenance.noPermissionDeleteTypes"),className:`p-2 rounded-lg hover:bg-bambu-dark text-bambu-gray hover:text-red-400 transition-colors ${u("maintenance:delete")?"":"opacity-50 cursor-not-allowed"}`,children:r.jsx(na,{className:"w-4 h-4"})})]}),De&&r.jsxs("div",{className:"mt-3 pt-3 border-t border-bambu-dark-tertiary",children:[r.jsx("p",{className:"text-xs text-bambu-gray mb-2",children:m("maintenance.assignedToPrinters")}),xe.length===0?r.jsx("p",{className:"text-xs text-orange-400",children:m("maintenance.noPrintersAssigned")}):r.jsx("div",{className:"flex flex-wrap gap-1 mb-2",children:xe.map(je=>r.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-1 bg-bambu-dark rounded text-xs text-white",children:[je.printerName,r.jsx("button",{onClick:()=>je.itemId&&d(je.itemId),disabled:!u("maintenance:delete"),title:u("maintenance:delete")?m("maintenance.removeFromPrinter"):m("maintenance.noPermissionRemovePrinter"),className:`ml-1 ${u("maintenance:delete")?"hover:text-red-400":"opacity-50 cursor-not-allowed"}`,children:"×"})]},je.printerId))}),ve.length>0&&r.jsxs("div",{className:"flex flex-wrap gap-1",children:[r.jsx("span",{className:"text-xs text-bambu-gray mr-1",children:m("maintenance.addPrinterShort")}),ve.map(je=>r.jsxs("button",{onClick:()=>c(je.id,V.id),disabled:!u("maintenance:create"),title:u("maintenance:create")?void 0:m("maintenance.noPermissionAssignPrinter"),className:`px-2 py-1 bg-bambu-dark rounded text-xs transition-colors ${u("maintenance:create")?"hover:bg-bambu-green/20 text-bambu-gray hover:text-bambu-green":"opacity-50 cursor-not-allowed text-bambu-gray"}`,children:["+ ",je.name]},je.id))]})]})]},V.id)})]})]}),fe.length>0&&r.jsxs("div",{children:[r.jsxs("div",{className:"mb-4",children:[r.jsx("h2",{className:"text-lg font-semibold text-white",children:m("maintenance.intervalOverrides")}),r.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:m("maintenance.intervalOverridesDescription")})]}),r.jsx("div",{className:"space-y-4",children:fe.map(V=>r.jsx(Tt,{children:r.jsxs(jt,{className:"py-4",children:[r.jsx("h3",{className:"text-sm font-medium text-white mb-3",children:V.printerName}),r.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-2",children:V.items.map(L=>{const te=Dw(L.maintenance_type_icon),be=e.find(Te=>Te.id===L.maintenance_type_id),xe=be?.default_interval_hours||L.interval_hours,ve=be?.interval_type||"hours",De=L.interval_type||"hours",je=p===L.id;return r.jsxs("div",{className:"flex items-center gap-2 p-2.5 bg-bambu-dark rounded-lg",children:[r.jsx(te,{className:"w-4 h-4 text-bambu-gray shrink-0"}),r.jsx("span",{className:"text-xs text-bambu-gray flex-1 truncate",children:L.maintenance_type_name}),je?r.jsxs("div",{className:"flex items-center gap-1",children:[b==="days"?r.jsx(Cn,{className:"w-3.5 h-3.5 text-bambu-gray shrink-0"}):r.jsx(ru,{className:"w-3.5 h-3.5 text-bambu-gray shrink-0"}),r.jsxs("select",{value:b,onChange:Te=>x(Te.target.value),className:"px-1.5 py-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-xs",children:[r.jsx("option",{value:"hours",children:m("maintenance.printHours")}),r.jsx("option",{value:"days",children:m("maintenance.calendarDays")})]}),r.jsx("input",{type:"number",value:g,onChange:Te=>v(Te.target.value),onKeyDown:Te=>{Te.key==="Enter"&&J(L.id,xe,ve),Te.key==="Escape"&&f(null)},className:"w-16 px-2 py-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-xs",min:"1"}),r.jsx(Le,{size:"sm",onClick:()=>J(L.id,xe,ve),children:"OK"})]}):r.jsxs("button",{onClick:()=>{u("maintenance:update")&&(f(L.id),v(L.interval_hours.toString()),x(De))},disabled:!u("maintenance:update"),title:u("maintenance:update")?void 0:m("maintenance.noPermissionEditIntervals"),className:`px-2 py-1 bg-bambu-dark-tertiary border border-bambu-dark-tertiary rounded text-xs font-medium text-white transition-colors flex items-center gap-1 ${u("maintenance:update")?"hover:bg-bambu-dark-secondary hover:border-bambu-green":"opacity-50 cursor-not-allowed"}`,children:[De==="days"?r.jsx(Cn,{className:"w-3 h-3"}):r.jsx(ru,{className:"w-3 h-3"}),DL(L.interval_hours,De,m),r.jsx(Bg,{className:"w-3 h-3 text-bambu-gray"})]})]},L.id)})})]})},V.printerId))})]}),fe.length===0&&r.jsx(Tt,{children:r.jsxs(jt,{className:"text-center py-12",children:[r.jsx(ar,{className:"w-12 h-12 mx-auto mb-4 text-bambu-gray/30"}),r.jsx("p",{className:"text-bambu-gray",children:m("common.noPrinters")}),r.jsx("p",{className:"text-sm text-bambu-gray/70 mt-1",children:m("maintenance.intervalOverridesDescription")})]})}),ce&&r.jsx(ka,{title:m("maintenance.deleteSystemTypeTitle"),message:m("maintenance.deleteSystemTypeMessage",{name:ce.name}),confirmText:m("common.delete"),cancelText:m("common.cancel"),variant:"danger",cancelVariant:"primary",cardClassName:"bg-red-950/70 border border-red-800/70",onConfirm:()=>{s(ce.id),de(null)},onCancel:()=>de(null)})]})}function vst(){const{t}=wt(),e=ia(),{showToast:a}=da(),{hasPermission:n}=lr(),[i,s]=y.useState("status"),{data:o,isLoading:l}=$e({queryKey:["maintenanceOverview"],queryFn:ne.getMaintenanceOverview}),{data:c}=$e({queryKey:["maintenanceTypes"],queryFn:ne.getMaintenanceTypes}),d=rt({mutationFn:({id:T,notes:j})=>ne.performMaintenance(T,j),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]}),e.invalidateQueries({queryKey:["maintenanceSummary"]}),a(t("maintenance.maintenanceComplete"))},onError:T=>{a(T.message,"error")}}),u=rt({mutationFn:({id:T,data:j})=>ne.updateMaintenanceItem(T,j),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]})},onError:T=>{a(T.message,"error")}}),m=rt({mutationFn:({id:T,data:j})=>ne.updateMaintenanceType(T,j),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceTypes"]}),e.invalidateQueries({queryKey:["maintenanceOverview"]}),a(t("maintenance.typeUpdated"))},onError:T=>{a(T.message,"error")}}),p=rt({mutationFn:ne.deleteMaintenanceType,onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceTypes"]}),e.invalidateQueries({queryKey:["maintenanceOverview"]}),a(t("maintenance.typeDeleted"))},onError:T=>{a(T.message,"error")}}),f=rt({mutationFn:ne.restoreDefaultMaintenanceTypes,onSuccess:T=>{e.invalidateQueries({queryKey:["maintenanceTypes"]}),e.invalidateQueries({queryKey:["maintenanceOverview"]}),a(t("maintenance.defaultsRestored",{count:T.restored}))},onError:T=>{a(T.message,"error")}}),g=rt({mutationFn:({printerId:T,hours:j})=>ne.setPrinterHours(T,j),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]}),e.invalidateQueries({queryKey:["maintenanceSummary"]}),a(t("maintenance.printHoursUpdated"))},onError:T=>{a(T.message,"error")}}),v=rt({mutationFn:({printerId:T,typeId:j})=>ne.assignMaintenanceType(T,j),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]}),a(t("maintenance.printerAssigned"))},onError:T=>{a(T.message,"error")}}),b=rt({mutationFn:ne.removeMaintenanceItem,onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]}),a(t("maintenance.printerRemoved"))},onError:T=>{a(T.message,"error")}}),x=T=>{d.mutate({id:T})},S=(T,j)=>{u.mutate({id:T,data:{enabled:j}})},k=(T,j)=>{g.mutate({printerId:T,hours:j})};if(l)return r.jsx("div",{className:"p-4 md:p-8 flex justify-center",children:r.jsx(lt,{className:"w-8 h-8 text-bambu-green animate-spin"})});const P=o?.reduce((T,j)=>T+j.due_count,0)||0,N=o?.reduce((T,j)=>T+j.warning_count,0)||0;return r.jsxs("div",{className:"p-4 md:p-8",children:[r.jsxs("div",{className:"mb-6",children:[r.jsxs("h1",{className:"text-2xl font-bold text-white flex items-center gap-3",children:[r.jsx(Jm,{className:"w-7 h-7 text-bambu-green"}),t("maintenance.title")]}),r.jsx("p",{className:"text-bambu-gray mt-1",children:i==="status"?r.jsxs(r.Fragment,{children:[P>0&&r.jsx("span",{className:"text-red-400",children:t("maintenance.dueCount",{count:P})}),P>0&&N>0&&" · ",N>0&&r.jsx("span",{className:"text-amber-400",children:t("maintenance.warningCount",{count:N})}),P===0&&N===0&&r.jsx("span",{className:"text-bambu-green",children:t("maintenance.allOk")})]}):t("maintenance.configureSettings")})]}),r.jsxs("div",{className:"flex gap-1 mb-6 border-b border-bambu-dark-tertiary",children:[r.jsx("button",{onClick:()=>s("status"),className:`px-4 py-2 text-sm font-medium border-b-2 -mb-px transition-colors ${i==="status"?"text-bambu-green border-bambu-green":"text-bambu-gray border-transparent hover:text-white"}`,children:t("maintenance.statusTab")}),r.jsx("button",{onClick:()=>s("settings"),className:`px-4 py-2 text-sm font-medium border-b-2 -mb-px transition-colors ${i==="settings"?"text-bambu-green border-bambu-green":"text-bambu-gray border-transparent hover:text-white"}`,children:t("maintenance.settingsTab")})]}),i==="status"?r.jsx("div",{className:"space-y-6",children:o&&o.length>0?[...o].sort((T,j)=>{const D=T.due_count*10+T.warning_count,C=j.due_count*10+j.warning_count;return D!==C?C-D:T.printer_name.localeCompare(j.printer_name)}).map(T=>r.jsx(xst,{overview:T,onPerform:x,onToggle:S,onSetHours:k,hasPermission:n,t},T.printer_id)):r.jsx(Tt,{children:r.jsxs(jt,{className:"text-center py-16",children:[r.jsx(Jm,{className:"w-16 h-16 mx-auto mb-4 text-bambu-gray/30"}),r.jsx("p",{className:"text-lg font-medium text-white mb-2",children:t("common.noPrinters")}),r.jsx("p",{className:"text-bambu-gray",children:t("maintenance.configureSettings")})]})})}):r.jsx(yst,{overview:o,types:c||[],onUpdateInterval:(T,j)=>u.mutate({id:T,data:j}),onAddType:async(T,j)=>{const D=await ne.createMaintenanceType(T);for(const C of j)await ne.assignMaintenanceType(C,D.id);e.invalidateQueries({queryKey:["maintenanceTypes"]}),e.invalidateQueries({queryKey:["maintenanceOverview"]}),a(t("maintenance.typeUpdated"))},onUpdateType:(T,j)=>m.mutate({id:T,data:j}),onDeleteType:T=>p.mutate(T),onRestoreDefaults:()=>f.mutate(),isRestoringDefaults:f.isPending,onAssignType:(T,j)=>v.mutate({printerId:T,typeId:j}),onRemoveItem:T=>b.mutate(T),hasPermission:n,t})]})}const qX=["#ef4444","#f97316","#eab308","#22c55e","#06b6d4","#3b82f6","#8b5cf6","#ec4899","#6b7280"];function Ade({project:t,onClose:e,onSave:a,isLoading:n,currencySymbol:i,t:s}){const[o,l]=y.useState(t?.name||""),[c,d]=y.useState(t?.description||""),[u,m]=y.useState(t?.color||qX[0]),[p,f]=y.useState(t?.target_count?.toString()||""),[g,v]=y.useState(t?.target_parts_count?.toString()||""),[b,x]=y.useState(t?.status||"active"),[S,k]=y.useState(t?.tags||""),[P,N]=y.useState(t?.due_date?.split("T")[0]||""),[T,j]=y.useState(t?.priority||"normal"),[D,C]=y.useState(t?.budget?.toString()||""),[E,R]=y.useState(t?.url||""),[I,O]=y.useState(null),z=ia(),[X,ae]=y.useState(t?.cover_image_filename||null),Y=y.useRef(null),[ce,de]=y.useState(!1),[oe,K]=y.useState(0),ie=async ge=>{const q=ge.target.files?.[0];if(!(!q||!t)){de(!0);try{const Q=await ne.uploadProjectCoverImage(t.id,q);ae(Q.filename),K(A=>A+1),z.invalidateQueries({queryKey:["projects"]})}catch{}finally{de(!1),Y.current&&(Y.current.value="")}}},ue=async()=>{if(t){de(!0);try{await ne.deleteProjectCoverImage(t.id),ae(null),K(ge=>ge+1),z.invalidateQueries({queryKey:["projects"]})}finally{de(!1)}}},he=ge=>{ge.preventDefault();const q=E.trim();if(q&&!/^https?:\/\//i.test(q)){O(s("projects.urlInvalid"));return}O(null),a({name:o.trim(),description:c.trim()||void 0,color:u,target_count:p?parseInt(p,10):void 0,target_parts_count:g?parseInt(g,10):void 0,tags:S.trim()||void 0,due_date:P||void 0,priority:T,budget:D.trim()?parseFloat(D):null,url:t?q||null:q||void 0,...t&&{status:b}})};return r.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:r.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-md border border-bambu-dark-tertiary flex flex-col max-h-[calc(100vh-2rem)]",children:[r.jsx("div",{className:"p-4 border-b border-bambu-dark-tertiary flex-shrink-0",children:r.jsx("h2",{className:"text-lg font-semibold text-white",children:s(t?"projects.editProject":"projects.newProject")})}),r.jsxs("form",{onSubmit:he,className:"flex flex-col flex-1 min-h-0",children:[r.jsxs("div",{className:"p-4 space-y-4 overflow-y-auto flex-1",children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("common.name")}),r.jsx("input",{type:"text",value:o,onChange:ge=>l(ge.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:s("projects.namePlaceholder"),required:!0})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("common.description")}),r.jsx("textarea",{value:c,onChange:ge=>d(ge.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green resize-none",placeholder:s("projects.descriptionPlaceholder"),rows:2})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("projects.urlLabel")}),r.jsx("input",{type:"url",value:E,onChange:ge=>{R(ge.target.value),I&&O(null)},className:`w-full bg-bambu-dark border rounded px-3 py-2 text-white placeholder-bambu-gray focus:outline-none ${I?"border-red-500 focus:border-red-500":"border-bambu-dark-tertiary focus:border-bambu-green"}`,placeholder:s("projects.urlPlaceholder"),maxLength:2048}),I&&r.jsx("p",{className:"text-xs text-red-400 mt-1",children:I})]}),t&&r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("projects.coverImageLabel")}),r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("div",{className:"w-20 h-20 rounded bg-bambu-dark border border-bambu-dark-tertiary overflow-hidden flex items-center justify-center flex-shrink-0",children:X?r.jsx("img",{src:`${ne.getProjectCoverImageUrl(t.id)}?v=${oe}`,alt:s("projects.coverImageAlt"),className:"w-full h-full object-cover"}):r.jsx(gu,{className:"w-6 h-6 text-bambu-gray"})}),r.jsxs("div",{className:"flex flex-col gap-2",children:[r.jsx("input",{ref:Y,type:"file",accept:"image/jpeg,image/png,image/gif,image/webp",onChange:ie,className:"hidden"}),r.jsxs(Le,{type:"button",variant:"secondary",onClick:()=>Y.current?.click(),disabled:ce,children:[ce?r.jsx(lt,{className:"w-4 h-4 animate-spin"}):r.jsx(Sn,{className:"w-4 h-4 mr-1"}),s(X?"projects.coverImageReplace":"projects.coverImageUpload")]}),X&&r.jsxs(Le,{type:"button",variant:"secondary",onClick:ue,disabled:ce,children:[r.jsx(Ht,{className:"w-4 h-4 mr-1"}),s("projects.coverImageRemove")]})]})]})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("projects.color")}),r.jsx("div",{className:"flex gap-2 flex-wrap",children:qX.map(ge=>r.jsx("button",{type:"button",onClick:()=>m(ge),className:`w-8 h-8 rounded-full transition-transform ${u===ge?"ring-2 ring-white ring-offset-2 ring-offset-bambu-dark-secondary scale-110":""}`,style:{backgroundColor:ge}},ge))})]}),r.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("projects.targetPlates")}),r.jsx("input",{type:"number",value:p,onChange:ge=>f(ge.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:s("projects.targetPlatesPlaceholder"),min:"1"}),r.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:s("projects.targetPlatesHelp")})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("projects.targetParts")}),r.jsx("input",{type:"number",value:g,onChange:ge=>v(ge.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:s("projects.targetPartsPlaceholder"),min:"1"}),r.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:s("projects.targetPartsHelp")})]})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("projects.tagsLabel")}),r.jsx("input",{type:"text",value:S,onChange:ge=>k(ge.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:s("projects.tagsPlaceholder")})]}),r.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("projects.dueDate")}),r.jsx("input",{type:"date",value:P,onChange:ge=>N(ge.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white focus:outline-none focus:border-bambu-green"})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("projects.priority")}),r.jsxs("select",{value:T,onChange:ge=>j(ge.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white focus:outline-none focus:border-bambu-green",children:[r.jsx("option",{value:"low",children:s("projects.priorityLow")}),r.jsx("option",{value:"normal",children:s("projects.priorityNormal")}),r.jsx("option",{value:"high",children:s("projects.priorityHigh")}),r.jsx("option",{value:"urgent",children:s("projects.priorityUrgent")})]})]})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("projectDetail.cost.budget")}),r.jsxs("div",{className:"relative",children:[r.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-bambu-gray pointer-events-none",children:i}),r.jsx("input",{type:"number",step:"0.01",min:"0",value:D,onChange:ge=>C(ge.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded pl-8 pr-3 py-2 text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:"0.00"})]})]}),t&&r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("common.status")}),r.jsxs("select",{value:b,onChange:ge=>x(ge.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white focus:outline-none focus:border-bambu-green",children:[r.jsx("option",{value:"active",children:s("projects.statusActive")}),r.jsx("option",{value:"completed",children:s("projects.statusCompleted")}),r.jsx("option",{value:"archived",children:s("projects.statusArchived")})]})]})]}),r.jsxs("div",{className:"flex justify-end gap-2 p-4 border-t border-bambu-dark-tertiary flex-shrink-0",children:[r.jsx(Le,{type:"button",variant:"secondary",onClick:e,children:s("common.cancel")}),r.jsx(Le,{type:"submit",disabled:!o.trim()||n,children:n?r.jsx(lt,{className:"w-4 h-4 animate-spin"}):s(t?"common.save":"projects.create")})]})]})]})})}function wst({projectId:t,altText:e}){const a=y.useRef(null),[n,i]=y.useState(!1),[s,o]=y.useState(null),l=()=>{if(!a.current)return;const d=a.current.getBoundingClientRect(),u=384,m=8,p=window.innerWidth,f=window.innerHeight;let g=d.right+m;g+u>p-8&&(g=d.left-u-m);let v=d.top;v+u>f-8&&(v=f-u-8),v<8&&(v=8),o({left:g,top:v}),i(!0)},c=()=>i(!1);return r.jsxs("div",{ref:a,className:"relative flex-shrink-0",onMouseEnter:l,onMouseLeave:c,onClick:d=>d.stopPropagation(),children:[r.jsx("div",{className:"w-10 h-10 rounded-lg overflow-hidden bg-bambu-dark border border-bambu-dark-tertiary",children:r.jsx("img",{src:ne.getProjectCoverImageUrl(t),alt:e,className:"w-full h-full object-cover",loading:"lazy"})}),n&&s&&xc.createPortal(r.jsx("div",{className:"fixed z-[100] w-96 h-96 rounded-lg overflow-hidden border border-bambu-dark-tertiary shadow-2xl bg-bambu-dark pointer-events-none",style:{left:s.left,top:s.top},"aria-hidden":"true",children:r.jsx("img",{src:ne.getProjectCoverImageUrl(t),alt:"",className:"w-full h-full object-contain",loading:"lazy"})}),document.body)]})}function Sst({project:t,onClick:e,onEdit:a,onDelete:n,hasPermission:i,t:s}){const o=t.target_count?Math.round(t.archive_count/t.target_count*100):0,l=t.target_parts_count?Math.round(t.completed_count/t.target_parts_count*100):0,c=t.status==="completed",d=t.status==="archived",[u,m]=y.useState(!1),f=c?{icon:to,color:"text-bambu-green",bg:"bg-bambu-green/10"}:d?{icon:ro,color:"text-bambu-gray",bg:"bg-bambu-gray/10"}:t.queue_count>0?{icon:ar,color:"text-blue-400",bg:"bg-blue-400/10"}:{icon:no,color:"text-bambu-gray",bg:"bg-bambu-gray/10"};return r.jsxs("div",{className:"group relative bg-gradient-to-br from-bambu-card to-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary hover:border-bambu-green/50 hover:shadow-lg hover:shadow-bambu-green/5 transition-all duration-300 cursor-pointer overflow-hidden",onClick:e,children:[r.jsx("div",{className:"absolute top-0 left-0 w-1.5 h-full",style:{backgroundColor:t.color||"#6b7280",boxShadow:`0 0 12px ${t.color||"#6b7280"}40`}}),r.jsxs("div",{className:"p-5 pl-6",children:[r.jsxs("div",{className:"flex items-start justify-between mb-4",children:[r.jsxs("div",{className:"flex items-center gap-3 min-w-0 flex-1",children:[t.cover_image_filename?r.jsx(wst,{projectId:t.id,altText:s("projects.coverImageAlt")}):r.jsx("div",{className:`p-2 rounded-lg ${f.bg} flex-shrink-0`,children:r.jsx(f.icon,{className:`w-5 h-5 ${f.color}`})}),r.jsxs("div",{className:"min-w-0 flex-1",children:[r.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[r.jsx("h3",{className:"font-semibold text-white truncate",children:t.name}),t.url&&r.jsx("a",{href:t.url,target:"_blank",rel:"noopener noreferrer",onClick:g=>g.stopPropagation(),title:t.url,"aria-label":s("projects.openExternalUrl"),className:"inline-flex items-center justify-center w-6 h-6 rounded bg-bambu-dark border border-bambu-dark-tertiary text-bambu-green hover:bg-bambu-green/10 hover:border-bambu-green transition-colors flex-shrink-0",children:r.jsx(Tr,{className:"w-3.5 h-3.5"})}),t.target_parts_count?r.jsxs("span",{className:`text-xs px-2 py-0.5 rounded-full whitespace-nowrap font-medium ${l>=100?"bg-bambu-green/20 text-bambu-green":"bg-bambu-dark text-bambu-gray"}`,children:[t.completed_count,"/",t.target_parts_count," ",s("projects.parts")]}):t.target_count?r.jsxs("span",{className:`text-xs px-2 py-0.5 rounded-full whitespace-nowrap font-medium ${o>=100?"bg-bambu-green/20 text-bambu-green":"bg-bambu-dark text-bambu-gray"}`,children:[t.archive_count,"/",t.target_count," ",s("projects.plates")]}):t.completed_count>0?r.jsxs("span",{className:"text-xs px-2 py-0.5 rounded-full whitespace-nowrap font-medium bg-bambu-dark text-bambu-gray",children:[t.completed_count," ",s("projects.parts")]}):null,c&&r.jsx("span",{className:"text-xs bg-bambu-green/20 text-bambu-green px-2 py-0.5 rounded-full whitespace-nowrap",children:s("projects.done")}),d&&r.jsx("span",{className:"text-xs bg-bambu-gray/20 text-bambu-gray px-2 py-0.5 rounded-full whitespace-nowrap",children:s("projects.statusArchived")})]}),t.description&&r.jsx("p",{className:"text-sm text-bambu-gray/70 mt-1 line-clamp-1",children:t.description}),t.archives&&t.archives.length>0&&(()=>{const g=t.archives.map(S=>S.filament_type).filter(Boolean).flatMap(S=>S.split(",").map(k=>k.trim())).filter(Boolean),v=[...new Set(g)],b=t.archives.map(S=>S.filament_color).filter(Boolean).flatMap(S=>S.split(",").map(k=>k.trim())).filter(S=>S.startsWith("#")||/^[0-9A-Fa-f]{6}$/.test(S)),x=[...new Set(b)];return v.length===0&&x.length===0?null:r.jsxs("div",{className:"flex items-center gap-2 mt-1.5",children:[v.slice(0,3).map(S=>r.jsx("span",{className:"text-[10px] px-1.5 py-0.5 bg-bambu-dark text-bambu-gray rounded",children:S},S)),x.length>0&&r.jsxs("div",{className:"flex items-center gap-0.5",children:[x.slice(0,5).map(S=>r.jsx("div",{className:"w-3 h-3 rounded-full border border-black/20",style:{backgroundColor:S.startsWith("#")?S:`#${S}`},title:S},S)),x.length>5&&r.jsxs("span",{className:"text-[10px] text-bambu-gray ml-0.5",children:["+",x.length-5]})]})]})})()]})]}),r.jsxs("div",{className:"relative",onClick:g=>g.stopPropagation(),children:[r.jsx("button",{className:"p-1.5 rounded-lg hover:bg-bambu-dark text-bambu-gray hover:text-white transition-colors opacity-0 group-hover:opacity-100",onClick:()=>m(!u),children:r.jsx(Cm,{className:"w-4 h-4"})}),u&&r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>m(!1)}),r.jsxs("div",{className:"absolute right-0 top-8 z-20 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl py-1 min-w-[120px]",children:[r.jsxs("button",{className:`w-full px-3 py-2 text-left text-sm flex items-center gap-2 ${i("projects:update")?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{i("projects:update")&&(a(),m(!1))},disabled:!i("projects:update"),title:i("projects:update")?void 0:s("projects.noEditPermission"),children:[r.jsx(Bg,{className:"w-4 h-4"}),s("common.edit")]}),r.jsxs("button",{className:`w-full px-3 py-2 text-left text-sm flex items-center gap-2 ${i("projects:delete")?"text-red-400 hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{i("projects:delete")&&(n(),m(!1))},disabled:!i("projects:delete"),title:i("projects:delete")?void 0:s("projects.noDeletePermission"),children:[r.jsx(na,{className:"w-4 h-4"}),s("common.delete")]})]})]})]})]}),r.jsx("div",{className:"mb-4",children:t.target_count||t.target_parts_count?r.jsxs("div",{className:"space-y-3",children:[t.target_count&&r.jsxs("div",{children:[r.jsxs("div",{className:"flex items-center justify-between text-xs mb-1",children:[r.jsx("span",{className:"text-bambu-gray",children:s("projects.plates")}),r.jsxs("span",{className:o>=100?"text-bambu-green font-medium":"text-white",children:[t.archive_count," / ",t.target_count]})]}),r.jsx("div",{className:"h-2 bg-bambu-dark/80 rounded-full overflow-hidden backdrop-blur-sm",children:r.jsx("div",{className:"h-full transition-all duration-500 ease-out rounded-full relative",style:{width:`${Math.min(o,100)}%`,background:o>=100?"linear-gradient(90deg, #22c55e, #4ade80)":`linear-gradient(90deg, ${t.color||"#6b7280"}, ${t.color||"#6b7280"}cc)`,boxShadow:`0 0 8px ${o>=100?"#22c55e":t.color||"#6b7280"}60`}})})]}),t.target_parts_count&&r.jsxs("div",{children:[r.jsxs("div",{className:"flex items-center justify-between text-xs mb-1",children:[r.jsx("span",{className:"text-bambu-gray",children:s("projects.parts")}),r.jsxs("span",{className:l>=100?"text-bambu-green font-medium":"text-white",children:[t.completed_count," / ",t.target_parts_count]})]}),r.jsx("div",{className:"h-2 bg-bambu-dark/80 rounded-full overflow-hidden backdrop-blur-sm",children:r.jsx("div",{className:"h-full transition-all duration-500 ease-out rounded-full relative",style:{width:`${Math.min(l,100)}%`,background:l>=100?"linear-gradient(90deg, #22c55e, #4ade80)":`linear-gradient(90deg, ${t.color||"#6b7280"}, ${t.color||"#6b7280"}cc)`,boxShadow:`0 0 8px ${l>=100?"#22c55e":t.color||"#6b7280"}60`}})})]}),t.failed_count>0&&r.jsxs("div",{className:"text-xs text-red-400",children:[t.failed_count," ",s("projects.failed")]})]}):t.completed_count>0||t.failed_count>0?r.jsxs("div",{className:"flex items-center gap-4 text-xs",children:[t.completed_count>0&&r.jsxs("div",{className:"flex items-center gap-1.5 text-bambu-gray",children:[r.jsx(ro,{className:"w-3.5 h-3.5"}),r.jsxs("span",{children:[t.completed_count," ",s("projects.completed")]})]}),t.failed_count>0&&r.jsxs("div",{className:"flex items-center gap-1.5 text-red-400",children:[r.jsx(xa,{className:"w-3.5 h-3.5"}),r.jsxs("span",{children:[t.failed_count," ",s("projects.failed")]})]}),t.queue_count>0&&r.jsxs("div",{className:"flex items-center gap-1.5 text-blue-400",children:[r.jsx(ar,{className:"w-3.5 h-3.5"}),r.jsxs("span",{children:[t.queue_count," ",s("projects.inQueue")]})]})]}):r.jsx("div",{className:"text-xs text-bambu-gray/60 italic",children:s("projects.noPrintsYet")})}),t.archives&&t.archives.length>0&&r.jsxs("div",{className:"mb-4",children:[r.jsx("div",{className:"grid grid-cols-4 gap-1.5",children:t.archives.slice(0,4).map(g=>r.jsxs("div",{className:"relative aspect-square rounded-lg bg-bambu-dark overflow-hidden border border-bambu-dark-tertiary",title:g.print_name||"Unknown",children:[g.thumbnail_path?r.jsx("img",{src:ne.getArchiveThumbnail(g.id),alt:g.print_name||"",className:"w-full h-full object-cover"}):r.jsx("div",{className:"w-full h-full flex items-center justify-center text-bambu-gray/50",children:r.jsx(en,{className:"w-6 h-6"})}),g.status==="failed"&&r.jsx("div",{className:"absolute inset-0 bg-red-500/40 flex items-center justify-center",children:r.jsx(xa,{className:"w-4 h-4 text-white"})})]},g.id))}),t.archive_count>4&&r.jsx("p",{className:"text-xs text-bambu-gray mt-1.5 text-center",children:s("common.more",{count:t.archive_count-4})})]}),r.jsxs("div",{className:"flex items-center justify-between pt-3 border-t border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"flex items-center gap-4 text-xs text-bambu-gray",children:[r.jsxs("div",{className:"flex items-center gap-1.5",title:s("projects.printJobs"),children:[r.jsx(tn,{className:"w-3.5 h-3.5 text-blue-400"}),r.jsxs("span",{children:[t.archive_count," ",s("projects.plates")]})]}),r.jsxs("div",{className:"flex items-center gap-1.5",title:s("projects.partsPrinted"),children:[r.jsx(en,{className:"w-3.5 h-3.5 text-bambu-green"}),r.jsxs("span",{children:[t.completed_count," ",s("projects.parts")]})]}),t.failed_count>0&&r.jsxs("div",{className:"flex items-center gap-1.5 text-red-400",title:s("projects.failedParts"),children:[r.jsx(xa,{className:"w-3.5 h-3.5"}),r.jsx("span",{children:t.failed_count})]}),t.queue_count>0&&r.jsxs("div",{className:"flex items-center gap-1.5 text-yellow-400",title:s("projects.inQueue"),children:[r.jsx(c3,{className:"w-3.5 h-3.5"}),r.jsx("span",{children:t.queue_count})]})]}),r.jsx(Vn,{className:"w-4 h-4 text-bambu-gray/50 group-hover:text-bambu-gray transition-colors"})]})]})]})}function kst(){const{t}=wt(),e=Ii(),a=ia(),{showToast:n}=da(),{hasPermission:i}=lr(),[s,o]=y.useState(!1),[l,c]=y.useState(),[d,u]=y.useState("active"),[m,p]=y.useState(null),{data:f}=$e({queryKey:["settings"],queryFn:ne.getSettings}),g=Vo(f?.currency||"USD"),{data:v,isLoading:b}=$e({queryKey:["projects",d==="all"?void 0:d],queryFn:()=>ne.getProjects(d==="all"?void 0:d)}),x=rt({mutationFn:X=>ne.createProject(X),onSuccess:()=>{a.invalidateQueries({queryKey:["projects"]}),o(!1),n(t("projects.toast.created"),"success")},onError:X=>{n(X.message,"error")}}),S=rt({mutationFn:({id:X,data:ae})=>ne.updateProject(X,ae),onSuccess:()=>{a.invalidateQueries({queryKey:["projects"]}),o(!1),c(void 0),n(t("projects.toast.updated"),"success")},onError:X=>{n(X.message,"error")}}),k=rt({mutationFn:X=>ne.deleteProject(X),onSuccess:()=>{p(null),n(t("projects.toast.deleted"),"success"),setTimeout(()=>window.location.reload(),100)},onError:X=>{p(null),n(X.message,"error")}}),P=rt({mutationFn:X=>ne.importProject(X),onSuccess:()=>{a.invalidateQueries({queryKey:["projects"]}),n(t("projects.toast.imported"),"success")},onError:X=>{n(X.message,"error")}}),N=y.useRef(null),T=async()=>{try{const X=await ne.getProjects(),ae=await Promise.all(X.map(async oe=>await ne.exportProjectJson(oe.id))),Y=new Blob([JSON.stringify(ae,null,2)],{type:"application/json"}),ce=URL.createObjectURL(Y),de=document.createElement("a");de.href=ce,de.download=`bambuddy_projects_${new Date().toISOString().split("T")[0]}.json`,de.click(),URL.revokeObjectURL(ce),n(t("projects.toast.exported"),"success")}catch(X){n(X.message,"error")}},j=()=>{N.current?.click()},D=async X=>{const ae=X.target.files?.[0];if(ae){try{if(ae.name.toLowerCase().endsWith(".zip"))await ne.importProjectFile(ae),a.invalidateQueries({queryKey:["projects"]}),n(t("projects.toast.imported"),"success");else{const ce=await ae.text(),de=JSON.parse(ce),oe=Array.isArray(de)?de:[de];for(const K of oe)await P.mutateAsync(K);oe.length>1&&n(t("projects.toast.multipleImported",{count:oe.length}),"success")}}catch(Y){n(`${t("projects.toast.importFailed")}: ${Y.message}`,"error")}X.target.value=""}},C=X=>{l?S.mutate({id:l.id,data:X}):x.mutate(X)},E=X=>{c(X),o(!0)},R=X=>{e(`/projects/${X.id}`)},I=X=>{p(X)},O=()=>{m!==null&&k.mutate(m)},z=v?.reduce((X,ae)=>(X[ae.status]=(X[ae.status]||0)+1,X.all=(X.all||0)+1,X),{})||{};return r.jsxs("div",{className:"p-4 md:p-8 space-y-8",children:[r.jsx("input",{ref:N,type:"file",accept:".json,.zip",onChange:D,className:"hidden"}),r.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4",children:[r.jsxs("div",{children:[r.jsxs("h1",{className:"text-2xl font-bold text-white flex items-center gap-3",children:[r.jsx(no,{className:"w-7 h-7 text-bambu-green"}),t("projects.title")]}),r.jsx("p",{className:"text-bambu-gray mt-1",children:t("projects.subtitle")})]}),r.jsxs("div",{className:"flex gap-2",children:[r.jsxs(Le,{variant:"secondary",onClick:j,disabled:!i("projects:create"),title:i("projects:create")?t("projects.importProject"):t("projects.noImportPermission"),children:[r.jsx(Sn,{className:"w-4 h-4 mr-2"}),t("projects.import")]}),r.jsxs(Le,{variant:"secondary",onClick:T,disabled:!i("projects:read"),title:i("projects:read")?t("projects.exportAll"):t("projects.noExportPermission"),children:[r.jsx(Ur,{className:"w-4 h-4 mr-2"}),t("projects.export")]}),r.jsxs(Le,{onClick:()=>o(!0),className:"sm:w-auto w-full",disabled:!i("projects:create"),title:i("projects:create")?void 0:t("projects.noCreatePermission"),children:[r.jsx(or,{className:"w-4 h-4 mr-2"}),t("projects.newProject")]})]})]}),r.jsx("div",{className:"flex gap-1 p-1 bg-bambu-dark rounded-xl w-fit",children:[{key:"active",label:t("projects.statusActive"),icon:ar},{key:"completed",label:t("projects.statusCompleted"),icon:to},{key:"archived",label:t("projects.statusArchived"),icon:ro},{key:"all",label:t("common.all"),icon:no}].map(({key:X,label:ae,icon:Y})=>r.jsxs("button",{onClick:()=>u(X),className:`flex items-center gap-2 px-4 py-2 text-sm rounded-lg transition-all ${d===X?"bg-bambu-card text-white shadow-sm":"text-bambu-gray hover:text-white"}`,children:[r.jsx(Y,{className:"w-4 h-4"}),r.jsx("span",{children:ae}),z[X]>0&&r.jsx("span",{className:`text-xs px-1.5 py-0.5 rounded-full ${d===X?"bg-bambu-green/20 text-bambu-green":"bg-bambu-dark-tertiary"}`,children:z[X]})]},X))}),b?r.jsx("div",{className:"flex items-center justify-center py-20",children:r.jsxs("div",{className:"flex flex-col items-center gap-3",children:[r.jsx(lt,{className:"w-8 h-8 animate-spin text-bambu-green"}),r.jsx("p",{className:"text-sm text-bambu-gray",children:t("projects.loading")})]})}):v?.length===0?r.jsxs("div",{className:"flex flex-col items-center justify-center py-20 px-4",children:[r.jsx("div",{className:"p-4 bg-bambu-dark rounded-2xl mb-4",children:r.jsx(no,{className:"w-12 h-12 text-bambu-gray/50"})}),r.jsx("h3",{className:"text-lg font-medium text-white mb-2",children:d==="all"?t("projects.noProjects"):t("projects.noProjectsFiltered",{status:d})}),r.jsx("p",{className:"text-bambu-gray text-center max-w-md mb-6",children:d==="all"?t("projects.createFirst"):t("projects.noProjectsFilteredHelp",{status:d})}),d==="all"&&r.jsxs(Le,{onClick:()=>o(!0),disabled:!i("projects:create"),title:i("projects:create")?void 0:t("projects.noCreatePermission"),children:[r.jsx(or,{className:"w-4 h-4 mr-2"}),t("projects.createFirstButton")]})]}):r.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-8",children:v?.map(X=>r.jsx(Sst,{project:X,onClick:()=>R(X),onEdit:()=>E(X),onDelete:()=>I(X.id),hasPermission:i,t},X.id))}),m!==null&&r.jsx(ka,{title:t("projects.deleteProject"),message:t("projects.deleteConfirm"),confirmText:t("projects.deleteProject"),variant:"danger",onConfirm:O,onCancel:()=>p(null)}),s&&r.jsx(Ade,{project:l,onClose:()=>{o(!1),c(void 0)},onSave:C,isLoading:x.isPending||S.isPending,currencySymbol:g,t})]})}function _st(t){const e=t.toLowerCase();return e.endsWith(".gcode")||e.endsWith(".gcode.3mf")}function Cst(t){return t>=1e3?`${(t/1e3).toFixed(2)}kg`:`${Math.round(t)}g`}function Pst({status:t,t:e}){const a={active:"bg-bambu-green/20 text-bambu-green",completed:"bg-blue-500/20 text-blue-400",archived:"bg-bambu-gray/20 text-bambu-gray"},n=a[t]||a.active,i={active:e("projectDetail.status.active"),completed:e("projectDetail.status.completed"),archived:e("projectDetail.status.archived")};return r.jsx("span",{className:`px-2 py-1 rounded text-sm font-medium ${n}`,children:i[t]||t.charAt(0).toUpperCase()+t.slice(1)})}function VX({icon:t,label:e,value:a,subValue:n,hint:i,color:s="text-bambu-gray"}){return r.jsx(Tt,{children:r.jsx(jt,{className:"p-4",children:r.jsxs("div",{className:"flex items-center gap-3",title:i,children:[r.jsx("div",{className:`p-2 rounded-lg bg-bambu-dark ${s}`,children:r.jsx(t,{className:"w-5 h-5"})}),r.jsxs("div",{children:[r.jsx("p",{className:"text-sm text-bambu-gray",children:e}),r.jsx("p",{className:"text-xl font-semibold text-white",children:a}),n&&r.jsx("p",{className:"text-xs text-bambu-gray/70",children:n})]})]})})})}function Nst({archives:t,t:e}){return t.length===0?r.jsxs("div",{className:"text-center py-8 text-bambu-gray",children:[r.jsx(en,{className:"w-12 h-12 mx-auto mb-2 opacity-50"}),r.jsx("p",{children:e("projectDetail.noPrints")})]}):r.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6 gap-3",children:t.map(a=>r.jsxs(Ls,{to:`/archives?search=${encodeURIComponent(a.print_name||"")}`,className:"group relative aspect-square rounded-lg bg-bambu-dark border border-bambu-dark-tertiary overflow-hidden hover:border-bambu-green transition-colors",children:[a.thumbnail_path?r.jsx("img",{src:ne.getArchiveThumbnail(a.id),alt:a.print_name||"Print",className:"w-full h-full object-cover"}):r.jsx("div",{className:"w-full h-full flex items-center justify-center text-bambu-gray",children:r.jsx(en,{className:"w-8 h-8"})}),a.status==="failed"&&r.jsx("div",{className:"absolute inset-0 bg-red-500/30 flex items-center justify-center",children:r.jsx(Fr,{className:"w-8 h-8 text-white"})}),a.status==="completed"&&r.jsx("div",{className:"absolute top-1 right-1",children:r.jsx(fr,{className:"w-4 h-4 text-bambu-green"})}),r.jsx("div",{className:"absolute inset-x-0 bottom-0 bg-gradient-to-t from-black/80 to-transparent p-2 opacity-0 group-hover:opacity-100 transition-opacity",children:r.jsx("p",{className:"text-xs text-white truncate",children:a.print_name||"Unknown"})})]},a.id))})}function Tst({priority:t,t:e}){const a={low:{color:"bg-gray-500/20 text-gray-400",label:e("projectDetail.priority.low")},normal:{color:"bg-blue-500/20 text-blue-400",label:e("projectDetail.priority.normal")},high:{color:"bg-orange-500/20 text-orange-400",label:e("projectDetail.priority.high")},urgent:{color:"bg-red-500/20 text-red-400",label:e("projectDetail.priority.urgent")}},{color:n,label:i}=a[t]||a.normal;return r.jsxs("span",{className:`px-2 py-1 rounded text-xs font-medium flex items-center gap-1 ${n}`,children:[t==="urgent"&&r.jsx(xa,{className:"w-3 h-3"}),i]})}function FL(t,e){if(!t)return null;const a=Ga(t);if(!a)return null;const n=new Date,i=Math.ceil((a.getTime()-n.getTime())/(1e3*60*60*24));return i<0?{color:"text-red-400",label:e("projectDetail.dueDate.overdue")}:i===0?{color:"text-orange-400",label:e("projectDetail.dueDate.today")}:i<=3?{color:"text-yellow-400",label:e("projectDetail.dueDate.daysLeft",{count:i})}:{color:"text-bambu-gray",label:e("projectDetail.dueDate.daysLeft",{count:i})}}function Ast(){const{id:t}=FS(),e=Ii(),{t:a}=wt(),n=ia(),{showToast:i}=da(),{hasPermission:s}=lr(),[o,l]=y.useState(!1),[c,d]=y.useState(!1),[u,m]=y.useState(""),[p,f]=y.useState(null),[g,v]=y.useState(null),b=parseInt(t||"0",10),{data:x,isLoading:S,error:k}=$e({queryKey:["project",b],queryFn:()=>ne.getProject(b),enabled:b>0}),{data:P,isLoading:N}=$e({queryKey:["project-archives",b],queryFn:()=>ne.getProjectArchives(b),enabled:b>0}),{data:T,isLoading:j}=$e({queryKey:["project-bom",b],queryFn:()=>ne.getProjectBOM(b),enabled:b>0}),{data:D,isLoading:C}=$e({queryKey:["project-timeline",b],queryFn:()=>ne.getProjectTimeline(b,20),enabled:b>0}),{data:E}=$e({queryKey:["settings"],queryFn:ne.getSettings}),{data:R}=$e({queryKey:["project-folders",b],queryFn:()=>ne.getLibraryFoldersByProject(b),enabled:b>0}),{data:I,isLoading:O}=$e({queryKey:["project-files",b],queryFn:()=>ne.getLibraryFiles(null,!1,b),enabled:b>0}),z=y.useMemo(()=>{const Me=new Map;for(const Be of I??[])if(Be.folder_id!=null){const Qe=Me.get(Be.folder_id)??[];Qe.push(Be),Me.set(Be.folder_id,Qe)}return Me},[I]),X=Vo(E?.currency||"USD"),ae=E?.time_format||"system",Y=rt({mutationFn:Me=>ne.updateProject(b,Me),onSuccess:()=>{n.invalidateQueries({queryKey:["project",b]}),n.invalidateQueries({queryKey:["projects"]}),l(!1),d(!1),i(a("projectDetail.toast.projectUpdated"),"success")},onError:Me=>{i(Me.message,"error")}}),ce=()=>{m(x?.notes||""),d(!0)},de=()=>{Y.mutate({notes:u})},oe=()=>{d(!1),m("")},[K,ie]=y.useState(""),[ue,he]=y.useState(1),[ge,q]=y.useState(""),[Q,A]=y.useState(""),[F,B]=y.useState(""),[W,H]=y.useState(!1),[le,U]=y.useState(!1),[G,Z]=y.useState(null),[J,re]=y.useState(""),[se,fe]=y.useState(1),[me,pe]=y.useState(""),[V,L]=y.useState(""),[te,be]=y.useState(""),[xe,ve]=y.useState({isOpen:!1,title:"",message:"",onConfirm:()=>{}}),De=rt({mutationFn:Me=>ne.createBOMItem(b,Me),onSuccess:()=>{n.invalidateQueries({queryKey:["project-bom",b]}),n.invalidateQueries({queryKey:["project",b]}),ie(""),he(1),q(""),A(""),B(""),H(!1),i(a("projectDetail.toast.partAdded"),"success")},onError:Me=>i(Me.message,"error")}),je=rt({mutationFn:({itemId:Me,data:Be})=>ne.updateBOMItem(b,Me,Be),onSuccess:()=>{n.invalidateQueries({queryKey:["project-bom",b]}),n.invalidateQueries({queryKey:["project",b]}),Z(null)},onError:Me=>i(Me.message,"error")}),Te=rt({mutationFn:Me=>ne.deleteBOMItem(b,Me),onSuccess:()=>{n.invalidateQueries({queryKey:["project-bom",b]}),n.invalidateQueries({queryKey:["project",b]}),i(a("projectDetail.toast.partRemoved"),"success")},onError:Me=>i(Me.message,"error")}),qe=Me=>{Me.preventDefault(),K.trim()&&De.mutate({name:K.trim(),quantity_needed:ue,unit_price:ge?parseFloat(ge):void 0,sourcing_url:Q.trim()||void 0,remarks:F.trim()||void 0})},Pe=Me=>{const Be=Me.is_complete?0:Me.quantity_needed;je.mutate({itemId:Me.id,data:{quantity_acquired:Be}})},Ie=(Me,Be)=>{ve({isOpen:!0,title:a("projectDetail.bom.deletePart"),message:a("projectDetail.bom.deleteConfirm",{name:Be}),onConfirm:()=>{ve(Qe=>({...Qe,isOpen:!1})),Te.mutate(Me)}})},Re=Me=>{Z(Me),re(Me.name),fe(Me.quantity_needed),pe(Me.unit_price?.toString()||""),L(Me.sourcing_url||""),be(Me.remarks||"")},Ue=Me=>{Me.preventDefault(),!(!G||!J.trim())&&je.mutate({itemId:G.id,data:{name:J.trim(),quantity_needed:se,unit_price:me?parseFloat(me):void 0,sourcing_url:V.trim()||void 0,remarks:te.trim()||void 0}})},ze=()=>{Z(null)},it=async()=>{try{const{blob:Me,filename:Be}=await ne.exportProjectZip(Number(b)),Qe=URL.createObjectURL(Me),Ge=document.createElement("a");Ge.href=Qe,Ge.download=Be||`${x?.name||"project"}_${new Date().toISOString().split("T")[0]}.zip`,Ge.click(),URL.revokeObjectURL(Qe),i(a("projectDetail.toast.projectExported"),"success")}catch(Me){i(Me.message,"error")}},Oe=rt({mutationFn:()=>ne.createTemplateFromProject(b),onSuccess:()=>{n.invalidateQueries({queryKey:["projects"]}),i(a("projectDetail.toast.templateCreated"),"success")},onError:Me=>i(Me.message,"error")}),tt=Me=>Vg(Me,ae,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"});if(S)return r.jsx("div",{className:"flex items-center justify-center py-24",children:r.jsx(lt,{className:"w-8 h-8 animate-spin text-bambu-green"})});if(k||!x)return r.jsxs("div",{className:"text-center py-24",children:[r.jsx("p",{className:"text-bambu-gray",children:k?`${a("common.error")}: ${k.message}`:a("projectDetail.notFound")}),r.jsx(Le,{variant:"secondary",className:"mt-4",onClick:()=>e("/projects"),children:a("projectDetail.backToProjects")})]});const Fe=x.stats,Ye=Fe?.progress_percent??0,Ve=Fe?.parts_progress_percent??0;return r.jsxs("div",{className:"p-4 md:p-8 space-y-8",children:[r.jsxs("div",{className:"flex items-center gap-2 text-sm text-bambu-gray",children:[r.jsx(Ls,{to:"/projects",className:"hover:text-white transition-colors",children:a("nav.projects")}),r.jsx(Vn,{className:"w-4 h-4"}),r.jsx("span",{className:"text-white",children:x.name})]}),r.jsxs("div",{className:"flex items-start justify-between",children:[r.jsxs("div",{className:"flex items-center gap-4",children:[r.jsx("button",{onClick:()=>e("/projects"),className:"p-2 rounded-lg bg-bambu-card hover:bg-bambu-dark-tertiary transition-colors",children:r.jsx(ev,{className:"w-5 h-5 text-bambu-gray"})}),r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("div",{className:"w-4 h-4 rounded-full shrink-0",style:{backgroundColor:x.color||"#6b7280"}}),r.jsxs("div",{children:[r.jsx("h1",{className:"text-2xl font-bold text-white",children:x.name}),x.description&&r.jsx("p",{className:"text-bambu-gray mt-1",children:x.description})]})]}),r.jsx(Pst,{status:x.status,t:a})]}),r.jsxs("div",{className:"flex gap-2",children:[r.jsxs(Le,{variant:"secondary",onClick:it,disabled:!s("projects:read"),title:s("projects:read")?a("projectDetail.exportProject"):a("projectDetail.noExportPermission"),children:[r.jsx(Ur,{className:"w-4 h-4 mr-2"}),a("projectDetail.export")]}),r.jsxs(Le,{onClick:()=>l(!0),disabled:!s("projects:update"),title:s("projects:update")?void 0:a("projectDetail.noEditPermission"),children:[r.jsx(Bg,{className:"w-4 h-4 mr-2"}),a("common.edit")]})]})]}),(x.target_count||x.target_parts_count)&&r.jsx(Tt,{children:r.jsxs(jt,{className:"p-4 space-y-4",children:[x.target_count&&r.jsxs("div",{children:[r.jsxs("div",{className:"flex items-center justify-between mb-2",children:[r.jsx("span",{className:"text-sm text-bambu-gray",children:a("projectDetail.progress.platesProgress")}),r.jsxs("span",{className:"text-sm font-medium text-white",children:[Fe?.total_archives||0," / ",x.target_count," ",a("projectDetail.progress.printJobs")]})]}),r.jsx("div",{className:"h-3 bg-bambu-dark rounded-full overflow-hidden",children:r.jsx("div",{className:"h-full transition-all duration-500",style:{width:`${Math.min(Ye,100)}%`,backgroundColor:Ye>=100?"#22c55e":x.color||"#6b7280"}})}),r.jsxs("div",{className:"flex justify-between mt-1",children:[r.jsx("span",{className:"text-xs text-bambu-gray/70",children:a("projectDetail.progress.percentComplete",{percent:Ye.toFixed(0)})}),Fe?.remaining_prints!=null&&Fe.remaining_prints>0&&r.jsx("span",{className:"text-xs text-bambu-gray/70",children:a("projectDetail.progress.remaining",{count:Fe.remaining_prints})})]})]}),x.target_parts_count&&r.jsxs("div",{children:[r.jsxs("div",{className:"flex items-center justify-between mb-2",children:[r.jsx("span",{className:"text-sm text-bambu-gray",children:a("projectDetail.progress.partsProgress")}),r.jsxs("span",{className:"text-sm font-medium text-white",children:[Fe?.completed_prints||0," / ",x.target_parts_count," ",a("projectDetail.progress.parts")]})]}),r.jsx("div",{className:"h-3 bg-bambu-dark rounded-full overflow-hidden",children:r.jsx("div",{className:"h-full transition-all duration-500",style:{width:`${Math.min(Ve,100)}%`,backgroundColor:Ve>=100?"#22c55e":x.color||"#6b7280"}})}),r.jsxs("div",{className:"flex justify-between mt-1",children:[r.jsx("span",{className:"text-xs text-bambu-gray/70",children:a("projectDetail.progress.percentComplete",{percent:Ve.toFixed(0)})}),Fe?.remaining_parts!=null&&Fe.remaining_parts>0&&r.jsx("span",{className:"text-xs text-bambu-gray/70",children:a("projectDetail.progress.remaining",{count:Fe.remaining_parts})})]})]})]})}),Fe&&r.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[r.jsx(Tt,{children:r.jsx(jt,{className:"p-4",children:r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("div",{className:"p-2 rounded-lg bg-bambu-dark text-bambu-green",children:r.jsx(en,{className:"w-5 h-5"})}),r.jsxs("div",{children:[r.jsx("p",{className:"text-sm text-bambu-gray",children:a("projectDetail.stats.printJobs")}),r.jsxs("p",{className:"text-xl font-semibold text-white",children:[Fe.total_archives," ",r.jsx("span",{className:"text-sm font-normal text-bambu-gray",children:a("projectDetail.stats.total")})]}),Fe.failed_prints>0&&r.jsx("p",{className:"text-sm text-status-error",children:a("projectDetail.stats.failed",{count:Fe.failed_prints})}),r.jsx("p",{className:"text-sm text-bambu-gray",children:a("projectDetail.stats.partsPrinted",{count:Fe.completed_prints})})]})]})})}),r.jsx(VX,{icon:ar,label:a("projectDetail.stats.printTime"),value:L0e(Fe.total_print_time_hours),color:"text-yellow-400"}),r.jsx(VX,{icon:xr,label:a("projectDetail.stats.filamentUsed"),value:Cst(Fe.total_filament_grams),color:"text-purple-400"})]}),Fe&&(()=>{const Me=Fe.estimated_cost+Fe.total_energy_cost+Fe.bom_cost;return Fe.estimated_cost>0||Me>0||x.budget!==null})()&&r.jsx(Tt,{children:r.jsxs(jt,{className:"p-4",children:[r.jsx("h2",{className:"text-lg font-semibold text-white mb-3",children:a("projectDetail.cost.title")}),r.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[r.jsxs("div",{children:[r.jsx("p",{className:"text-xs text-bambu-gray uppercase",children:a("projectDetail.cost.filamentCost")}),r.jsxs("p",{className:"text-lg font-semibold text-white",children:[X,Fe.estimated_cost.toFixed(2)]})]}),Fe.total_energy_kwh>0&&r.jsxs("div",{children:[r.jsx("p",{className:"text-xs text-bambu-gray uppercase",children:a("projectDetail.cost.energy")}),r.jsxs("p",{className:"text-lg font-semibold text-white",children:[Fe.total_energy_kwh.toFixed(3)," kWh",Fe.total_energy_cost>0&&r.jsxs("span",{className:"text-sm text-bambu-gray ml-1",children:["(",X,Fe.total_energy_cost.toFixed(2),")"]})]})]}),(()=>{const Me=Fe.estimated_cost+Fe.total_energy_cost+Fe.bom_cost;return Me<=0?null:r.jsxs("div",{children:[r.jsx("p",{className:"text-xs text-bambu-gray uppercase",children:a("projectDetail.cost.totalCost")}),r.jsxs("p",{className:"text-lg font-semibold text-bambu-green",children:[X,Me.toFixed(2)]}),Fe.bom_cost>0&&r.jsx("p",{className:"text-xs text-bambu-gray/70",children:a("projectDetail.cost.includesBom")})]})})(),x.budget!==null&&(()=>{const Me=Fe.estimated_cost+Fe.total_energy_cost+Fe.bom_cost,Be=x.budget-Me;return r.jsxs("div",{children:[r.jsx("p",{className:"text-xs text-bambu-gray uppercase",children:a("projectDetail.cost.budget")}),r.jsxs("p",{className:"text-sm text-bambu-gray",children:[a("projectDetail.cost.total"),": ",r.jsxs("span",{className:"text-white font-semibold",children:[X,x.budget.toFixed(2)]})]}),r.jsxs("p",{className:`text-sm ${Be>=0?"text-bambu-green":"text-red-400"}`,children:[a("projectDetail.cost.remaining"),": ",r.jsxs("span",{className:"font-semibold",children:[X,Be.toFixed(2)]})]})]})})()]})]})}),x.children&&x.children.length>0&&r.jsx(Tt,{children:r.jsxs(jt,{className:"p-4",children:[r.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2 mb-3",children:[r.jsx(oxe,{className:"w-5 h-5"}),a("projectDetail.subProjects.title",{count:x.children.length})]}),r.jsx("div",{className:"space-y-2",children:x.children.map(Me=>r.jsxs(Ls,{to:`/projects/${Me.id}`,className:"flex items-center justify-between p-3 bg-bambu-dark rounded-lg hover:bg-bambu-dark-tertiary transition-colors",children:[r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("div",{className:"w-3 h-3 rounded-full",style:{backgroundColor:Me.color||"#6b7280"}}),r.jsx("span",{className:"text-white",children:Me.name}),r.jsx("span",{className:`text-xs px-2 py-0.5 rounded ${Me.status==="completed"?"bg-status-ok/20 text-status-ok":Me.status==="archived"?"bg-bambu-gray/20 text-bambu-gray":"bg-blue-500/20 text-blue-400"}`,children:Me.status})]}),Me.progress_percent!==null&&r.jsxs("span",{className:"text-sm text-bambu-gray",children:[Me.progress_percent.toFixed(0),"%"]})]},Me.id))})]})}),x.parent_id&&x.parent_name&&r.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[r.jsx(tn,{className:"w-4 h-4 text-bambu-gray"}),r.jsx("span",{className:"text-bambu-gray",children:a("projectDetail.partOf")}),r.jsx(Ls,{to:`/projects/${x.parent_id}`,className:"text-bambu-green hover:underline",children:x.parent_name})]}),(x.tags||x.due_date||x.priority!=="normal")&&r.jsxs("div",{className:"flex flex-wrap items-center gap-4",children:[x.priority&&x.priority!=="normal"&&r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("span",{className:"text-xs text-bambu-gray uppercase",children:a("projectDetail.priorityLabel")}),r.jsx(Tst,{priority:x.priority,t:a})]}),x.due_date&&r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(Cn,{className:"w-4 h-4 text-bambu-gray"}),r.jsx("span",{className:"text-sm text-white",children:qg(x.due_date,{year:"numeric",month:"short",day:"numeric"})}),FL(x.due_date,a)&&r.jsxs("span",{className:`text-xs ${FL(x.due_date,a).color}`,children:["(",FL(x.due_date,a).label,")"]})]}),x.tags&&r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(Xm,{className:"w-4 h-4 text-bambu-gray"}),r.jsx("div",{className:"flex flex-wrap gap-1",children:x.tags.split(",").map((Me,Be)=>r.jsx("span",{className:"px-2 py-0.5 bg-bambu-dark-tertiary text-bambu-gray text-xs rounded",children:Me.trim()},Be))})]})]}),r.jsx(Tt,{children:r.jsxs(jt,{className:"p-4",children:[r.jsxs("div",{className:"flex items-center justify-between mb-3",children:[r.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[r.jsx(us,{className:"w-5 h-5"}),a("projectDetail.notes.title")]}),c?r.jsxs("div",{className:"flex gap-2",children:[r.jsxs(Le,{variant:"secondary",size:"sm",onClick:oe,disabled:Y.isPending,children:[r.jsx(Ht,{className:"w-4 h-4 mr-1"}),a("common.cancel")]}),r.jsxs(Le,{size:"sm",onClick:de,disabled:Y.isPending,children:[Y.isPending?r.jsx(lt,{className:"w-4 h-4 animate-spin mr-1"}):r.jsx(ms,{className:"w-4 h-4 mr-1"}),a("common.save")]})]}):r.jsxs(Le,{variant:"secondary",size:"sm",onClick:ce,disabled:!s("projects:update"),title:s("projects:update")?void 0:a("projectDetail.notes.noEditPermission"),children:[r.jsx(Bg,{className:"w-4 h-4 mr-1"}),a("common.edit")]})]}),c?r.jsx(oI,{content:u,onChange:m,placeholder:a("projectDetail.notes.placeholder")}):x.notes?r.jsx("div",{className:"prose prose-invert prose-sm max-w-none",dangerouslySetInnerHTML:{__html:DB.sanitize(x.notes)}}):r.jsx("p",{className:"text-bambu-gray/70 text-sm italic",children:a("projectDetail.notes.empty")})]})}),r.jsx(Tt,{children:r.jsxs(jt,{className:"p-4",children:[r.jsx("div",{className:"flex items-center justify-between mb-3",children:r.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[r.jsx(Fl,{className:"w-5 h-5"}),a("projectDetail.files.title")]})}),r.jsxs("p",{className:"text-xs text-bambu-gray mb-3",children:[r.jsx(Ls,{to:"/files",className:"text-bambu-green hover:underline",children:a("projectDetail.files.linkFolders")})," ",a("projectDetail.files.forQuickAccess")]}),R&&R.length>0?r.jsx("div",{className:"space-y-4",children:R.map(Me=>{const Be=z.get(Me.id)??[],Qe=O;return r.jsxs("div",{children:[r.jsxs(Ls,{to:`/files?folder=${Me.id}`,className:"flex items-center justify-between p-3 bg-bambu-dark rounded-lg hover:bg-bambu-dark-tertiary transition-colors mb-2",children:[r.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[r.jsx(Fl,{className:"w-5 h-5 text-bambu-green shrink-0"}),r.jsxs("div",{className:"min-w-0",children:[r.jsx("p",{className:"text-sm text-white truncate",children:Me.name}),r.jsx("p",{className:"text-xs text-bambu-gray",children:a("projectDetail.files.fileCount",{count:Me.file_count})})]})]}),r.jsx(Vn,{className:"w-4 h-4 text-bambu-gray shrink-0"})]}),Qe?r.jsx("div",{className:"flex items-center gap-2 px-3 py-2 text-bambu-gray text-sm",children:r.jsx(lt,{className:"w-4 h-4 animate-spin"})}):Be.length===0?r.jsx("p",{className:"text-bambu-gray/60 text-xs italic px-3",children:a("projectDetail.files.noFiles")}):r.jsx("div",{className:"space-y-1 pl-3",children:Be.map(Ge=>{const Ee=_st(Ge.filename);return r.jsxs("div",{className:"flex items-center gap-3 p-2 rounded-lg hover:bg-bambu-dark-tertiary transition-colors",children:[r.jsx("div",{className:"w-10 h-10 shrink-0 rounded bg-bambu-dark overflow-hidden flex items-center justify-center",children:Ge.thumbnail_path?r.jsx("img",{src:ne.getLibraryFileThumbnailUrl(Ge.id),alt:Ge.print_name||Ge.filename,className:"w-full h-full object-cover"}):r.jsx(Rh,{className:"w-5 h-5 text-bambu-gray/40"})}),r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsx("p",{className:"text-sm text-white truncate",title:Ge.print_name||Ge.filename,children:Ge.print_name||Ge.filename}),r.jsx("span",{className:`text-xs px-1.5 py-0.5 rounded font-medium ${Ge.file_type==="3mf"?"bg-bambu-green/20 text-bambu-green":Ge.file_type==="gcode"?"bg-blue-500/20 text-blue-400":"bg-bambu-gray/20 text-bambu-gray"}`,children:Ge.file_type.toUpperCase()})]}),Ee&&r.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[r.jsx("button",{onClick:()=>f(Ge),title:a("projectDetail.files.print"),className:"p-1.5 rounded hover:bg-bambu-green/20 text-bambu-green transition-colors",children:r.jsx(gs,{className:"w-4 h-4"})}),r.jsx("button",{onClick:()=>v(Ge),title:a("projectDetail.files.addToQueue"),className:"p-1.5 rounded hover:bg-blue-500/20 text-blue-400 transition-colors",children:r.jsx(Age,{className:"w-4 h-4"})})]})]},Ge.id)})})]},Me.id)})}):r.jsx("p",{className:"text-bambu-gray/70 text-sm italic",children:a("projectDetail.files.empty")})]})}),r.jsx(Tt,{children:r.jsxs(jt,{className:"p-4",children:[r.jsxs("div",{className:"flex items-center justify-between mb-4",children:[r.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[r.jsx(fb,{className:"w-5 h-5"}),a("projectDetail.bom.title"),Fe&&Fe.bom_total_items>0&&r.jsxs("span",{className:"text-sm font-normal text-bambu-gray",children:["(",a("projectDetail.bom.acquired",{completed:Fe.bom_completed_items,total:Fe.bom_total_items}),")"]})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[T&&T.some(Me=>Me.is_complete)&&r.jsx("button",{onClick:()=>U(!le),className:`text-xs px-2 py-1 rounded transition-colors ${le?"bg-bambu-green/20 text-bambu-green":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:a(le?"projectDetail.bom.showAll":"projectDetail.bom.hideDone")}),!W&&r.jsxs(Le,{variant:"secondary",size:"sm",onClick:()=>H(!0),disabled:!s("projects:update"),title:s("projects:update")?void 0:a("projectDetail.bom.noAddPermission"),children:[r.jsx(or,{className:"w-4 h-4 mr-1"}),a("projectDetail.bom.addPart")]})]})]}),W&&r.jsxs("form",{onSubmit:qe,className:"bg-bambu-dark rounded-lg p-4 mb-4 space-y-3",children:[r.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[r.jsx("input",{type:"text",value:K,onChange:Me=>ie(Me.target.value),className:"bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:a("projectDetail.bom.partNamePlaceholder"),autoFocus:!0}),r.jsxs("div",{className:"flex gap-2",children:[r.jsx("input",{type:"number",value:ue,onChange:Me=>he(parseInt(Me.target.value)||1),className:"w-20 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white focus:outline-none focus:border-bambu-green",min:"1",placeholder:a("projectDetail.bom.qty")}),r.jsx("input",{type:"number",step:"0.01",value:ge,onChange:Me=>q(Me.target.value),className:"flex-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:a("projectDetail.bom.price",{currency:X})})]})]}),r.jsx("input",{type:"url",value:Q,onChange:Me=>A(Me.target.value),className:"w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:a("projectDetail.bom.sourcingUrlPlaceholder")}),r.jsx("input",{type:"text",value:F,onChange:Me=>B(Me.target.value),className:"w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:a("projectDetail.bom.remarksPlaceholder")}),r.jsxs("div",{className:"flex justify-end gap-2",children:[r.jsx(Le,{type:"button",variant:"secondary",size:"sm",onClick:()=>H(!1),children:a("common.cancel")}),r.jsx(Le,{type:"submit",size:"sm",disabled:!K.trim()||De.isPending,children:De.isPending?r.jsx(lt,{className:"w-4 h-4 animate-spin"}):a("projectDetail.bom.addPart")})]})]}),j?r.jsx("div",{className:"flex items-center justify-center py-4",children:r.jsx(lt,{className:"w-6 h-6 animate-spin text-bambu-green"})}):T&&T.length>0?r.jsxs("div",{className:"space-y-2",children:[T.filter(Me=>!le||!Me.is_complete).map(Me=>r.jsx("div",{className:`p-3 rounded-lg transition-colors ${Me.is_complete?"bg-status-ok/10":"bg-bambu-dark"}`,children:G?.id===Me.id?r.jsxs("form",{onSubmit:Ue,className:"space-y-3",children:[r.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[r.jsx("input",{type:"text",value:J,onChange:Be=>re(Be.target.value),className:"bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:a("projectDetail.bom.partName"),autoFocus:!0}),r.jsxs("div",{className:"flex gap-2",children:[r.jsx("input",{type:"number",value:se,onChange:Be=>fe(parseInt(Be.target.value)||1),className:"w-20 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white focus:outline-none focus:border-bambu-green",min:"1",placeholder:a("projectDetail.bom.qty")}),r.jsx("input",{type:"number",step:"0.01",value:me,onChange:Be=>pe(Be.target.value),className:"flex-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:a("projectDetail.bom.price",{currency:X})})]})]}),r.jsx("input",{type:"url",value:V,onChange:Be=>L(Be.target.value),className:"w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:a("projectDetail.bom.sourcingUrlPlaceholder")}),r.jsx("input",{type:"text",value:te,onChange:Be=>be(Be.target.value),className:"w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:a("projectDetail.bom.remarksPlaceholder")}),r.jsxs("div",{className:"flex justify-end gap-2",children:[r.jsx(Le,{type:"button",variant:"secondary",size:"sm",onClick:ze,children:a("common.cancel")}),r.jsx(Le,{type:"submit",size:"sm",disabled:!J.trim()||je.isPending,children:je.isPending?r.jsx(lt,{className:"w-4 h-4 animate-spin"}):a("common.save")})]})]}):r.jsxs("div",{className:"flex items-start gap-3",children:[r.jsx("button",{onClick:()=>s("projects:update")&&Pe(Me),disabled:je.isPending||!s("projects:update"),title:s("projects:update")?void 0:a("projectDetail.bom.noUpdatePermission"),className:`w-5 h-5 mt-0.5 rounded border-2 flex items-center justify-center transition-colors shrink-0 ${Me.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:Me.is_complete&&r.jsx(fr,{className:"w-3 h-3"})}),r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsxs("div",{className:"flex items-center justify-between gap-2",children:[r.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[r.jsxs("p",{className:`text-sm font-medium ${Me.is_complete?"text-bambu-gray line-through":"text-white"}`,children:[Me.name,r.jsxs("span",{className:"text-bambu-gray font-normal ml-2",children:["x",Me.quantity_needed]})]}),Me.unit_price!==null&&r.jsxs("span",{className:"text-xs text-bambu-green whitespace-nowrap",children:[X,(Me.unit_price*Me.quantity_needed).toFixed(2)]})]}),r.jsxs("div",{className:"flex items-center gap-1",children:[r.jsx("button",{onClick:()=>s("projects:update")&&Re(Me),disabled:!s("projects:update"),className:`p-1 rounded transition-colors shrink-0 ${s("projects:update")?"hover:bg-bambu-dark-tertiary text-bambu-gray hover:text-white":"text-bambu-gray/50 cursor-not-allowed"}`,title:s("projects:update")?a("common.edit"):a("projectDetail.bom.noEditPermission"),children:r.jsx(ci,{className:"w-4 h-4"})}),r.jsx("button",{onClick:()=>s("projects:update")&&Ie(Me.id,Me.name),disabled:!s("projects:update"),className:`p-1 rounded transition-colors shrink-0 ${s("projects:update")?"hover:bg-bambu-dark-tertiary text-bambu-gray hover:text-red-400":"text-bambu-gray/50 cursor-not-allowed"}`,title:s("projects:update")?a("common.delete"):a("projectDetail.bom.noDeletePermission"),children:r.jsx(na,{className:"w-4 h-4"})})]})]}),Me.sourcing_url&&r.jsxs("a",{href:Me.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:Be=>Be.stopPropagation(),children:[r.jsx(Tr,{className:"w-3 h-3 shrink-0"}),r.jsx("span",{className:"truncate",children:(()=>{try{return new URL(Me.sourcing_url).hostname.replace("www.","")}catch{return Me.sourcing_url}})()})]}),Me.remarks&&r.jsx("p",{className:"mt-1 text-xs text-bambu-gray/80 italic",children:Me.remarks})]})]})},Me.id)),Fe&&Fe.bom_cost>0&&r.jsxs("div",{className:"pt-2 mt-2 border-t border-bambu-dark-tertiary flex justify-between text-sm",children:[r.jsx("span",{className:"text-bambu-gray",children:a("projectDetail.bom.totalCost")}),r.jsxs("span",{className:"text-white font-medium",children:[X,Fe.bom_cost.toFixed(2)]})]})]}):r.jsx("p",{className:"text-bambu-gray/70 text-sm italic",children:a("projectDetail.bom.empty")})]})}),r.jsx(Tt,{children:r.jsxs(jt,{className:"p-4",children:[r.jsx("div",{className:"flex items-center justify-between mb-3",children:r.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[r.jsx(Jh,{className:"w-5 h-5"}),a("projectDetail.timeline.title")]})}),C?r.jsx("div",{className:"flex items-center justify-center py-4",children:r.jsx(lt,{className:"w-6 h-6 animate-spin text-bambu-green"})}):D&&D.length>0?r.jsx("div",{className:"space-y-3",children:D.slice(0,10).map((Me,Be)=>r.jsxs("div",{className:"flex gap-3",children:[r.jsxs("div",{className:`w-8 h-8 rounded-full flex items-center justify-center shrink-0 ${Me.event_type==="print_completed"?"bg-status-ok/20 text-status-ok":Me.event_type==="print_failed"?"bg-status-error/20 text-status-error":Me.event_type==="print_started"?"bg-yellow-500/20 text-yellow-400":"bg-bambu-dark-tertiary text-bambu-gray"}`,children:[Me.event_type==="print_completed"&&r.jsx(fr,{className:"w-4 h-4"}),Me.event_type==="print_failed"&&r.jsx(Fr,{className:"w-4 h-4"}),Me.event_type==="print_started"&&r.jsx(xr,{className:"w-4 h-4"}),Me.event_type==="queued"&&r.jsx(c3,{className:"w-4 h-4"}),Me.event_type==="project_created"&&r.jsx(or,{className:"w-4 h-4"})]}),r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsx("p",{className:"text-sm text-white",children:Me.title}),Me.description&&r.jsx("p",{className:"text-xs text-bambu-gray truncate",children:Me.description}),r.jsx("p",{className:"text-xs text-bambu-gray/70",children:tt(Me.timestamp)})]})]},Be))}):r.jsx("p",{className:"text-bambu-gray/70 text-sm italic",children:a("projectDetail.timeline.empty")})]})}),!x.is_template&&r.jsx("div",{className:"flex justify-end",children:r.jsxs(Le,{variant:"secondary",size:"sm",onClick:()=>Oe.mutate(),disabled:Oe.isPending||!s("projects:create"),title:s("projects:create")?void 0:a("projectDetail.template.noCreatePermission"),children:[Oe.isPending?r.jsx(lt,{className:"w-4 h-4 animate-spin mr-2"}):r.jsx(li,{className:"w-4 h-4 mr-2"}),a("projectDetail.template.saveAsTemplate")]})}),Fe&&(Fe.queued_prints>0||Fe.in_progress_prints>0)&&r.jsx(Tt,{children:r.jsxs(jt,{className:"p-4",children:[r.jsxs("div",{className:"flex items-center justify-between mb-3",children:[r.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[r.jsx(c3,{className:"w-5 h-5"}),a("projectDetail.queue.title")]}),r.jsx(Ls,{to:`/queue?project=${b}`,className:"text-sm text-bambu-green hover:underline",children:a("projectDetail.queue.viewAll")})]}),r.jsxs("div",{className:"flex items-center gap-4 text-sm",children:[Fe.in_progress_prints>0&&r.jsx("span",{className:"text-yellow-400",children:a("projectDetail.queue.printing",{count:Fe.in_progress_prints})}),Fe.queued_prints>0&&r.jsx("span",{className:"text-bambu-gray",children:a("projectDetail.queue.queued",{count:Fe.queued_prints})})]})]})}),r.jsxs("div",{children:[r.jsx("div",{className:"flex items-center justify-between mb-4",children:r.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[r.jsx(en,{className:"w-5 h-5"}),a("projectDetail.prints.title",{count:P?.length||0})]})}),N?r.jsx("div",{className:"flex items-center justify-center py-8",children:r.jsx(lt,{className:"w-6 h-6 animate-spin text-bambu-green"})}):r.jsx(Nst,{archives:P||[],t:a})]}),o&&r.jsx(Ade,{t:a,currencySymbol:X,project:{...x,archive_count:Fe?.total_archives||0,total_items:Fe?.total_items||0,completed_count:Fe?.completed_prints||0,failed_count:Fe?.failed_prints||0,queue_count:Fe?.queued_prints||0,progress_percent:Fe?.progress_percent||null,archives:[]},onClose:()=>l(!1),onSave:Me=>Y.mutate(Me),isLoading:Y.isPending}),xe.isOpen&&r.jsx(ka,{title:xe.title,message:xe.message,confirmText:a("common.delete"),variant:"danger",onConfirm:xe.onConfirm,onCancel:()=>ve(Me=>({...Me,isOpen:!1}))}),p&&r.jsx(Pc,{mode:"reprint",libraryFileId:p.id,archiveName:p.print_name||p.filename,projectId:b,onClose:()=>f(null),onSuccess:()=>{f(null),n.invalidateQueries({queryKey:["archives"]})}}),g&&r.jsx(Pc,{mode:"add-to-queue",libraryFileId:g.id,archiveName:g.print_name||g.filename,projectId:b,onClose:()=>v(null),onSuccess:()=>{v(null),n.invalidateQueries({queryKey:["queue"]})}})]})}function jst({archiveId:t,libraryFileId:e,title:a,fileType:n,onClose:i,onSliceWithBambuddy:s}){const{t:o}=wt(),{data:l}=$e({queryKey:["settings"],queryFn:ne.getSettings}),c=l?.open_in_slicer||l?.preferred_slicer||"bambu_studio",d=e!=null,[u,m]=y.useState(null),[p,f]=y.useState(null),[g,v]=y.useState(!0),[b,x]=y.useState(null),[S,k]=y.useState(!1),[P,N]=y.useState(null),[T,j]=y.useState(0),[D,C]=y.useState(!1),[E,R]=y.useState(null),[I,O]=y.useState(!1),[z,X]=y.useState(!1),ae=y.useRef(null),Y=y.useRef(null),ce=10,de=160,oe=240,K=.35;y.useEffect(()=>{const L=te=>{te.key==="Escape"&&i()};return window.addEventListener("keydown",L),()=>window.removeEventListener("keydown",L)},[i]),y.useEffect(()=>{if(v(!0),d){const L=(n||"").toLowerCase(),te=L==="3mf"||L==="gcode.3mf",be=te||L==="stl",xe=te||L==="gcode";f({has_model:be,has_gcode:xe,has_source:!1,build_volume:{x:256,y:256,z:256},filament_colors:[]}),m(be?"3d":xe?"gcode":null),v(!1);return}if(!t){f(null),m(null),v(!1);return}ne.getArchiveCapabilities(t).then(L=>{f(L),L.has_model?m("3d"):L.has_gcode&&m("gcode"),v(!1)}).catch(()=>{f({has_model:!0,has_gcode:!1,has_source:!1,build_volume:{x:256,y:256,z:256},filament_colors:[]}),m("3d"),v(!1)})},[t,n,d]),y.useEffect(()=>{if(k(!0),N(null),j(0),d){const L=(n||"").toLowerCase();if(!e||!(L==="3mf"||L==="gcode.3mf")){x(null),k(!1);return}ne.getLibraryFilePlates(e).then(be=>x(be)).catch(()=>x(null)).finally(()=>k(!1));return}if(!t){x(null),k(!1);return}ne.getArchivePlates(t).then(L=>x(L)).catch(()=>x(null)).finally(()=>k(!1))},[t,n,d,e]);const ie=y.useMemo(()=>b?.plates??[],[b]),ue=(b?.is_multi_plate??!1)&&ie.length>1,he=D&&ue,ge=P==null?null:ie.find(L=>L.index===P)??null,q=L=>L.object_count??L.objects?.length??0,Q=ie.reduce((L,te)=>L+q(te),0),A=ge?q(ge):Q,F=ge?o("modelViewer.plateNumber",{number:ge.index}):o("modelViewer.allPlates"),B=ie.length>0,W=y.useRef(null),H=y.useRef(null),[le,U]=y.useState(10),[G,Z]=y.useState(3),J=ie.length>le,re=Math.max(1,Math.ceil(ie.length/le)),se=J?ie.slice(T*le,(T+1)*le):ie;y.useEffect(()=>{if(!he){U(10),Z(3);return}const L=W.current,te=H.current;if(!L||!te)return;let be=0;const xe=()=>{const je=te.clientWidth,qe=Math.floor(je/210),Pe=Math.max(3,Math.min(5,qe||3));Z(Ye=>Ye===Pe?Ye:Pe);const Ie=window.getComputedStyle(L),Re=Number.parseFloat(Ie.rowGap||"0"),ze=L.querySelector("button")?.getBoundingClientRect().height??44,it=te.clientHeight,tt=Math.max(1,Math.floor((it+Re)/(ze+Re)))*Pe,Fe=Math.max(1,tt-1);U(Ye=>Ye===Fe?Ye:Fe)},ve=()=>{be&&cancelAnimationFrame(be),be=requestAnimationFrame(xe)};ve();const De=new ResizeObserver(ve);return De.observe(te),De.observe(L),()=>{be&&cancelAnimationFrame(be),De.disconnect()}},[he,ie.length]),y.useEffect(()=>{if(!J){j(0);return}j(L=>Math.min(L,re-1))},[ie.length,J,re]),y.useEffect(()=>{if(!J||P==null)return;const L=ie.findIndex(be=>be.index===P);if(L<0)return;const te=Math.floor(L/le);j(be=>be===te?be:te)},[ie,le,P,J]),y.useEffect(()=>{if(!he){R(null),X(!1);return}if(z)return;const L=ae.current,te=Y.current;if(!L||!te)return;const be=L.clientHeight;if(!be)return;const xe=Math.max(oe,be*K),ve=Math.max(de,be-ce-xe),De=Math.min(te.scrollHeight,ve);R(Math.max(de,De))},[he,z,ie.length,T,ce,de,oe,K]),y.useEffect(()=>{if(!I)return;const L=be=>{const xe=ae.current;if(!xe)return;const ve=xe.getBoundingClientRect(),De=ve.height;if(!De)return;const je=Math.max(oe,De*K),Te=Math.max(de,De-ce-je),qe=Math.min(Te,Math.max(de,be.clientY-ve.top));R(qe)},te=()=>{O(!1),X(!0)};return document.addEventListener("mousemove",L),document.addEventListener("mouseup",te),document.body.style.cursor="row-resize",document.body.style.userSelect="none",()=>{document.removeEventListener("mousemove",L),document.removeEventListener("mouseup",te),document.body.style.cursor="",document.body.style.userSelect=""}},[I,ce,de,oe,K]);const fe=d?(n||"").toLowerCase()==="3mf":!0,me=(()=>{const L=(n||"").toLowerCase();return L==="3mf"||L==="stl"||L==="step"||L==="stp"})(),pe=!!(d&&l?.use_slicer_api&&s&&me),V=async()=>{if(!fe)return;const L=a||"model";try{if(d){const{token:te}=await ne.createLibrarySlicerToken(e),be=ne.getLibrarySlicerDownloadUrl(e,te,L);Lm(`${window.location.origin}${be}`,c)}else{const{token:te}=await ne.createArchiveSlicerToken(t),be=ne.getArchiveSlicerDownloadUrl(t,te,L);Lm(`${window.location.origin}${be}`,c)}}catch{if(d){const te=`${window.location.origin}${ne.getLibraryFileDownloadUrl(e)}`;Lm(te,c)}else{const te=`${window.location.origin}${ne.getArchiveForSlicer(t,L)}`;Lm(te,c)}}};return r.jsx("div",{className:`fixed inset-0 bg-black/70 flex items-center justify-center z-50 ${D?"p-0":"p-8"}`,onClick:i,children:r.jsxs("div",{className:`bg-bambu-dark-secondary border border-bambu-dark-tertiary w-full flex flex-col ${D?"h-full max-w-none rounded-none":"h-[80vh] max-w-4xl rounded-xl"}`,onClick:L=>L.stopPropagation(),children:[r.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"flex items-center gap-3 min-w-0 flex-1 mr-4",children:[r.jsx("h2",{className:"text-lg font-semibold text-white truncate",children:a}),B&&r.jsxs("span",{className:"text-xs text-bambu-gray bg-bambu-dark-tertiary/70 px-2 py-1 rounded whitespace-nowrap",children:[F,": ",o("modelViewer.objectCount",{count:A})]})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[pe?r.jsxs(Le,{variant:"secondary",size:"sm",onClick:s,children:[r.jsx(bd,{className:"w-4 h-4"}),o("slice.action")]}):r.jsxs(Le,{variant:"secondary",size:"sm",onClick:V,disabled:!fe,children:[r.jsx(Tr,{className:"w-4 h-4"}),o("modelViewer.openInSlicer")]}),r.jsx(Le,{variant:"secondary",size:"sm",onClick:()=>C(L=>!L),title:D?"Exit fullscreen":"Enter fullscreen",children:D?r.jsx(UI,{className:"w-4 h-4"}):r.jsx(LT,{className:"w-4 h-4"})}),r.jsx(Le,{variant:"ghost",size:"sm",onClick:i,children:r.jsx(Ht,{className:"w-5 h-5"})})]})]}),p&&r.jsxs("div",{className:"flex border-b border-bambu-dark-tertiary",children:[r.jsxs("button",{onClick:()=>p.has_model&&m("3d"),disabled:!p.has_model,className:`flex items-center gap-2 px-6 py-3 text-sm font-medium transition-colors ${u==="3d"?"text-bambu-green border-b-2 border-bambu-green":p.has_model?"text-bambu-gray hover:text-white":"text-bambu-gray/30 cursor-not-allowed"}`,children:[r.jsx(Ei,{className:"w-4 h-4"}),o("modelViewer.tabs.model"),!p.has_model&&r.jsxs("span",{className:"text-xs",children:["(",o("modelViewer.notAvailable"),")"]})]}),r.jsxs("button",{onClick:()=>p.has_gcode&&m("gcode"),disabled:!p.has_gcode,className:`flex items-center gap-2 px-6 py-3 text-sm font-medium transition-colors ${u==="gcode"?"text-bambu-green border-b-2 border-bambu-green":p.has_gcode?"text-bambu-gray hover:text-white":"text-bambu-gray/30 cursor-not-allowed"}`,children:[r.jsx(obe,{className:"w-4 h-4"}),o("modelViewer.tabs.gcode"),!p.has_gcode&&r.jsxs("span",{className:"text-xs",children:["(",o("modelViewer.notSliced"),")"]})]})]}),r.jsx("div",{className:"flex-1 overflow-hidden p-4",children:g?r.jsx("div",{className:"w-full h-full flex items-center justify-center",children:r.jsx(lt,{className:"w-8 h-8 animate-spin text-bambu-green"})}):u==="3d"&&p?r.jsxs("div",{ref:ae,className:`w-full h-full flex flex-col ${he?"gap-0 min-h-0":"gap-3"}`,children:[ue&&r.jsxs("div",{ref:Y,style:he&&E!=null?{height:E}:void 0,className:`rounded-lg border border-bambu-dark-tertiary bg-bambu-dark p-3 ${he?"flex flex-col shrink-0":""}`,children:[r.jsxs("div",{className:"flex items-center gap-2 text-sm text-bambu-gray mb-2",children:[r.jsx(tn,{className:"w-4 h-4"}),o("modelViewer.plates"),S&&r.jsx(lt,{className:"w-3 h-3 animate-spin"})]}),r.jsxs("div",{className:he?"flex flex-col min-h-0 flex-1":void 0,children:[r.jsx("div",{ref:H,className:he?"min-h-0 overflow-hidden pr-1 flex-1":void 0,children:r.jsxs("div",{ref:W,className:he?"grid gap-2":"grid grid-cols-2 md:grid-cols-3 gap-2",style:he?{gridTemplateColumns:`repeat(${G}, minmax(0, 1fr))`}:void 0,children:[r.jsxs("button",{type:"button",onClick:()=>N(null),className:`flex items-center rounded-lg border text-left transition-colors ${he?"gap-1.5 p-1.5 w-full":"gap-2 p-2"} ${P==null?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary bg-bambu-dark-secondary hover:border-bambu-gray"}`,children:[r.jsx("div",{className:`rounded bg-bambu-dark-tertiary flex items-center justify-center ${he?"w-8 h-8":"w-10 h-10"}`,children:r.jsx(tn,{className:`${he?"w-4 h-4":"w-5 h-5"} text-bambu-gray`})}),r.jsxs("div",{className:"min-w-0 flex-1",children:[r.jsx("p",{className:`${he?"text-xs":"text-sm"} text-white font-medium truncate`,children:o("modelViewer.allPlates")}),r.jsx("p",{className:`${he?"text-[10px]":"text-xs"} text-bambu-gray truncate`,children:o("modelViewer.plateCount",{count:ie.length})})]}),P==null&&r.jsx(_r,{className:`${he?"w-3.5 h-3.5":"w-4 h-4"} text-bambu-green flex-shrink-0`})]}),se.map(L=>r.jsxs("button",{type:"button",onClick:()=>N(L.index),className:`flex items-center rounded-lg border text-left transition-colors ${he?"gap-1.5 p-1.5 w-full":"gap-2 p-2"} ${P===L.index?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary bg-bambu-dark-secondary hover:border-bambu-gray"}`,children:[L.has_thumbnail&&L.thumbnail_url?r.jsx("img",{src:L.thumbnail_url,alt:`Plate ${L.index}`,className:`${he?"w-8 h-8":"w-10 h-10"} rounded object-cover bg-bambu-dark-tertiary`}):r.jsx("div",{className:`rounded bg-bambu-dark-tertiary flex items-center justify-center ${he?"w-8 h-8":"w-10 h-10"}`,children:r.jsx(tn,{className:`${he?"w-4 h-4":"w-5 h-5"} text-bambu-gray`})}),r.jsxs("div",{className:"min-w-0 flex-1",children:[r.jsx("p",{className:`${he?"text-xs":"text-sm"} text-white font-medium truncate`,children:L.name||o("modelViewer.plateNumber",{number:L.index})}),r.jsx("p",{className:`${he?"text-[10px]":"text-xs"} text-bambu-gray truncate`,children:o("modelViewer.objectCount",{count:L.object_count??L.objects?.length??0})})]}),P===L.index&&r.jsx(_r,{className:`${he?"w-3.5 h-3.5":"w-4 h-4"} text-bambu-green flex-shrink-0`})]},L.index))]})}),(ge||J)&&r.jsxs("div",{className:"mt-auto pt-3 flex items-center gap-4 text-xs text-bambu-gray overflow-x-auto",children:[ge&&r.jsxs("div",{className:"flex items-center gap-3 whitespace-nowrap",children:[r.jsx("span",{children:o("modelViewer.plateNumber",{number:ge.index})}),ge.print_time_seconds!=null&&r.jsx("span",{children:o("modelViewer.eta",{minutes:Math.round(ge.print_time_seconds/60)})}),ge.filament_used_grams!=null&&r.jsxs("span",{children:[ge.filament_used_grams.toFixed(1)," g"]}),ge.filaments.length>0&&r.jsx("span",{children:o("modelViewer.filamentCount",{count:ge.filaments.length})})]}),J&&r.jsxs("div",{className:`flex items-center gap-2 whitespace-nowrap ${ge?"ml-auto":""}`,children:[r.jsx("span",{children:o("modelViewer.pagination.pageOf",{current:T+1,total:re})}),r.jsxs("div",{className:"flex items-center gap-1",children:[r.jsx("button",{type:"button",onClick:()=>j(L=>Math.max(L-1,0)),disabled:T===0,className:`px-2 py-1 rounded border text-xs ${T===0?"border-bambu-dark-tertiary text-bambu-gray/40 cursor-not-allowed":"border-bambu-dark-tertiary text-bambu-gray hover:text-white hover:border-bambu-gray"}`,children:o("modelViewer.pagination.prev")}),(()=>{let te=Math.max(0,T-Math.floor(2.5));const be=Math.min(re,te+5);be-te<5&&(te=Math.max(0,be-5));const xe=Array.from({length:be-te},(ve,De)=>te+De);return r.jsxs(r.Fragment,{children:[te>0&&r.jsx("button",{type:"button",onClick:()=>j(0),className:`px-2 py-1 rounded border text-xs ${T===0?"border-bambu-green text-bambu-green":"border-bambu-dark-tertiary text-bambu-gray hover:text-white hover:border-bambu-gray"}`,children:"1"}),te>1&&r.jsx("span",{className:"px-1",children:"…"}),xe.map(ve=>r.jsx("button",{type:"button",onClick:()=>j(ve),className:`px-2 py-1 rounded border text-xs ${T===ve?"border-bambu-green text-bambu-green":"border-bambu-dark-tertiary text-bambu-gray hover:text-white hover:border-bambu-gray"}`,children:ve+1},ve)),bej(re-1),className:`px-2 py-1 rounded border text-xs ${T===re-1?"border-bambu-green text-bambu-green":"border-bambu-dark-tertiary text-bambu-gray hover:text-white hover:border-bambu-gray"}`,children:re})]})})(),r.jsx("button",{type:"button",onClick:()=>j(L=>Math.min(L+1,re-1)),disabled:T>=re-1,className:`px-2 py-1 rounded border text-xs ${T>=re-1?"border-bambu-dark-tertiary text-bambu-gray/40 cursor-not-allowed":"border-bambu-dark-tertiary text-bambu-gray hover:text-white hover:border-bambu-gray"}`,children:o("modelViewer.pagination.next")})]})]})]})]})]}),he&&r.jsx("div",{role:"separator","aria-orientation":"horizontal",onMouseDown:L=>{L.preventDefault(),O(!0),X(!0)},className:`h-2 cursor-row-resize flex items-center justify-center ${I?"bg-bambu-dark-tertiary":"bg-bambu-dark-secondary/60 hover:bg-bambu-dark-tertiary"}`,children:r.jsx("div",{className:"w-12 h-1 rounded-full bg-bambu-gray/50"})}),r.jsx("div",{className:`flex-1 ${he?"min-h-0":""}`,children:r.jsx(yee,{url:d?ne.getLibraryFileDownloadUrl(e):p.has_source?ne.getSource3mfDownloadUrl(t):ne.getArchiveDownload(t),fileType:n,buildVolume:p.build_volume,filamentColors:p.filament_colors,selectedPlateId:P,className:"w-full h-full"})})]}):u==="gcode"&&p?r.jsx(tte,{gcodeUrl:d?ne.getLibraryFileGcodeUrl(e):ne.getArchiveGcode(t),filamentColors:p.filament_colors,className:"w-full h-full"}):r.jsx("div",{className:"w-full h-full flex items-center justify-center text-bambu-gray",children:o("modelViewer.noPreview")})})]})})}const Mst=90;function Est({onClose:t}){const{t:e}=wt(),a=ia(),{showToast:n}=da(),[i,s]=y.useState(Mst),[o,l]=y.useState(!0),[c,d]=y.useState(i);y.useEffect(()=>{const b=window.setTimeout(()=>d(i),300);return()=>window.clearTimeout(b)},[i]);const u=$e({queryKey:["library-purge-preview",c,o],queryFn:()=>ne.previewLibraryPurge(c,o),enabled:c>=1}),m=rt({mutationFn:()=>ne.executeLibraryPurge(i,o),onSuccess:b=>{n(e("libraryPurge.toast.success",{count:b.moved_to_trash}),"success"),a.invalidateQueries({queryKey:["library-files"]}),a.invalidateQueries({queryKey:["library-folders"]}),a.invalidateQueries({queryKey:["library-trash"]}),a.invalidateQueries({queryKey:["library-trash-count"]}),t()},onError:b=>n(b.message||e("libraryPurge.toast.failed"),"error")});y.useEffect(()=>{const b=x=>{x.key==="Escape"&&!m.isPending&&t()};return window.addEventListener("keydown",b),()=>window.removeEventListener("keydown",b)},[t,m.isPending]);const p=u.data,f=p?.count??0,g=p?.total_bytes??0,v=f>0&&!m.isPending;return r.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4",children:r.jsxs("div",{className:"bg-white dark:bg-gray-900 rounded-lg shadow-xl max-w-lg w-full",children:[r.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-gray-200 dark:border-gray-700",children:[r.jsxs("h2",{className:"text-lg font-semibold text-gray-900 dark:text-gray-100 flex items-center gap-2",children:[r.jsx(na,{className:"w-5 h-5"}),e("libraryPurge.title")]}),r.jsx("button",{onClick:t,className:"text-gray-400 hover:text-gray-600 dark:hover:text-gray-200","aria-label":e("common.close"),disabled:m.isPending,children:r.jsx(Ht,{className:"w-5 h-5"})})]}),r.jsxs("div",{className:"p-4 space-y-4",children:[r.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-400",children:e("libraryPurge.description")}),r.jsxs("div",{children:[r.jsx("label",{htmlFor:"purge-days",className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1",children:e("libraryPurge.ageLabel")}),r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("input",{id:"purge-days",type:"number",min:1,max:3650,value:i,onChange:b=>s(Math.max(1,Math.min(3650,parseInt(b.target.value||"0",10)||0))),className:"w-24 rounded border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-sm px-2 py-1 text-gray-900 dark:text-gray-100"}),r.jsx("span",{className:"text-sm text-gray-600 dark:text-gray-400",children:e("libraryPurge.days")})]})]}),r.jsxs("label",{className:"flex items-center gap-2 text-sm text-gray-700 dark:text-gray-300",children:[r.jsx("input",{type:"checkbox",checked:o,onChange:b=>l(b.target.checked),className:"rounded border-gray-300"}),e("libraryPurge.includeNeverPrinted")]}),r.jsxs("div",{className:"rounded border border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-800/30 p-3",children:[r.jsx("div",{className:"text-xs font-semibold uppercase tracking-wide text-gray-600 dark:text-gray-300 mb-2",children:e("libraryPurge.effectsTitle")}),r.jsxs("ul",{className:"text-xs text-gray-700 dark:text-gray-300 space-y-1 list-disc pl-4",children:[r.jsx("li",{children:e("libraryPurge.effect1")}),r.jsx("li",{children:e("libraryPurge.effect2")}),r.jsx("li",{children:e("libraryPurge.effect3")}),r.jsx("li",{children:e("libraryPurge.effect4")})]})]}),r.jsx("div",{className:"rounded border border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-800/50 p-3",children:u.isLoading||u.isFetching?r.jsxs("div",{className:"flex items-center gap-2 text-sm text-gray-500 dark:text-gray-400",children:[r.jsx(lt,{className:"w-4 h-4 animate-spin"})," ",e("libraryPurge.previewLoading")]}):u.isError?r.jsx("div",{className:"text-sm text-red-600 dark:text-red-400",children:u.error?.message??e("libraryPurge.previewFailed")}):r.jsxs("div",{className:"text-sm text-gray-900 dark:text-gray-100",children:[r.jsx("div",{className:"font-medium",children:e("libraryPurge.previewSummary",{count:f,size:cs(g)})}),p?.sample_filenames&&p.sample_filenames.length>0&&r.jsxs("ul",{className:"mt-2 text-xs text-gray-600 dark:text-gray-400 space-y-0.5 list-disc pl-4",children:[p.sample_filenames.map(b=>r.jsx("li",{className:"truncate",children:b},b)),f>p.sample_filenames.length&&r.jsx("li",{className:"list-none italic text-gray-500",children:e("libraryPurge.andMore",{count:f-p.sample_filenames.length})})]})]})}),r.jsxs("div",{className:"flex gap-2 items-start text-xs text-amber-700 dark:text-amber-400 bg-amber-50 dark:bg-amber-900/20 rounded px-3 py-2",children:[r.jsx(xa,{className:"w-4 h-4 mt-0.5 shrink-0"}),r.jsx("span",{children:e("libraryPurge.warning")})]})]}),r.jsxs("div",{className:"flex justify-end gap-2 p-4 border-t border-gray-200 dark:border-gray-700",children:[r.jsx(Le,{variant:"secondary",onClick:t,disabled:m.isPending,children:e("common.cancel")}),r.jsx(Le,{variant:"danger",disabled:!v,onClick:()=>m.mutate(),children:m.isPending?r.jsxs(r.Fragment,{children:[r.jsx(lt,{className:"w-4 h-4 animate-spin mr-1"}),e("libraryPurge.purging")]}):e("libraryPurge.confirmCta",{count:f})})]})]})})}function Dst({parentId:t,onClose:e,onSave:a,isLoading:n,t:i}){const[s,o]=y.useState(""),l=c=>{c.preventDefault(),a({name:s.trim(),parent_id:t})};return r.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:r.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-sm border border-bambu-dark-tertiary",children:[r.jsx("div",{className:"p-4 border-b border-bambu-dark-tertiary",children:r.jsx("h2",{className:"text-lg font-semibold text-white",children:i("fileManager.newFolder")})}),r.jsxs("form",{onSubmit:l,className:"p-4 space-y-4",children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:i("fileManager.folderName")}),r.jsx("input",{type:"text",value:s,onChange:c=>o(c.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:i("fileManager.folderNamePlaceholder"),autoFocus:!0,required:!0})]}),r.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[r.jsx(Le,{type:"button",variant:"secondary",onClick:e,children:i("common.cancel")}),r.jsx(Le,{type:"submit",disabled:!s.trim()||n,children:n?r.jsx(lt,{className:"w-4 h-4 animate-spin"}):i("common.create")})]})]})]})})}function Fst({onClose:t,onSave:e,isLoading:a,t:n}){const[i,s]=y.useState(""),[o,l]=y.useState(""),[c,d]=y.useState(!0),[u,m]=y.useState(!1),p=f=>{f.preventDefault(),e({name:i.trim(),external_path:o.trim(),readonly:c,show_hidden:u})};return r.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:r.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-md border border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"p-4 border-b border-bambu-dark-tertiary",children:[r.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[r.jsx(ow,{className:"w-5 h-5 text-bambu-green"}),n("fileManager.linkExternalFolder")]}),r.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:n("fileManager.linkExternalFolderDescription")})]}),r.jsxs("form",{onSubmit:p,className:"p-4 space-y-4",children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:n("fileManager.folderName")}),r.jsx("input",{type:"text",value:i,onChange:f=>s(f.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:n("fileManager.externalFolderNamePlaceholder"),autoFocus:!0,required:!0})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:n("fileManager.externalPath")}),r.jsx("input",{type:"text",value:o,onChange:f=>l(f.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green font-mono text-sm",placeholder:"/mnt/nas/3d-prints",required:!0}),r.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:n("fileManager.externalPathHelp")})]}),r.jsxs("div",{className:"space-y-2",children:[r.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[r.jsx("input",{type:"checkbox",checked:c,onChange:f=>d(f.target.checked),className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),r.jsx("span",{className:"text-sm text-white",children:n("fileManager.readOnly")}),r.jsxs("span",{className:"text-xs text-bambu-gray",children:["(",n("fileManager.readOnlyHelp"),")"]})]}),r.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[r.jsx("input",{type:"checkbox",checked:u,onChange:f=>m(f.target.checked),className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),r.jsx("span",{className:"text-sm text-white",children:n("fileManager.showHiddenFiles")})]})]}),r.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[r.jsx(Le,{type:"button",variant:"secondary",onClick:t,children:n("common.cancel")}),r.jsx(Le,{type:"submit",disabled:!i.trim()||!o.trim()||a,children:a?r.jsx(lt,{className:"w-4 h-4 animate-spin"}):n("fileManager.linkFolder")})]})]})]})})}const Lst='<>:"/\\|?*';function Rst(t){for(const e of t)if(Lst.includes(e)||e.charCodeAt(0)<32)return e;return null}function zst({type:t,currentName:e,onClose:a,onSave:n,isLoading:i,t:s}){const o=t==="file"?e.match(/(\.gcode\.3mf|\.3mf|\.gcode)$/i)?.[1]??"":"",l=t==="file"&&o?e.slice(0,-o.length):e,[c,d]=y.useState(l),u=t==="file"?Rst(c):null,m=u?s("fileManager.invalidFilenameChar",{char:u}):null,p=f=>{if(f.preventDefault(),m)return;const g=t==="file"?c.trim()+o:c.trim();c.trim()&&g!==e&&n(g)};return r.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:r.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-sm border border-bambu-dark-tertiary",children:[r.jsx("div",{className:"p-4 border-b border-bambu-dark-tertiary",children:r.jsx("h2",{className:"text-lg font-semibold text-white",children:s(t==="file"?"fileManager.renameFile":"fileManager.renameFolder")})}),r.jsxs("form",{onSubmit:p,className:"p-4 space-y-4",children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("common.name")}),r.jsxs("div",{className:`flex items-center bg-bambu-dark border rounded focus-within:border-bambu-green ${m?"border-red-500":"border-bambu-dark-tertiary"}`,children:[r.jsx("input",{type:"text",value:c,onChange:f=>d(f.target.value),className:"flex-1 bg-transparent px-3 py-2 text-white placeholder-bambu-gray focus:outline-none min-w-0",autoFocus:!0,required:!0}),o&&r.jsx("span",{className:"pr-3 text-bambu-gray text-sm select-none whitespace-nowrap",children:o})]}),m&&r.jsx("p",{className:"mt-1 text-xs text-red-400",children:m})]}),r.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[r.jsx(Le,{type:"button",variant:"secondary",onClick:a,children:s("common.cancel")}),r.jsx(Le,{type:"submit",disabled:!c.trim()||c.trim()===l||!!m||i,children:i?r.jsx(lt,{className:"w-4 h-4 animate-spin"}):s("common.rename")})]})]})]})})}function Ist({folders:t,selectedFiles:e,currentFolderId:a,onClose:n,onMove:i,isLoading:s,t:o}){const[l,c]=y.useState(null),d=(m,p=0)=>{const f=[];for(const g of m)f.push({id:g.id,name:g.name,depth:p}),g.children.length>0&&f.push(...d(g.children,p+1));return f},u=[{id:null,name:o("fileManager.rootNoFolder"),depth:0},...d(t)];return r.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:r.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-sm border border-bambu-dark-tertiary",children:[r.jsx("div",{className:"p-4 border-b border-bambu-dark-tertiary",children:r.jsx("h2",{className:"text-lg font-semibold text-white",children:o("fileManager.moveFiles",{count:e.length})})}),r.jsxs("div",{className:"p-4 space-y-4",children:[r.jsx("div",{className:"max-h-64 overflow-y-auto space-y-1",children:u.map(m=>r.jsxs("button",{onClick:()=>c(m.id),disabled:m.id===a,className:`w-full text-left px-3 py-2 rounded transition-colors flex items-center gap-2 ${l===m.id?"bg-bambu-green/20 text-bambu-green":m.id===a?"opacity-50 cursor-not-allowed text-bambu-gray":"hover:bg-bambu-dark text-white"}`,style:{paddingLeft:`${12+m.depth*16}px`},children:[r.jsx(Fl,{className:"w-4 h-4"}),m.name,m.id===a&&r.jsxs("span",{className:"text-xs text-bambu-gray ml-auto",children:["(",o("fileManager.current"),")"]})]},m.id??"root"))}),r.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[r.jsx(Le,{type:"button",variant:"secondary",onClick:n,children:o("common.cancel")}),r.jsx(Le,{onClick:()=>i(l),disabled:s,children:s?r.jsx(lt,{className:"w-4 h-4 animate-spin"}):o("common.move")})]})]})]})})}function Ost({folder:t,onClose:e,onLink:a,isLoading:n,t:i}){const[s,o]=y.useState("project"),[l,c]=y.useState(t.project_id||t.archive_id||null);y.useState(()=>{t.archive_id&&o("archive")});const{data:d}=$e({queryKey:["projects"],queryFn:()=>ne.getProjects(),select:g=>[...g].sort((v,b)=>v.name.localeCompare(b.name))}),{data:u}=$e({queryKey:["archives-for-link"],queryFn:()=>ne.getArchives(void 0,void 0,100)}),m=()=>{a(s==="project"?{project_id:l,archive_id:0}:{project_id:0,archive_id:l})},p=()=>{a({project_id:0,archive_id:0})},f=t.project_id||t.archive_id;return r.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:r.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-md border border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"p-4 border-b border-bambu-dark-tertiary flex items-center justify-between",children:[r.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[r.jsx(Oh,{className:"w-5 h-5 text-bambu-green"}),i("fileManager.linkFolder")]}),r.jsx("button",{onClick:e,className:"p-1 hover:bg-bambu-dark rounded",children:r.jsx(Ht,{className:"w-5 h-5 text-bambu-gray"})})]}),r.jsxs("div",{className:"p-4 space-y-4",children:[r.jsx("p",{className:"text-sm text-bambu-gray",children:i("fileManager.linkFolderDescription",{name:t.name})}),r.jsxs("div",{className:"flex gap-2",children:[r.jsxs("button",{onClick:()=>{o("project"),c(null)},className:`flex-1 flex items-center justify-center gap-2 px-3 py-2 rounded-lg border transition-colors ${s==="project"?"border-bambu-green bg-bambu-green/10 text-bambu-green":"border-bambu-dark-tertiary text-bambu-gray hover:text-white"}`,children:[r.jsx(rJ,{className:"w-4 h-4"}),i("fileManager.project")]}),r.jsxs("button",{onClick:()=>{o("archive"),c(null)},className:`flex-1 flex items-center justify-center gap-2 px-3 py-2 rounded-lg border transition-colors ${s==="archive"?"border-bambu-green bg-bambu-green/10 text-bambu-green":"border-bambu-dark-tertiary text-bambu-gray hover:text-white"}`,children:[r.jsx(ro,{className:"w-4 h-4"}),i("fileManager.archive")]})]}),r.jsx("div",{className:"max-h-64 overflow-y-auto space-y-1 bg-bambu-dark rounded-lg p-2",children:s==="project"?d&&d.length>0?d.map(g=>r.jsxs("button",{onClick:()=>c(g.id),className:`w-full text-left px-3 py-2 rounded transition-colors flex items-center gap-2 ${l===g.id?"bg-bambu-green/20 text-bambu-green":"hover:bg-bambu-dark-tertiary text-white"}`,children:[r.jsx("div",{className:"w-3 h-3 rounded-full flex-shrink-0",style:{backgroundColor:g.color||"#00ae42"}}),r.jsx("span",{className:"truncate",children:g.name})]},g.id)):r.jsx("p",{className:"text-sm text-bambu-gray text-center py-4",children:i("fileManager.noProjectsFound")}):u&&u.length>0?u.map(g=>r.jsxs("button",{onClick:()=>c(g.id),className:`w-full text-left px-3 py-2 rounded transition-colors flex items-center gap-2 ${l===g.id?"bg-bambu-green/20 text-bambu-green":"hover:bg-bambu-dark-tertiary text-white"}`,children:[r.jsx(Rh,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"}),r.jsx("span",{className:"truncate",children:g.print_name||g.filename})]},g.id)):r.jsx("p",{className:"text-sm text-bambu-gray text-center py-4",children:i("fileManager.noArchivesFound")})})]}),r.jsxs("div",{className:"p-4 border-t border-bambu-dark-tertiary flex justify-between",children:[f&&r.jsxs(Le,{variant:"danger",onClick:p,disabled:n,children:[r.jsx(mu,{className:"w-4 h-4 mr-2"}),i("fileManager.unlink")]}),r.jsxs("div",{className:`flex gap-2 ${f?"":"ml-auto"}`,children:[r.jsx(Le,{variant:"secondary",onClick:e,children:i("common.cancel")}),r.jsx(Le,{onClick:m,disabled:!l||n,children:n?r.jsx(lt,{className:"w-4 h-4 animate-spin"}):i("fileManager.link")})]})]})]})})}function jde({folder:t,selectedFolderId:e,onSelect:a,onDelete:n,onLink:i,onRename:s,depth:o=0,wrapNames:l=!1,defaultExpanded:c=!0,hasPermission:d,t:u}){const[m,p]=y.useState(c),[f,g]=y.useState(!1),v=t.children.length>0,b=t.project_id||t.archive_id,x=t.is_external;return r.jsxs("div",{children:[r.jsxs("div",{className:`group flex items-center gap-1 px-2 py-1.5 rounded cursor-pointer transition-colors ${e===t.id?"bg-bambu-green/20 text-bambu-green":"hover:bg-bambu-dark text-white"}`,style:{paddingLeft:`${8+o*12}px`},onClick:()=>a(t.id),children:[v?r.jsx("button",{onClick:S=>{S.stopPropagation(),p(!m)},className:"p-0.5 hover:bg-bambu-dark-tertiary rounded",children:r.jsx(Vn,{className:`w-3.5 h-3.5 transition-transform ${m?"rotate-90":""}`})}):r.jsx("div",{className:"w-4.5"}),x?r.jsx(ow,{className:"w-4 h-4 text-purple-400 flex-shrink-0"}):r.jsx(Fl,{className:"w-4 h-4 text-bambu-green flex-shrink-0"}),r.jsx("span",{className:`text-sm flex-1 min-w-0 ${l?"break-all":"truncate"}`,title:t.name,children:t.name}),b&&r.jsxs("button",{onClick:S=>{S.stopPropagation(),i(t)},className:"flex-shrink-0 flex items-center gap-1 text-xs px-1.5 py-0.5 rounded bg-blue-500/20 text-blue-400 hover:bg-blue-500/30 transition-colors",title:`${t.project_name?`Project: ${t.project_name}`:`Archive: ${t.archive_name}`} (click to change)`,children:[r.jsx(Oh,{className:"w-3 h-3"}),t.project_name?r.jsx(rJ,{className:"w-3 h-3"}):r.jsx(ro,{className:"w-3 h-3"})]}),x&&t.external_readonly&&r.jsx("span",{title:u("fileManager.readOnly"),children:r.jsx(mc,{className:"w-3 h-3 text-amber-400 flex-shrink-0"})}),t.file_count>0&&r.jsx("span",{className:"flex-shrink-0 text-xs text-bambu-gray",children:t.file_count}),!b&&!x&&r.jsx("button",{onClick:S=>{S.stopPropagation(),i(t)},className:"flex-shrink-0 p-1 rounded hover:bg-bambu-dark-tertiary",title:u("fileManager.linkToProjectOrArchive"),children:r.jsx(Oh,{className:"w-3.5 h-3.5 text-bambu-gray hover:text-bambu-green"})}),r.jsx("div",{className:`flex-shrink-0 flex items-center gap-0.5 transition-opacity ${l?"":"opacity-0 group-hover:opacity-100"}`,onClick:S=>S.stopPropagation(),children:r.jsxs("div",{className:"relative",children:[r.jsx("button",{onClick:()=>g(!f),className:"p-1 rounded hover:bg-bambu-dark-tertiary",children:r.jsx(Cm,{className:"w-3.5 h-3.5 text-bambu-gray"})}),f&&r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>g(!1)}),r.jsxs("div",{className:"absolute right-0 top-full mt-1 z-20 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl py-1 min-w-[120px]",children:[r.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${d("library:update_all")?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{d("library:update_all")&&(s(t),g(!1))},disabled:!d("library:update_all"),title:d("library:update_all")?void 0:u("fileManager.noPermissionRenameFolder"),children:[r.jsx(ci,{className:"w-3.5 h-3.5"}),u("common.rename")]}),r.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${d("library:update_all")?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{d("library:update_all")&&(i(t),g(!1))},disabled:!d("library:update_all"),title:d("library:update_all")?void 0:u("fileManager.noPermissionLinkFolder"),children:[r.jsx(Oh,{className:"w-3.5 h-3.5"}),u(b?"fileManager.changeLink":"fileManager.linkTo")]}),r.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${d("library:delete_all")?"text-red-400 hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{d("library:delete_all")&&(n(t.id),g(!1))},disabled:!d("library:delete_all"),title:d("library:delete_all")?void 0:u("fileManager.noPermissionDeleteFolder"),children:[r.jsx(na,{className:"w-3.5 h-3.5"}),u("common.delete")]})]})]})]})})]}),v&&m&&r.jsx("div",{children:t.children.map(S=>r.jsx(jde,{folder:S,selectedFolderId:e,onSelect:a,onDelete:n,onLink:i,onRename:s,depth:o+1,wrapNames:l,defaultExpanded:c,hasPermission:d,t:u},S.id))})]})}function Fw(t){const e=t.toLowerCase();return e.endsWith(".gcode")||e.endsWith(".gcode.3mf")}function gI(t){const e=t.toLowerCase();return e.endsWith(".gcode")||e.endsWith(".gcode.3mf")?!1:e.endsWith(".stl")||e.endsWith(".3mf")||e.endsWith(".step")||e.endsWith(".stp")}function Bst({file:t,isSelected:e,isMobile:a,onSelect:n,onDelete:i,onDownload:s,onAddToQueue:o,onPrint:l,onSlice:c,useSlicerApi:d,onPreview3d:u,onRename:m,onGenerateThumbnail:p,thumbnailVersion:f,hasPermission:g,canModify:v,authEnabled:b,t:x}){const[S,k]=y.useState(!1);return r.jsxs("div",{className:`group relative bg-bambu-dark-secondary rounded-lg border transition-all cursor-pointer overflow-hidden ${e?"border-bambu-green ring-1 ring-bambu-green":"border-bambu-dark-tertiary hover:border-bambu-green/50"}`,onClick:()=>n(t.id),children:[r.jsxs("div",{className:"aspect-square bg-bambu-dark flex items-center justify-center overflow-hidden",children:[t.thumbnail_path?r.jsx("img",{src:`${ne.getLibraryFileThumbnailUrl(t.id)}${f?(ne.getLibraryFileThumbnailUrl(t.id).includes("?")?"&":"?")+`v=${f}`:""}`,alt:t.filename,className:"w-full h-full object-cover"}):r.jsx(Rh,{className:"w-12 h-12 text-bambu-gray/30"}),r.jsx("div",{className:`absolute top-2 right-2 text-xs px-1.5 py-0.5 rounded font-medium ${t.file_type==="3mf"?"bg-bambu-green/90 text-white":t.file_type==="gcode"||t.file_type==="gcode.3mf"?"bg-blue-500/90 text-white":t.file_type==="stl"?"bg-purple-500/90 text-white":"bg-bambu-gray/90 text-white"}`,children:t.file_type.toUpperCase()})]}),r.jsxs("div",{className:"p-3",children:[r.jsx("h3",{className:"text-sm font-medium text-white truncate",title:t.print_name||t.filename,children:t.print_name||t.filename}),r.jsxs("div",{className:"flex items-center gap-3 mt-1 text-xs text-bambu-gray",children:[r.jsx("span",{children:cs(t.file_size)}),t.print_time_seconds&&r.jsxs("span",{className:"flex items-center gap-1",children:[r.jsx(ar,{className:"w-3 h-3"}),ds(t.print_time_seconds)]})]}),t.sliced_for_model&&r.jsxs("div",{className:"mt-1 text-xs text-bambu-gray flex items-center gap-1",children:[r.jsx(xr,{className:"w-3 h-3"}),t.sliced_for_model]}),t.print_count>0&&r.jsx("div",{className:"mt-1 text-xs text-bambu-green",children:x("fileManager.printedCount",{count:t.print_count})}),b&&t.created_by_username&&r.jsxs("div",{className:"mt-1 text-xs text-bambu-gray flex items-center gap-1",children:[r.jsx(Zm,{className:"w-3 h-3"}),t.created_by_username]})]}),r.jsxs("div",{className:`absolute bottom-2 right-2 transition-opacity ${a?"opacity-100":"opacity-0 group-hover:opacity-100"}`,onClick:P=>P.stopPropagation(),children:[r.jsx("button",{onClick:()=>k(!S),className:"p-1.5 rounded bg-bambu-dark-secondary/90 hover:bg-bambu-dark-tertiary",children:r.jsx(Cm,{className:"w-4 h-4 text-bambu-gray"})}),S&&r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>k(!1)}),r.jsxs("div",{className:"absolute right-0 bottom-8 z-20 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl py-1 min-w-[140px]",children:[l&&Fw(t.filename)&&r.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${g("printers:control")?"text-bambu-green hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{g("printers:control")&&(l(t),k(!1))},disabled:!g("printers:control"),title:g("printers:control")?void 0:x("fileManager.noPermissionPrint"),children:[r.jsx(xr,{className:"w-3.5 h-3.5"}),x("common.print")]}),o&&Fw(t.filename)&&r.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${g("queue:create")?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{g("queue:create")&&(o(t.id),k(!1))},disabled:!g("queue:create"),title:g("queue:create")?void 0:x("fileManager.noPermissionAddToQueue"),children:[r.jsx(ar,{className:"w-3.5 h-3.5"}),x("fileManager.schedulePrint")]}),c&&d&&gI(t.filename)&&r.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${g("library:upload")?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{g("library:upload")&&(c(t),k(!1))},disabled:!g("library:upload"),title:g("library:upload")?void 0:x("fileManager.noPermissionSlice"),children:[r.jsx(bd,{className:"w-3.5 h-3.5"}),x("slice.action")]}),u&&(t.file_type==="3mf"||t.file_type==="gcode"||t.file_type==="stl"||t.file_type==="gcode.3mf")&&r.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${g("library:read")?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{g("library:read")&&(u(t),k(!1))},disabled:!g("library:read"),title:g("library:read")?void 0:"You do not have permission to preview files",children:[r.jsx(Ei,{className:"w-3.5 h-3.5"}),"3D Preview"]}),r.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${g("library:read")?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{g("library:read")&&(s(t.id),k(!1))},disabled:!g("library:read"),title:g("library:read")?void 0:x("fileManager.noPermissionDownload"),children:[r.jsx(Ur,{className:"w-3.5 h-3.5"}),x("common.download")]}),m&&r.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${v("library","update",t.created_by_id)?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{v("library","update",t.created_by_id)&&(m(t),k(!1))},disabled:!v("library","update",t.created_by_id),title:v("library","update",t.created_by_id)?void 0:x("fileManager.noPermissionRenameFile"),children:[r.jsx(ci,{className:"w-3.5 h-3.5"}),x("common.rename")]}),p&&t.file_type==="stl"&&r.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${v("library","update",t.created_by_id)?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{v("library","update",t.created_by_id)&&(p(t),k(!1))},disabled:!v("library","update",t.created_by_id),title:v("library","update",t.created_by_id)?void 0:x("fileManager.noPermissionGenerateThumbnail"),children:[r.jsx(gu,{className:"w-3.5 h-3.5"}),x("fileManager.generateThumbnail")]}),r.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${v("library","delete",t.created_by_id)?"text-red-400 hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{v("library","delete",t.created_by_id)&&(i(t.id),k(!1))},disabled:!v("library","delete",t.created_by_id),title:v("library","delete",t.created_by_id)?void 0:x("fileManager.noPermissionDeleteFile"),children:[r.jsx(na,{className:"w-3.5 h-3.5"}),x("common.delete")]})]})]})]}),r.jsx("div",{className:`absolute top-2 left-2 w-5 h-5 rounded border-2 flex items-center justify-center transition-all ${e?"bg-bambu-green border-bambu-green":`border-white/30 bg-black/30 ${a?"opacity-100":"opacity-0 group-hover:opacity-100"}`}`,children:e&&r.jsx("div",{className:"w-2 h-2 bg-white rounded-sm"})})]})}function Ust(){const{t}=wt(),e=ia(),{showToast:a}=da(),{hasPermission:n,hasAnyPermission:i,canModify:s,authEnabled:o}=lr(),[l]=mb(),c=Ii(),d=l.get("folder"),u=d?parseInt(d,10):null,[m,p]=y.useState(u),[f,g]=y.useState("internal"),[v,b]=y.useState([]),[x,S]=y.useState(!1),[k,P]=y.useState(!1),[N,T]=y.useState(!1),[j,D]=y.useState(!1),[C,E]=y.useState(!1),[R,I]=y.useState(null),[O,z]=y.useState(null),[X,ae]=y.useState(null),[Y,ce]=y.useState(null),[de,oe]=y.useState(null),[K,ie]=y.useState(null),[ue,he]=y.useState(null),[ge,q]=y.useState({}),[Q,A]=y.useState(null),[F,B]=y.useState(()=>localStorage.getItem("library-view-mode")||"grid"),[W,H]=y.useState(()=>localStorage.getItem("library-wrap-folders")==="true"),[le,U]=y.useState(()=>localStorage.getItem("library-collapse-folders")==="true"),[G,Z]=y.useState(()=>{const Ae=localStorage.getItem("library-sidebar-width");return Ae?parseInt(Ae,10):256}),[J,re]=y.useState(!1),se=y.useRef(null);y.useEffect(()=>{if(!J)return;document.body.style.userSelect="none",document.body.style.cursor="col-resize";const Ae=ct=>{if(!se.current)return;const Ne=se.current.parentElement?.getBoundingClientRect();if(!Ne)return;const We=ct.clientX-Ne.left,st=Math.min(500,Math.max(200,We));Z(st)},we=()=>{re(!1),document.body.style.userSelect="",document.body.style.cursor="",localStorage.setItem("library-sidebar-width",String(G))};return document.addEventListener("mousemove",Ae),document.addEventListener("mouseup",we),()=>{document.removeEventListener("mousemove",Ae),document.removeEventListener("mouseup",we),document.body.style.userSelect="",document.body.style.cursor=""}},[J,G]);const[fe,me]=y.useState(""),[pe,V]=y.useState("all"),[L,te]=y.useState(""),[be,xe]=y.useState(()=>localStorage.getItem("library-sort-field")||"name"),[ve,De]=y.useState(()=>localStorage.getItem("library-sort-direction")||"asc"),je=Use();y.useEffect(()=>{const Ae=l.get("folder");if(Ae){const we=parseInt(Ae,10);p(we)}},[l]);const{data:Te}=$e({queryKey:["settings"],queryFn:()=>ne.getSettings()}),{data:qe,isLoading:Pe}=$e({queryKey:["library-folders"],queryFn:()=>ne.getLibraryFolders()}),{data:Ie}=$e({queryKey:["library-trash-count"],queryFn:async()=>{try{return(await ne.listLibraryTrash(1,0)).total}catch{return 0}},staleTime:3e4}),{data:Re,isLoading:Ue}=$e({queryKey:["library-files",m,f],queryFn:()=>ne.getLibraryFiles(m,!1,void 0,m===null?f:void 0)}),{data:ze}=$e({queryKey:["library-stats"],queryFn:()=>ne.getLibraryStats()}),{data:it}=$e({queryKey:["users"],queryFn:()=>ne.getUsers()}),Oe=y.useMemo(()=>{if(!Re)return[];const Ae=new Set(Re.map(we=>we.file_type));return Array.from(Ae).sort()},[Re]),tt=y.useMemo(()=>{if(!Re)return[];let Ae=[...Re];if(fe.trim()){const we=fe.toLowerCase();Ae=Ae.filter(ct=>ct.filename.toLowerCase().includes(we)||ct.print_name&&ct.print_name.toLowerCase().includes(we))}if(pe!=="all"&&(Ae=Ae.filter(we=>we.file_type===pe)),L.trim()){const we=L.toLowerCase();Ae=Ae.filter(ct=>ct.created_by_username&&ct.created_by_username.toLowerCase().includes(we))}return Ae.sort((we,ct)=>{let Ne=0;switch(be){case"name":Ne=(we.print_name||we.filename).localeCompare(ct.print_name||ct.filename);break;case"date":Ne=(Ga(we.created_at)?.getTime()??0)-(Ga(ct.created_at)?.getTime()??0);break;case"size":Ne=we.file_size-ct.file_size;break;case"type":Ne=we.file_type.localeCompare(ct.file_type);break;case"prints":Ne=we.print_count-ct.print_count;break}return ve==="asc"?Ne:-Ne}),Ae},[Re,fe,pe,L,be,ve]),Fe=y.useMemo(()=>{if(!ze||!Te)return!1;const Ae=(Te.library_disk_warning_gb||5)*1024*1024*1024;return ze.disk_free_bytesne.createLibraryFolder(Ae),onSuccess:()=>{e.invalidateQueries({queryKey:["library-folders"]}),S(!1),a(t("fileManager.toast.folderCreated"),"success")},onError:Ae=>a(Ae.message,"error")}),Ve=rt({mutationFn:async Ae=>{const we=await ne.createExternalFolder(Ae);return await ne.scanExternalFolder(we.id),we},onSuccess:Ae=>{e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-stats"]}),P(!1),p(Ae.id),a(t("fileManager.toast.externalFolderLinked"),"success")},onError:Ae=>a(Ae.message,"error")}),Me=rt({mutationFn:Ae=>ne.scanExternalFolder(Ae),onSuccess:Ae=>{e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-stats"]}),a(t("fileManager.toast.folderScanned",{added:Ae.added,removed:Ae.removed}),"success")},onError:Ae=>a(Ae.message,"error")}),Be=rt({mutationFn:Ae=>ne.deleteLibraryFolder(Ae),onSuccess:()=>{e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-stats"]}),m===O?.id&&p(null),z(null),a(t("fileManager.toast.folderDeleted"),"success")},onError:Ae=>{z(null),a(Ae.message,"error")}}),Qe=rt({mutationFn:Ae=>ne.deleteLibraryFile(Ae),onSuccess:()=>{e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-stats"]}),e.invalidateQueries({queryKey:["library-trash-count"]}),b(Ae=>Ae.filter(we=>we!==O?.id)),z(null),a(t("fileManager.toast.fileDeleted"),"success")},onError:Ae=>{z(null),a(Ae.message,"error")}}),Ge=rt({mutationFn:Ae=>ne.bulkDeleteLibrary(Ae,[]),onSuccess:(Ae,we)=>{e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-stats"]}),e.invalidateQueries({queryKey:["library-trash-count"]}),a(t("fileManager.toast.filesDeleted",{count:we.length}),"success"),b([]),z(null)},onError:Ae=>{z(null),a(Ae.message,"error")}}),Ee=rt({mutationFn:({fileIds:Ae,folderId:we})=>ne.moveLibraryFiles(Ae,we),onSuccess:()=>{e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-folders"]}),b([]),T(!1),a(t("fileManager.toast.filesMoved"),"success")},onError:Ae=>a(Ae.message,"error")}),at=rt({mutationFn:({id:Ae,data:we})=>ne.updateLibraryFolder(Ae,we),onSuccess:(Ae,we)=>{e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["project-folders"]}),e.invalidateQueries({queryKey:["archive-folders"]}),I(null);const ct=we.data.project_id===0&&we.data.archive_id===0;a(t(ct?"fileManager.toast.folderUnlinked":"fileManager.toast.folderLinked"),"success")},onError:Ae=>a(Ae.message,"error")}),Xe=rt({mutationFn:({id:Ae,filename:we})=>ne.updateLibraryFile(Ae,{filename:we}),onSuccess:()=>{e.invalidateQueries({queryKey:["library-files"]}),he(null),a(t("fileManager.toast.fileRenamed"),"success")},onError:Ae=>{he(null),a(Ae.message,"error")}}),Nt=rt({mutationFn:({id:Ae,name:we})=>ne.updateLibraryFolder(Ae,{name:we}),onSuccess:()=>{e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-files"]}),he(null),a(t("fileManager.toast.folderRenamed"),"success")},onError:Ae=>{he(null),a(Ae.message,"error")}}),Vt=rt({mutationFn:()=>ne.batchGenerateStlThumbnails({all_missing:!0}),onSuccess:Ae=>{if(e.invalidateQueries({queryKey:["library-files"]}),Ae.succeeded>0){const we=Date.now(),ct={};Ae.results.forEach(Ne=>{Ne.success&&(ct[Ne.file_id]=we)}),q(Ne=>({...Ne,...ct}))}Ae.succeeded>0&&Ae.failed===0?a(t("fileManager.toast.thumbnailsGenerated",{count:Ae.succeeded}),"success"):Ae.succeeded>0&&Ae.failed>0?a(t("fileManager.toast.thumbnailsGeneratedPartial",{succeeded:Ae.succeeded,failed:Ae.failed}),"success"):Ae.processed===0?a(t("fileManager.toast.noStlMissingThumbnails"),"info"):a(t("fileManager.toast.failedToGenerateThumbnails",{error:Ae.results[0]?.error||"Unknown error"}),"error")},onError:Ae=>a(Ae.message,"error")}),ht=rt({mutationFn:Ae=>ne.batchGenerateStlThumbnails({file_ids:[Ae]}),onSuccess:Ae=>{if(e.invalidateQueries({queryKey:["library-files"]}),Ae.succeeded>0){const we=Ae.results[0]?.file_id;we&&q(ct=>({...ct,[we]:Date.now()})),a(t("fileManager.toast.thumbnailGenerated"),"success")}else a(t("fileManager.toast.failedToGenerateThumbnail",{error:Ae.results[0]?.error||"Unknown error"}),"error")},onError:Ae=>a(Ae.message,"error")}),It=y.useCallback(Ae=>{const we=Ae.toLowerCase();return we.endsWith(".gcode")||we.includes(".gcode.")},[]),Xt=y.useMemo(()=>Re?Re.filter(Ae=>v.includes(Ae.id)&&It(Ae.filename)):[],[Re,v,It]),oa=y.useCallback(Ae=>{b(we=>we.includes(Ae)?we.filter(ct=>ct!==Ae):[...we,Ae])},[]),la=y.useCallback(()=>{tt.length>0&&b(tt.map(Ae=>Ae.id))},[tt]),ot=y.useCallback(()=>{b([])},[]),vt=()=>{e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-stats"]})},Pt=Ae=>{ne.downloadLibraryFile(Ae).catch(we=>{console.error("Library file download failed:",we)})},ea=()=>{O&&(O.type==="file"?Qe.mutate(O.id):O.type==="folder"?Be.mutate(O.id):O.type==="bulk"&&Ge.mutate(v))},aa=Be.isPending||Qe.isPending||Ge.isPending,Ce=Ae=>{B(Ae),localStorage.setItem("library-view-mode",Ae)},Ke=Pe||Ue,nt=y.useMemo(()=>{if(!m||!qe)return null;const Ae=we=>{for(const ct of we){if(ct.id===m)return ct;const Ne=Ae(ct.children);if(Ne)return Ne}return null};return Ae(qe)},[m,qe]);return r.jsxs("div",{className:"p-4 md:p-8 min-h-[calc(100vh-64px)] lg:h-[calc(100vh-64px)] flex flex-col",children:[r.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4 mb-6",children:[r.jsxs("div",{children:[r.jsxs("h1",{className:"text-2xl font-bold text-white flex items-center gap-3",children:[r.jsx(Fl,{className:"w-7 h-7 text-bambu-green"}),t("fileManager.title")]}),r.jsx("p",{className:"text-bambu-gray mt-1",children:t("fileManager.subtitle")})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsxs("div",{className:"flex items-center bg-bambu-dark rounded-lg p-1",children:[r.jsx("button",{onClick:()=>Ce("grid"),className:`p-1.5 rounded transition-colors ${F==="grid"?"bg-bambu-dark-secondary text-white":"text-bambu-gray hover:text-white"}`,title:t("fileManager.gridView"),children:r.jsx(OS,{className:"w-4 h-4"})}),r.jsx("button",{onClick:()=>Ce("list"),className:`p-1.5 rounded transition-colors ${F==="list"?"bg-bambu-dark-secondary text-white":"text-bambu-gray hover:text-white"}`,title:t("fileManager.listView"),children:r.jsx(BS,{className:"w-4 h-4"})})]}),r.jsxs(Le,{variant:"secondary",onClick:()=>Vt.mutate(),disabled:Vt.isPending||!i("library:update_own","library:update_all"),title:i("library:update_own","library:update_all")?t("fileManager.generateThumbnailsForMissing"):t("fileManager.noPermissionGenerateThumbnail"),children:[Vt.isPending?r.jsx(lt,{className:"w-4 h-4 mr-2 animate-spin"}):r.jsx(gu,{className:"w-4 h-4 mr-2"}),t("fileManager.generateThumbnails")]}),r.jsxs(Le,{variant:"secondary",onClick:()=>P(!0),disabled:!n("library:upload"),title:n("library:upload")?t("fileManager.linkExternalFolder"):t("fileManager.noPermissionCreateFolder"),children:[r.jsx(ow,{className:"w-4 h-4 mr-2"}),t("fileManager.linkExternal")]}),r.jsxs(Le,{variant:"secondary",onClick:()=>S(!0),disabled:!n("library:upload"),title:n("library:upload")?void 0:t("fileManager.noPermissionCreateFolder"),children:[r.jsx(nxe,{className:"w-4 h-4 mr-2"}),t("fileManager.newFolder")]}),n("library:purge")&&r.jsxs(Le,{variant:"secondary",onClick:()=>E(!0),title:t("libraryPurge.headerTooltip"),children:[r.jsx(na,{className:"w-4 h-4 mr-2"}),t("libraryPurge.headerButton")]}),i("library:delete_own","library:delete_all")&&r.jsxs(Ls,{to:"/files/trash",className:"inline-flex items-center px-3 py-1.5 text-sm rounded bg-bambu-dark-secondary text-bambu-gray hover:text-white hover:bg-bambu-dark transition-colors",title:t("libraryTrash.headerTooltip"),children:[r.jsx(na,{className:"w-4 h-4 mr-2"}),t("libraryTrash.headerButton"),typeof Ie=="number"&&Ie>0&&r.jsx("span",{className:"ml-1.5 px-1.5 py-0.5 text-xs rounded-full bg-bambu-green/20 text-bambu-green",children:Ie})]}),r.jsxs(Le,{onClick:()=>D(!0),disabled:!n("library:upload"),title:n("library:upload")?void 0:t("fileManager.noPermissionUpload"),children:[r.jsx(Sn,{className:"w-4 h-4 mr-2"}),t("common.upload")]})]})]}),Fe&&ze&&Te&&r.jsxs("div",{className:"flex items-center gap-3 mb-4 p-3 bg-amber-500/10 border border-amber-500/30 rounded-lg",children:[r.jsx(xa,{className:"w-5 h-5 text-amber-500 flex-shrink-0"}),r.jsxs("div",{className:"flex-1",children:[r.jsx("p",{className:"text-sm text-amber-500 font-medium",children:t("fileManager.lowDiskSpaceWarning")}),r.jsx("p",{className:"text-xs text-amber-500/80",children:t("fileManager.lowDiskSpaceDetails",{free:cs(ze.disk_free_bytes),total:cs(ze.disk_total_bytes),threshold:Te.library_disk_warning_gb})})]})]}),ze&&r.jsxs("div",{className:"flex flex-wrap items-center gap-3 sm:gap-6 mb-6 p-3 bg-bambu-dark-secondary rounded-lg border border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[r.jsx(FT,{className:"w-4 h-4 text-bambu-green"}),r.jsxs("span",{className:"text-bambu-gray",children:[t("fileManager.files"),":"]}),r.jsx("span",{className:"text-white font-medium",children:ze.total_files})]}),r.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[r.jsx(Fl,{className:"w-4 h-4 text-blue-400"}),r.jsxs("span",{className:"text-bambu-gray",children:[t("fileManager.folders"),":"]}),r.jsx("span",{className:"text-white font-medium",children:ze.total_folders})]}),r.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[r.jsx(hb,{className:"w-4 h-4 text-amber-400"}),r.jsxs("span",{className:"text-bambu-gray",children:[t("fileManager.size"),":"]}),r.jsx("span",{className:"text-white font-medium",children:cs(ze.total_size_bytes)})]}),r.jsxs("div",{className:"flex items-center gap-2 text-sm sm:ml-auto",children:[r.jsxs("span",{className:"text-bambu-gray",children:[t("fileManager.free"),":"]}),r.jsx("span",{className:`font-medium ${Fe?"text-amber-500":"text-white"}`,children:cs(ze.disk_free_bytes)})]})]}),r.jsxs("div",{className:"flex-1 flex flex-col lg:flex-row gap-4 lg:gap-6 min-h-0",children:[r.jsx("div",{className:"lg:hidden",children:r.jsxs("select",{value:m!==null?String(m):`__top:${f}`,onChange:Ae=>{const we=Ae.target.value;we.startsWith("__top:")?(p(null),g(we.slice(6))):p(parseInt(we,10))},className:"w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg px-3 py-2.5 text-white focus:outline-none focus:border-bambu-green",children:[r.jsxs("option",{value:"__top:internal",children:["📁 ",t("fileManager.allFiles")]}),qe?.some(Ae=>Ae.is_external)&&r.jsxs("option",{value:"__top:external",children:["🔗 ",t("fileManager.allExternal")]}),qe&&(()=>{const Ae=(we,ct=0)=>{const Ne=[];for(const We of we)Ne.push({id:We.id,name:We.name,fileCount:We.file_count,depth:ct}),We.children.length>0&&Ne.push(...Ae(We.children,ct+1));return Ne};return Ae(qe).map(we=>r.jsxs("option",{value:we.id,children:["│ ".repeat(we.depth),"📂 ",we.name," ",we.fileCount>0?`(${we.fileCount})`:""]},we.id))})()]})}),r.jsxs("div",{ref:se,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:`${G}px`},children:[r.jsx("div",{className:`absolute right-0 top-0 bottom-0 w-1.5 cursor-col-resize z-10 group/resize flex items-center justify-center transition-colors ${J?"bg-bambu-green":"hover:bg-bambu-green/50"}`,onMouseDown:Ae=>{Ae.preventDefault(),re(!0)},onDoubleClick:()=>{Z(256),localStorage.setItem("library-sidebar-width","256")},title:t("fileManager.dragToResizeTooltip"),children:r.jsxs("div",{className:`flex flex-col gap-1 opacity-0 group-hover/resize:opacity-100 transition-opacity ${J?"opacity-100":""}`,children:[r.jsx("div",{className:"w-0.5 h-0.5 rounded-full bg-white/70"}),r.jsx("div",{className:"w-0.5 h-0.5 rounded-full bg-white/70"}),r.jsx("div",{className:"w-0.5 h-0.5 rounded-full bg-white/70"})]})}),r.jsxs("div",{className:"p-3 border-b border-bambu-dark-tertiary flex items-center justify-between",children:[r.jsx("h2",{className:"text-sm font-medium text-white",children:t("fileManager.folders")}),r.jsxs("div",{className:"flex items-center gap-1",children:[r.jsx("button",{onClick:()=>{const Ae=!le;U(Ae),localStorage.setItem("library-collapse-folders",String(Ae))},className:`text-xs px-1.5 py-0.5 rounded transition-colors ${le?"bg-bambu-green/20 text-bambu-green":"text-bambu-gray hover:text-white hover:bg-bambu-dark"}`,title:t(le?"fileManager.expandFoldersByDefault":"fileManager.collapseFoldersByDefault"),children:t("fileManager.collapse")}),r.jsx("button",{onClick:()=>{const Ae=!W;H(Ae),localStorage.setItem("library-wrap-folders",String(Ae))},className:`text-xs px-1.5 py-0.5 rounded transition-colors ${W?"bg-bambu-green/20 text-bambu-green":"text-bambu-gray hover:text-white hover:bg-bambu-dark"}`,title:t(W?"fileManager.disableTextWrapping":"fileManager.enableTextWrapping"),children:t("fileManager.wrap")})]})]}),r.jsxs("div",{className:"flex-1 overflow-y-auto p-2",children:[r.jsxs("div",{className:`flex items-center gap-2 px-2 py-1.5 rounded cursor-pointer transition-colors ${m===null&&f==="internal"?"bg-bambu-green/20 text-bambu-green":"hover:bg-bambu-dark text-white"}`,onClick:()=>{p(null),g("internal")},children:[r.jsx(Rh,{className:"w-4 h-4"}),r.jsx("span",{className:"text-sm",children:t("fileManager.allFiles")})]}),qe?.some(Ae=>Ae.is_external)&&r.jsxs("div",{className:`flex items-center gap-2 px-2 py-1.5 rounded cursor-pointer transition-colors ${m===null&&f==="external"?"bg-bambu-green/20 text-bambu-green":"hover:bg-bambu-dark text-white"}`,onClick:()=>{p(null),g("external")},children:[r.jsx(ow,{className:"w-4 h-4 text-purple-400"}),r.jsx("span",{className:"text-sm",children:t("fileManager.allExternal")})]}),qe?.map(Ae=>r.jsx(jde,{folder:Ae,selectedFolderId:m,onSelect:p,onDelete:we=>z({type:"folder",id:we}),onLink:I,onRename:we=>he({type:"folder",id:we.id,name:we.name}),wrapNames:W,defaultExpanded:!le,hasPermission:n,t},`${Ae.id}-${le?"c":"e"}`))]})]}),r.jsxs("div",{className:"flex-1 flex flex-col min-w-0 min-h-0",children:[nt?.is_external&&r.jsxs("div",{className:"flex items-center gap-3 mb-4 p-3 bg-purple-500/10 border border-purple-500/30 rounded-lg",children:[r.jsx(ow,{className:"w-5 h-5 text-purple-400 flex-shrink-0"}),r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("span",{className:"text-sm font-medium text-purple-300",children:t("fileManager.externalFolder")}),nt.external_readonly&&r.jsxs("span",{className:"text-xs px-1.5 py-0.5 rounded bg-amber-500/20 text-amber-400 flex items-center gap-1",children:[r.jsx(mc,{className:"w-3 h-3"}),t("fileManager.readOnly")]})]}),r.jsx("p",{className:"text-xs text-bambu-gray truncate font-mono",title:nt.external_path||"",children:nt.external_path})]}),r.jsxs(Le,{variant:"secondary",size:"sm",onClick:()=>m&&Me.mutate(m),disabled:Me.isPending,title:t("fileManager.scanFolder"),children:[Me.isPending?r.jsx(lt,{className:"w-4 h-4 animate-spin"}):r.jsx(tr,{className:"w-4 h-4"}),r.jsx("span",{className:"ml-1.5",children:t("fileManager.scanFolder")})]})]}),Re&&Re.length>0&&r.jsxs("div",{className:"flex flex-wrap items-center gap-2 sm:gap-3 mb-4 p-2 sm:p-3 bg-bambu-dark-secondary rounded-lg border border-bambu-dark-tertiary sticky top-0 z-10 lg:static",children:[r.jsxs("div",{className:"relative w-full sm:w-auto sm:flex-1 sm:max-w-xs",children:[r.jsx(br,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),r.jsx("input",{type:"text",placeholder:t("fileManager.searchFiles"),value:fe,onChange:Ae=>me(Ae.target.value),className:"w-full pl-9 pr-3 py-1.5 bg-bambu-dark border border-bambu-dark-tertiary rounded text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green"})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(av,{className:"w-4 h-4 text-bambu-gray hidden sm:block"}),r.jsxs("select",{value:pe,onChange:Ae=>V(Ae.target.value),className:"bg-bambu-dark border border-bambu-dark-tertiary rounded px-2 py-1.5 text-sm text-white focus:outline-none focus:border-bambu-green",children:[r.jsx("option",{value:"all",children:t("fileManager.allTypes")}),Oe.map(Ae=>r.jsx("option",{value:Ae,children:Ae.toUpperCase()},Ae))]})]}),o&&r.jsxs("div",{className:"relative",children:[r.jsx("input",{type:"text",placeholder:t("fileManager.filterByUser",{defaultValue:"Filter by user"}),value:L,onChange:Ae=>te(Ae.target.value),list:"usernames-list",className:`w-32 sm:w-40 px-2 py-1.5 bg-bambu-dark border border-bambu-dark-tertiary rounded text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green ${L?"pr-7":""}`,style:L?{WebkitAppearance:"none",MozAppearance:"textfield"}:void 0}),L&&r.jsx("button",{onClick:()=>te(""),className:"absolute right-2 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white z-10",children:r.jsx(Ht,{className:"w-3 h-3"})}),r.jsx("datalist",{id:"usernames-list",children:it?.map(Ae=>r.jsx("option",{value:Ae.username},Ae.id))})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsxs("select",{value:be,onChange:Ae=>{const we=Ae.target.value;xe(we),localStorage.setItem("library-sort-field",we)},className:"bg-bambu-dark border border-bambu-dark-tertiary rounded px-2 py-1.5 text-sm text-white focus:outline-none focus:border-bambu-green",children:[r.jsx("option",{value:"name",children:t("common.name")}),r.jsx("option",{value:"date",children:t("common.date")}),r.jsx("option",{value:"size",children:t("fileManager.size")}),r.jsx("option",{value:"type",children:t("common.type")}),r.jsx("option",{value:"prints",children:t("fileManager.prints")})]}),r.jsx("button",{onClick:()=>De(Ae=>{const we=Ae==="asc"?"desc":"asc";return localStorage.setItem("library-sort-direction",we),we}),className:"p-1.5 rounded bg-bambu-dark border border-bambu-dark-tertiary hover:border-bambu-green transition-colors",title:t(ve==="asc"?"fileManager.ascending":"fileManager.descending"),children:ve==="asc"?r.jsx(sge,{className:"w-4 h-4 text-white"}):r.jsx(Jfe,{className:"w-4 h-4 text-white"})})]}),(fe||pe!=="all"||L)&&r.jsx("span",{className:"text-sm text-bambu-gray hidden sm:inline",children:t("fileManager.resultsCount",{showing:tt.length,total:Re.length})})]}),tt.length>0&&r.jsxs("div",{className:"flex flex-wrap items-center gap-2 mb-4 p-2 bg-bambu-dark-secondary rounded-lg border border-bambu-dark-tertiary sticky top-[52px] z-10 lg:static",children:[v.length===tt.length&&v.length>0?r.jsxs(Le,{variant:"secondary",size:"sm",onClick:ot,children:[r.jsx(so,{className:"w-4 h-4 sm:mr-1"}),r.jsx("span",{className:"hidden sm:inline",children:t("fileManager.deselectAll")})]}):r.jsxs(Le,{variant:"secondary",size:"sm",onClick:la,children:[r.jsx(xs,{className:"w-4 h-4 sm:mr-1"}),r.jsx("span",{className:"hidden sm:inline",children:t("fileManager.selectAll")})]}),v.length>0&&r.jsxs(r.Fragment,{children:[r.jsx("span",{className:"text-sm text-bambu-gray ml-2",children:t("fileManager.selected",{count:v.length})}),r.jsx("div",{className:"hidden sm:block flex-1"}),r.jsxs("div",{className:"w-full sm:w-auto flex flex-wrap items-center gap-2 mt-2 sm:mt-0",children:[Xt.length===1&&r.jsxs(Le,{variant:"primary",size:"sm",onClick:()=>ce(Xt[0]),disabled:!n("printers:control"),title:n("printers:control")?void 0:t("fileManager.noPermissionPrint"),children:[r.jsx(gs,{className:"w-4 h-4 sm:mr-1"}),r.jsx("span",{className:"hidden sm:inline",children:t("common.print")})]}),Xt.length===1&&r.jsxs(Le,{variant:"secondary",size:"sm",onClick:()=>oe(Xt[0]),disabled:!n("queue:create"),title:n("queue:create")?void 0:t("fileManager.noPermissionAddToQueue"),children:[r.jsx(ar,{className:"w-4 h-4 sm:mr-1"}),r.jsx("span",{className:"hidden sm:inline",children:t("fileManager.schedulePrint")})]}),r.jsxs(Le,{variant:"secondary",size:"sm",onClick:()=>T(!0),disabled:!i("library:update_own","library:update_all"),title:i("library:update_own","library:update_all")?void 0:t("fileManager.noPermissionMoveFiles"),children:[r.jsx(vye,{className:"w-4 h-4 sm:mr-1"}),r.jsx("span",{className:"hidden sm:inline",children:t("common.move")})]}),r.jsxs(Le,{variant:"danger",size:"sm",onClick:()=>{v.length===1?z({type:"file",id:v[0]}):z({type:"bulk",id:0,count:v.length})},disabled:!i("library:delete_own","library:delete_all"),title:i("library:delete_own","library:delete_all")?void 0:t("fileManager.noPermissionDeleteFiles"),children:[r.jsx(na,{className:"w-4 h-4 sm:mr-1"}),r.jsx("span",{className:"hidden sm:inline",children:t("common.delete")})]}),r.jsxs(Le,{variant:"secondary",size:"sm",onClick:ot,children:[r.jsx(Ht,{className:"w-4 h-4 sm:mr-1"}),r.jsx("span",{className:"hidden sm:inline",children:t("common.clear")})]})]})]})]}),Ke?r.jsx("div",{className:"flex-1 flex items-center justify-center",children:r.jsxs("div",{className:"flex flex-col items-center gap-3",children:[r.jsx(lt,{className:"w-8 h-8 animate-spin text-bambu-green"}),r.jsx("p",{className:"text-sm text-bambu-gray",children:t("fileManager.loadingFiles")})]})}):Re?.length===0?r.jsxs("div",{className:"flex-1 flex flex-col items-center justify-center",children:[r.jsx("div",{className:"p-4 bg-bambu-dark rounded-2xl mb-4",children:r.jsx(Rh,{className:"w-12 h-12 text-bambu-gray/50"})}),r.jsx("h3",{className:"text-lg font-medium text-white mb-2",children:t(m!==null?"fileManager.folderIsEmpty":f==="external"?"fileManager.externalIsEmpty":"fileManager.noFilesYet")}),r.jsx("p",{className:"text-bambu-gray text-center max-w-md mb-6",children:t(m!==null?"fileManager.folderEmptyDescription":f==="external"?"fileManager.externalEmptyDescription":"fileManager.noFilesDescription")}),r.jsxs(Le,{onClick:()=>D(!0),disabled:!n("library:upload"),title:n("library:upload")?void 0:t("fileManager.noPermissionUpload"),children:[r.jsx(or,{className:"w-4 h-4 mr-2"}),t("fileManager.uploadFiles")]})]}):tt.length===0?r.jsxs("div",{className:"flex-1 flex flex-col items-center justify-center",children:[r.jsx("div",{className:"p-4 bg-bambu-dark rounded-2xl mb-4",children:r.jsx(br,{className:"w-12 h-12 text-bambu-gray/50"})}),r.jsx("h3",{className:"text-lg font-medium text-white mb-2",children:t("fileManager.noMatchingFiles")}),r.jsx("p",{className:"text-bambu-gray text-center max-w-md mb-6",children:t("fileManager.noMatchingFilesDescription")}),r.jsx(Le,{variant:"secondary",onClick:()=>{me(""),V("all")},children:t("fileManager.clearFilters")})]}):F==="grid"?r.jsx("div",{className:"flex-1 lg:overflow-y-auto",children:r.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 2xl:grid-cols-6 gap-4",children:tt.map(Ae=>r.jsx(Bst,{file:Ae,isSelected:v.includes(Ae.id),isMobile:je,t,onSelect:oa,onDelete:we=>z({type:"file",id:we}),onDownload:Pt,onAddToQueue:we=>{const ct=Re?.find(Ne=>Ne.id===we);ct&&oe(ct)},onPrint:ae,onSlice:ie,useSlicerApi:Te?.use_slicer_api??!1,onPreview3d:we=>{Fw(we.filename)?c(`/gcode-viewer?library_file=${we.id}`):A(we)},onRename:we=>he({type:"file",id:we.id,name:we.filename}),onGenerateThumbnail:we=>ht.mutate(we.id),thumbnailVersion:ge[Ae.id],hasPermission:n,canModify:s,authEnabled:o},Ae.id))})}):r.jsx("div",{className:"flex-1 lg:overflow-y-auto",children:r.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg border border-bambu-dark-tertiary overflow-x-auto",children:[r.jsxs("div",{className:`hidden sm:grid ${o?"grid-cols-[auto_1fr_120px_100px_100px_100px_min-content]":"grid-cols-[auto_1fr_100px_100px_100px_min-content]"} gap-4 px-4 py-2 bg-bambu-dark-secondary border-b border-bambu-dark-tertiary text-xs text-bambu-gray font-medium`,children:[r.jsx("div",{className:"w-6"}),r.jsx("div",{children:t("common.name")}),o&&r.jsx("div",{children:t("fileManager.uploadedBy",{defaultValue:"Uploaded By"})}),r.jsx("div",{children:t("common.type")}),r.jsx("div",{children:t("fileManager.size")}),r.jsx("div",{children:t("fileManager.prints")}),r.jsx("div",{})]}),tt.map(Ae=>r.jsxs("div",{className:`grid ${o?"grid-cols-[auto_1fr_120px_100px_100px_100px_min-content]":"grid-cols-[auto_1fr_100px_100px_100px_min-content]"} 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 ${v.includes(Ae.id)?"bg-bambu-green/10":""}`,onClick:()=>oa(Ae.id),children:[r.jsx("div",{className:`w-5 h-5 rounded border-2 flex items-center justify-center ${v.includes(Ae.id)?"bg-bambu-green border-bambu-green":"border-bambu-gray/50"}`,children:v.includes(Ae.id)&&r.jsx("div",{className:"w-2 h-2 bg-white rounded-sm"})}),r.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[r.jsxs("div",{className:"relative group/thumb",children:[r.jsx("div",{className:"w-10 h-10 rounded bg-bambu-dark flex-shrink-0 overflow-hidden",children:Ae.thumbnail_path?r.jsx("img",{src:`${ne.getLibraryFileThumbnailUrl(Ae.id)}${ge[Ae.id]?(ne.getLibraryFileThumbnailUrl(Ae.id).includes("?")?"&":"?")+`v=${ge[Ae.id]}`:""}`,alt:"",className:"w-full h-full object-cover"}):r.jsx("div",{className:"w-full h-full flex items-center justify-center",children:r.jsx(Rh,{className:"w-5 h-5 text-bambu-gray/50"})})}),Ae.thumbnail_path&&r.jsx("div",{className:"absolute left-0 top-full mt-2 z-50 hidden group-hover/thumb:block",children:r.jsx("div",{className:"w-48 h-48 rounded-lg bg-bambu-dark-secondary border border-bambu-dark-tertiary shadow-xl overflow-hidden",children:r.jsx("img",{src:`${ne.getLibraryFileThumbnailUrl(Ae.id)}${ge[Ae.id]?(ne.getLibraryFileThumbnailUrl(Ae.id).includes("?")?"&":"?")+`v=${ge[Ae.id]}`:""}`,alt:Ae.filename,className:"w-full h-full object-contain"})})})]}),r.jsx("div",{className:"min-w-0",children:r.jsx("div",{className:"text-sm text-white truncate",children:Ae.print_name||Ae.filename})})]}),o&&r.jsx("div",{className:"text-sm text-bambu-gray flex items-center gap-1",children:Ae.created_by_username?r.jsxs(r.Fragment,{children:[r.jsx(Zm,{className:"w-3 h-3"}),r.jsx("span",{className:"truncate",children:Ae.created_by_username})]}):"-"}),r.jsx("div",{children:r.jsx("span",{className:`text-xs px-1.5 py-0.5 rounded font-medium ${Ae.file_type==="3mf"?"bg-bambu-green/20 text-bambu-green":Ae.file_type==="gcode"?"bg-blue-500/20 text-blue-400":Ae.file_type==="stl"?"bg-purple-500/20 text-purple-400":"bg-bambu-gray/20 text-bambu-gray"}`,children:Ae.file_type.toUpperCase()})}),r.jsx("div",{className:"text-sm text-bambu-gray",children:cs(Ae.file_size)}),r.jsx("div",{className:"text-sm text-bambu-gray",children:Ae.print_count>0?`${Ae.print_count}x`:"-"}),r.jsxs("div",{className:"flex items-center gap-1",onClick:we=>we.stopPropagation(),children:[Fw(Ae.filename)&&r.jsxs(r.Fragment,{children:[r.jsx("button",{onClick:()=>n("printers:control")&&ae(Ae),className:`p-1.5 rounded transition-colors ${n("printers:control")?"hover:bg-bambu-dark text-bambu-gray hover:text-bambu-green":"text-bambu-gray/50 cursor-not-allowed"}`,title:n("printers:control")?t("common.print"):t("fileManager.noPermissionPrint"),disabled:!n("printers:control"),children:r.jsx(xr,{className:"w-4 h-4"})}),r.jsx("button",{onClick:()=>{n("queue:create")&&oe(Ae)},className:`p-1.5 rounded transition-colors ${n("queue:create")?"hover:bg-bambu-dark text-bambu-gray hover:text-white":"text-bambu-gray/50 cursor-not-allowed"}`,title:n("queue:create")?t("fileManager.schedulePrint"):t("fileManager.noPermissionAddToQueue"),disabled:!n("queue:create"),children:r.jsx(ar,{className:"w-4 h-4"})})]}),(Te?.use_slicer_api??!1)&&gI(Ae.filename)&&r.jsx("button",{onClick:()=>n("library:upload")&&ie(Ae),className:`p-1.5 rounded transition-colors ${n("library:upload")?"hover:bg-bambu-dark text-bambu-gray hover:text-bambu-green":"text-bambu-gray/50 cursor-not-allowed"}`,title:n("library:upload")?t("slice.action"):t("fileManager.noPermissionSlice"),disabled:!n("library:upload"),children:r.jsx(bd,{className:"w-4 h-4"})}),(Ae.file_type==="3mf"||Ae.file_type==="gcode"||Ae.file_type==="stl")&&r.jsx("button",{onClick:()=>{n("library:read")&&(Fw(Ae.filename)?c(`/gcode-viewer?library_file=${Ae.id}`):A(Ae))},className:`p-1.5 rounded transition-colors ${n("library:read")?"hover:bg-bambu-dark text-bambu-gray hover:text-bambu-green":"text-bambu-gray/50 cursor-not-allowed"}`,title:n("library:read")?"3D Preview":"You do not have permission to preview files",disabled:!n("library:read"),children:r.jsx(Ei,{className:"w-4 h-4"})}),r.jsx("button",{onClick:()=>n("library:read")&&Pt(Ae.id),className:`p-1.5 rounded transition-colors ${n("library:read")?"hover:bg-bambu-dark text-bambu-gray hover:text-white":"text-bambu-gray/50 cursor-not-allowed"}`,title:n("library:read")?t("common.download"):t("fileManager.noPermissionDownload"),disabled:!n("library:read"),children:r.jsx(Ur,{className:"w-4 h-4"})}),r.jsx("button",{onClick:()=>s("library","update",Ae.created_by_id)&&he({type:"file",id:Ae.id,name:Ae.filename}),className:`p-1.5 rounded transition-colors ${s("library","update",Ae.created_by_id)?"hover:bg-bambu-dark text-bambu-gray hover:text-white":"text-bambu-gray/50 cursor-not-allowed"}`,title:s("library","update",Ae.created_by_id)?t("common.rename"):t("fileManager.noPermissionRenameFile"),disabled:!s("library","update",Ae.created_by_id),children:r.jsx(ci,{className:"w-4 h-4"})}),Ae.file_type==="stl"&&r.jsx("button",{onClick:()=>s("library","update",Ae.created_by_id)&&ht.mutate(Ae.id),className:`p-1.5 rounded transition-colors ${s("library","update",Ae.created_by_id)?"hover:bg-bambu-dark text-bambu-gray hover:text-bambu-green":"text-bambu-gray/50 cursor-not-allowed"}`,title:s("library","update",Ae.created_by_id)?t("fileManager.generateThumbnail"):t("fileManager.noPermissionGenerateThumbnail"),disabled:ht.isPending||!s("library","update",Ae.created_by_id),children:r.jsx(gu,{className:"w-4 h-4"})}),r.jsx("button",{onClick:()=>s("library","delete",Ae.created_by_id)&&z({type:"file",id:Ae.id}),className:`p-1.5 rounded transition-colors ${s("library","delete",Ae.created_by_id)?"hover:bg-bambu-dark text-bambu-gray hover:text-red-400":"text-bambu-gray/50 cursor-not-allowed"}`,title:s("library","delete",Ae.created_by_id)?t("common.delete"):t("fileManager.noPermissionDeleteFile"),disabled:!s("library","delete",Ae.created_by_id),children:r.jsx(na,{className:"w-4 h-4"})})]})]},Ae.id))]})})]})]}),x&&r.jsx(Dst,{parentId:m,onClose:()=>S(!1),onSave:Ae=>Ye.mutate(Ae),isLoading:Ye.isPending,t}),k&&r.jsx(Fst,{onClose:()=>P(!1),onSave:Ae=>Ve.mutate(Ae),isLoading:Ve.isPending,t}),N&&qe&&r.jsx(Ist,{folders:qe,selectedFiles:v,currentFolderId:m,onClose:()=>T(!1),onMove:Ae=>Ee.mutate({fileIds:v,folderId:Ae}),isLoading:Ee.isPending,t}),j&&r.jsx(jse,{folderId:m,onClose:()=>D(!1),onUploadComplete:vt}),C&&r.jsx(Est,{onClose:()=>E(!1)}),R&&r.jsx(Ost,{folder:R,onClose:()=>I(null),onLink:Ae=>at.mutate({id:R.id,data:Ae}),isLoading:at.isPending,t}),O&&r.jsx(ka,{title:O.type==="folder"?t("fileManager.deleteFolder"):O.type==="bulk"?t("fileManager.deleteFilesCount",{count:O.count}):t("fileManager.deleteFile"),message:O.type==="folder"?t("fileManager.deleteFolderConfirm"):O.type==="bulk"?t("fileManager.deleteFilesConfirm",{count:O.count}):t("fileManager.deleteFileConfirm"),confirmText:t("common.delete"),variant:"danger",isLoading:aa,loadingText:t("fileManager.deleting"),onConfirm:ea,onCancel:()=>z(null)}),X&&r.jsx(Pc,{mode:"reprint",libraryFileId:X.id,archiveName:X.print_name||X.filename,onClose:()=>ae(null),onSuccess:()=>{ae(null),e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["archives"]})}}),Y&&r.jsx(Pc,{mode:"reprint",libraryFileId:Y.id,archiveName:Y.print_name||Y.filename,onClose:()=>ce(null),onSuccess:()=>{ce(null),b([]),e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["archives"]})}}),de&&r.jsx(Pc,{mode:"add-to-queue",libraryFileId:de.id,archiveName:de.print_name||de.filename,onClose:()=>oe(null),onSuccess:()=>{oe(null),b([]),e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["queue"]}),e.invalidateQueries({queryKey:["archives"]})}}),K&&r.jsx(QA,{source:{kind:"libraryFile",id:K.id,filename:K.filename},onClose:()=>ie(null)}),Q&&r.jsx(jst,{libraryFileId:Q.id,title:Q.print_name||Q.filename,fileType:Q.file_type,onClose:()=>A(null),onSliceWithBambuddy:gI(Q.filename)&&n("library:upload")?()=>{const Ae=Q;A(null),ie(Ae)}:void 0}),ue&&r.jsx(zst,{type:ue.type,currentName:ue.name,onClose:()=>he(null),onSave:Ae=>{ue.type==="file"?Xe.mutate({id:ue.id,filename:Ae}):Nt.mutate({id:ue.id,name:Ae})},isLoading:Xe.isPending||Nt.isPending,t})]})}function Hst(t){const e=Ga(t);if(!e)return"";const a=Math.ceil((e.getTime()-Date.now())/(1e3*60*60*24));return a<=0?"any moment":a===1?"1 day":`${a} days`}function GX(t){const e=Ga(t);return e?e.toLocaleString():t}function qst(){const{t}=wt(),e=Ii(),a=ia(),{showToast:n}=da(),{hasPermission:i,authEnabled:s}=lr(),[o,l]=y.useState(null),[c,d]=y.useState(new Set),u=!s||i("library:purge"),m=$e({queryKey:["library-trash"],queryFn:()=>ne.listLibraryTrash(200,0)}),p=$e({queryKey:["library-trash-settings"],queryFn:()=>ne.getLibraryTrashSettings(),enabled:u}),[f,g]=y.useState(null);y.useEffect(()=>{p.data&&f===null&&g(p.data.retention_days)},[p.data,f]);const v=rt({mutationFn:O=>{const z=p.data;return ne.updateLibraryTrashSettings({retention_days:O,auto_purge_enabled:z?.auto_purge_enabled??!1,auto_purge_days:z?.auto_purge_days??90,auto_purge_include_never_printed:z?.auto_purge_include_never_printed??!0})},onSuccess:O=>{n(t("libraryTrash.toast.retentionSaved",{days:O.retention_days}),"success"),a.invalidateQueries({queryKey:["library-trash-settings"]}),a.invalidateQueries({queryKey:["library-trash"]})},onError:O=>n(O.message||t("libraryTrash.toast.retentionFailed"),"error")}),b=rt({mutationFn:O=>ne.restoreLibraryTrash(O),onSuccess:()=>{n(t("libraryTrash.toast.restored"),"success"),a.invalidateQueries({queryKey:["library-trash"]}),a.invalidateQueries({queryKey:["library-trash-count"]}),a.invalidateQueries({queryKey:["library-files"]}),a.invalidateQueries({queryKey:["library-folders"]})},onError:O=>n(O.message||t("libraryTrash.toast.restoreFailed"),"error")}),x=rt({mutationFn:O=>ne.hardDeleteLibraryTrash(O),onSuccess:()=>{n(t("libraryTrash.toast.purged"),"success"),a.invalidateQueries({queryKey:["library-trash"]}),a.invalidateQueries({queryKey:["library-trash-count"]})},onError:O=>n(O.message||t("libraryTrash.toast.purgeFailed"),"error")}),S=rt({mutationFn:()=>ne.emptyLibraryTrash(),onSuccess:O=>{n(t("libraryTrash.toast.emptied",{count:O.deleted}),"success"),a.invalidateQueries({queryKey:["library-trash"]}),a.invalidateQueries({queryKey:["library-trash-count"]})},onError:O=>n(O.message||t("libraryTrash.toast.emptyFailed"),"error")}),k=rt({mutationFn:O=>Promise.all(O.map(z=>ne.restoreLibraryTrash(z))),onSuccess:(O,z)=>{n(t("libraryTrash.toast.bulkRestored",{count:z.length}),"success"),d(new Set),a.invalidateQueries({queryKey:["library-trash"]}),a.invalidateQueries({queryKey:["library-trash-count"]}),a.invalidateQueries({queryKey:["library-files"]}),a.invalidateQueries({queryKey:["library-folders"]})},onError:O=>n(O.message||t("libraryTrash.toast.restoreFailed"),"error")}),P=rt({mutationFn:O=>Promise.all(O.map(z=>ne.hardDeleteLibraryTrash(z))),onSuccess:(O,z)=>{n(t("libraryTrash.toast.bulkPurged",{count:z.length}),"success"),d(new Set),a.invalidateQueries({queryKey:["library-trash"]}),a.invalidateQueries({queryKey:["library-trash-count"]})},onError:O=>n(O.message||t("libraryTrash.toast.purgeFailed"),"error")}),N=y.useMemo(()=>m.data?.items??[],[m.data?.items]),T=m.data?.retention_days??30,j=y.useMemo(()=>N.reduce((O,z)=>O+z.file_size,0),[N]),D=N.length>0&&N.every(O=>c.has(O.id)),C=c.size>0&&!D,E=O=>{d(z=>{const X=new Set(z);return X.has(O)?X.delete(O):X.add(O),X})},R=()=>{d(O=>O.size===N.length?new Set:new Set(N.map(z=>z.id)))},I=()=>{o&&(o.type==="delete"?x.mutate(o.id):o.type==="bulkDelete"?P.mutate(Array.from(c)):S.mutate(),l(null))};return r.jsxs("div",{className:"p-6 max-w-screen-2xl mx-auto",children:[r.jsx("div",{className:"flex items-center gap-3 mb-4",children:r.jsxs(Ls,{to:"/files",className:"inline-flex items-center gap-1 text-sm text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-200",children:[r.jsx(ev,{className:"w-4 h-4"})," ",t("libraryTrash.backToFiles")]})}),r.jsxs("div",{className:"flex items-start justify-between mb-6 gap-4 flex-wrap",children:[r.jsxs("div",{children:[r.jsx("h1",{className:"text-2xl font-bold text-gray-900 dark:text-gray-100",children:t("libraryTrash.title")}),r.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-400 mt-1",children:u?t("libraryTrash.subtitleAdmin",{days:T}):t("libraryTrash.subtitleUser",{days:T})})]}),N.length>0&&r.jsxs(Le,{variant:"secondary",onClick:()=>l({type:"empty"}),className:"text-red-600 dark:text-red-400",children:[r.jsx(na,{className:"w-4 h-4 mr-1"}),t("libraryTrash.emptyTrash")]})]}),u&&p.data&&r.jsxs("div",{className:"mb-4 border border-gray-200 dark:border-gray-700 rounded-lg p-3 flex items-center gap-3 bg-gray-50 dark:bg-gray-800/40",children:[r.jsx("label",{htmlFor:"retention-days",className:"text-sm font-medium text-gray-700 dark:text-gray-300",children:t("libraryTrash.retentionLabel")}),r.jsx("input",{id:"retention-days",type:"number",min:1,max:365,value:f??p.data.retention_days,onChange:O=>g(Math.max(1,Math.min(365,parseInt(O.target.value||"0",10)||0))),className:"w-20 rounded border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-sm px-2 py-1 text-gray-900 dark:text-gray-100"}),r.jsx("span",{className:"text-sm text-gray-600 dark:text-gray-400",children:t("libraryTrash.days")}),r.jsxs(Le,{variant:"secondary",onClick:()=>f!=null&&v.mutate(f),disabled:v.isPending||f==null||f===p.data.retention_days,className:"ml-auto",children:[r.jsx(ms,{className:"w-4 h-4 mr-1"}),t("common.save")]})]}),m.isLoading?r.jsxs("div",{className:"flex items-center gap-2 text-gray-500 dark:text-gray-400",children:[r.jsx(lt,{className:"w-4 h-4 animate-spin"})," ",t("libraryTrash.loading")]}):N.length===0?r.jsx("div",{className:"border border-dashed border-gray-300 dark:border-gray-700 rounded-lg p-12 text-center",children:r.jsx("p",{className:"text-gray-500 dark:text-gray-400",children:t("libraryTrash.empty")})}):r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"flex items-center justify-between mb-2",children:[r.jsx("div",{className:"text-xs text-gray-500 dark:text-gray-400",children:t("libraryTrash.summary",{count:N.length,size:cs(j)})}),c.size>0&&r.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[r.jsx("span",{className:"text-gray-600 dark:text-gray-400",children:t("libraryTrash.selectionCount",{count:c.size})}),r.jsxs(Le,{variant:"secondary",onClick:()=>k.mutate(Array.from(c)),disabled:k.isPending,children:[r.jsx(bs,{className:"w-4 h-4 mr-1"}),t("libraryTrash.bulkRestore")]}),r.jsxs(Le,{variant:"secondary",onClick:()=>l({type:"bulkDelete",count:c.size}),disabled:P.isPending,className:"text-red-600 dark:text-red-400",children:[r.jsx(na,{className:"w-4 h-4 mr-1"}),t("libraryTrash.bulkPurge")]})]})]}),r.jsx("div",{className:"border border-gray-200 dark:border-gray-700 rounded-lg overflow-x-auto",children:r.jsxs("table",{className:"w-full text-sm",children:[r.jsx("thead",{className:"bg-gray-50 dark:bg-gray-800 text-left text-gray-600 dark:text-gray-300",children:r.jsxs("tr",{children:[r.jsx("th",{className:"px-3 py-2 w-10",children:r.jsx("input",{type:"checkbox",checked:D,ref:O=>{O&&(O.indeterminate=C)},onChange:R,"aria-label":t("libraryTrash.selectAll"),className:"rounded border-gray-300 cursor-pointer"})}),r.jsx("th",{className:"px-3 py-2 font-medium",children:t("libraryTrash.col.filename")}),r.jsx("th",{className:"px-3 py-2 font-medium",children:t("libraryTrash.col.folder")}),r.jsx("th",{className:"px-3 py-2 font-medium text-right",children:t("libraryTrash.col.size")}),r.jsx("th",{className:"px-3 py-2 font-medium whitespace-nowrap",children:t("libraryTrash.col.deleted")}),r.jsx("th",{className:"px-3 py-2 font-medium whitespace-nowrap",children:t("libraryTrash.col.autoPurge")}),u&&r.jsx("th",{className:"px-3 py-2 font-medium",children:t("libraryTrash.col.owner")}),r.jsx("th",{className:"px-3 py-2 font-medium text-right",children:t("libraryTrash.col.actions")})]})}),r.jsx("tbody",{className:"divide-y divide-gray-100 dark:divide-gray-800",children:N.map(O=>r.jsxs("tr",{className:"hover:bg-gray-50 dark:hover:bg-gray-800/50",children:[r.jsx("td",{className:"px-3 py-2",children:r.jsx("input",{type:"checkbox",checked:c.has(O.id),onChange:()=>E(O.id),"aria-label":t("libraryTrash.selectOne",{filename:O.filename}),className:"rounded border-gray-300 cursor-pointer"})}),r.jsx("td",{className:"px-3 py-2 text-gray-900 dark:text-gray-100 truncate max-w-md",title:O.filename,children:O.filename}),r.jsx("td",{className:"px-3 py-2 text-gray-600 dark:text-gray-400",children:O.folder_name??"—"}),r.jsx("td",{className:"px-3 py-2 text-right text-gray-600 dark:text-gray-400 tabular-nums whitespace-nowrap",children:cs(O.file_size)}),r.jsx("td",{className:"px-3 py-2 text-gray-600 dark:text-gray-400 whitespace-nowrap",children:GX(O.deleted_at)}),r.jsx("td",{className:"px-3 py-2 text-gray-600 dark:text-gray-400 whitespace-nowrap",children:r.jsx("span",{title:GX(O.auto_purge_at),children:t("libraryTrash.autoPurgeIn",{when:Hst(O.auto_purge_at)})})}),u&&r.jsx("td",{className:"px-3 py-2 text-gray-600 dark:text-gray-400",children:O.created_by_username??"—"}),r.jsxs("td",{className:"px-3 py-2 text-right whitespace-nowrap",children:[r.jsxs("button",{onClick:()=>b.mutate(O.id),disabled:b.isPending,className:"inline-flex items-center gap-1 px-2 py-1 text-xs text-blue-600 hover:text-blue-800 dark:text-blue-400 dark:hover:text-blue-300",children:[r.jsx(bs,{className:"w-3.5 h-3.5"}),t("libraryTrash.restore")]}),r.jsxs("button",{onClick:()=>l({type:"delete",id:O.id,filename:O.filename}),disabled:x.isPending,className:"inline-flex items-center gap-1 px-2 py-1 text-xs text-red-600 hover:text-red-800 dark:text-red-400 dark:hover:text-red-300 ml-2",children:[r.jsx(na,{className:"w-3.5 h-3.5"}),t("libraryTrash.purgeNow")]})]})]},O.id))})]})})]}),o&&r.jsx(ka,{onCancel:()=>l(null),onConfirm:I,title:o.type==="delete"?t("libraryTrash.confirm.purgeTitle"):o.type==="bulkDelete"?t("libraryTrash.confirm.bulkPurgeTitle"):t("libraryTrash.confirm.emptyTitle"),message:o.type==="delete"?t("libraryTrash.confirm.purgeBody",{filename:o.filename}):o.type==="bulkDelete"?t("libraryTrash.confirm.bulkPurgeBody",{count:o.count}):t("libraryTrash.confirm.emptyBody",{count:N.length}),confirmText:t("libraryTrash.confirm.cta"),variant:"danger"}),m.isError&&r.jsxs("div",{className:"mt-4 text-sm text-red-600 dark:text-red-400",children:[m.error?.message??t("libraryTrash.loadError"),r.jsx(Le,{variant:"secondary",onClick:()=>e("/files"),className:"ml-3",children:t("libraryTrash.backToFiles")})]})]})}function Vst(t,e){const a=`token=${encodeURIComponent(e)}`;let n=0;return t.querySelectorAll('img[src*="/api/v1/"], video[src*="/api/v1/"]').forEach(i=>{const s=i.getAttribute("src")||"";if(s.includes(a))return;const o=s.replace(/([?&])token=[^&]*(&|$)/,(c,d,u)=>u==="&"?d:""),l=o.includes("?")?"&":"?";i.src=`${o}${l}${a}`,n+=1}),n}function Mde(){const{authEnabled:t,user:e,loading:a}=lr(),n=ia(),i=y.useRef(!1),{data:s}=$e({queryKey:["camera-stream-token",e?.id??null],queryFn:()=>ne.getCameraStreamToken(),enabled:!a&&(!t||e!==null),staleTime:3e3*1e3,refetchInterval:3e3*1e3});y.useEffect(()=>{const o=s?.token??null;return D8(o),o&&Vst(document,o),()=>D8(null)},[s?.token]),y.useEffect(()=>{if(!t)return;const o=l=>{const c=l.target;if(!(c instanceof HTMLImageElement||c instanceof HTMLVideoElement))return;const d=c.src||"",u=yJ();!u||!d.includes(`token=${encodeURIComponent(u)}`)||i.current||(i.current=!0,n.invalidateQueries({queryKey:["camera-stream-token"]}),setTimeout(()=>{i.current=!1},5e3))};return document.addEventListener("error",o,!0),()=>document.removeEventListener("error",o,!0)},[t,n])}const kP=5,Gst=2e3,$st=3e4,Wst=5e3;function Kst(){const{t}=wt(),e=ia(),{showToast:a}=da(),{hasPermission:n,authEnabled:i,user:s}=lr(),{printerId:o}=FS(),l=parseInt(o||"0",10),[c]=mb(),d=parseInt(c.get("fps")||"15",10),u=Math.min(Math.max(isNaN(d)?15:d,1),30);Mde();const{data:m}=$e({queryKey:["camera-stream-token",s?.id??null],queryFn:()=>ne.getCameraStreamToken(),enabled:i?!!s:!0,staleTime:3e3*1e3}),p=m?.token??yJ(),[f,g]=y.useState("stream"),[v,b]=y.useState(!1),[x,S]=y.useState(!1),[k,P]=y.useState(!1),[N,T]=y.useState(!0),[j,D]=y.useState(Date.now()),[C,E]=y.useState(!1),[R,I]=y.useState(!1),[O,z]=y.useState(0),[X,ae]=y.useState(!1),[Y,ce]=y.useState(0),[de,oe]=y.useState(1),[K,ie]=y.useState({x:0,y:0}),[ue,he]=y.useState(!1),[ge,q]=y.useState({x:0,y:0}),[Q,A]=y.useState(null),[F,B]=y.useState(null),W=y.useRef(null),H=y.useRef(null),le=y.useRef(null),U=y.useRef(null),G=y.useRef(null),{data:Z}=$e({queryKey:["printer",l],queryFn:()=>ne.getPrinter(l),enabled:l>0}),{data:J}=$e({queryKey:["printerStatus",l],queryFn:()=>ne.getPrinterStatus(l),refetchInterval:3e4,enabled:l>0}),re=rt({mutationFn:Be=>ne.setChamberLight(l,Be),onMutate:async Be=>{await e.cancelQueries({queryKey:["printerStatus",l]});const Qe=e.getQueryData(["printerStatus",l]);return e.setQueryData(["printerStatus",l],Ge=>({...Ge,chamber_light:Be})),{previousStatus:Qe}},onSuccess:(Be,Qe)=>{a(`Chamber light ${Qe?"on":"off"}`)},onError:(Be,Qe,Ge)=>{Ge?.previousStatus&&e.setQueryData(["printerStatus",l],Ge.previousStatus),a(Be.message||t("printers.toast.failedToControlChamberLight"),"error")}}),se=(J?.state==="RUNNING"||J?.state==="PAUSE")&&(J?.printable_objects_count??0)>=2;y.useEffect(()=>(Z&&(document.title=`${Z.name} - Camera`),()=>{document.title="Bambuddy"}),[Z]);const fe=y.useRef(!1);y.useEffect(()=>{const Be=`/api/v1/printers/${l}/camera/stop`;fe.current=!1;const Qe=()=>{if(l>0&&!fe.current){fe.current=!0;const at={},Xe=ep();Xe&&(at.Authorization=`Bearer ${Xe}`),fetch(Be,{method:"POST",keepalive:!0,headers:at}).catch(()=>{})}},Ge=()=>{Qe()};window.addEventListener("beforeunload",Ge);const Ee=W.current;return()=>{window.removeEventListener("beforeunload",Ge),Ee&&(Ee.src=""),Qe()}},[l]),y.useEffect(()=>{if(N&&!C){const Qe=setTimeout(()=>{T(!1)},f==="stream"?3e3:2e4);return()=>clearTimeout(Qe)}},[f,N,j,C]),y.useEffect(()=>{const Be=()=>{const Qe=!!document.fullscreenElement;I(Qe),oe(1),ie({x:0,y:0}),f==="stream"&&!C&&(W.current&&(W.current.src=""),setTimeout(()=>{T(!0),D(Date.now())},200))};return document.addEventListener("fullscreenchange",Be),()=>document.removeEventListener("fullscreenchange",Be)},[f,C]),y.useEffect(()=>{let Be;const Qe=()=>{clearTimeout(Be),Be=setTimeout(()=>{localStorage.setItem("cameraWindowState",JSON.stringify({width:window.outerWidth,height:window.outerHeight,left:window.screenX,top:window.screenY}))},500)};return window.addEventListener("resize",Qe),()=>{clearTimeout(Be),window.removeEventListener("resize",Qe)}},[]),y.useEffect(()=>()=>{le.current&&clearTimeout(le.current),U.current&&clearInterval(U.current),G.current&&clearInterval(G.current)},[]);const me=y.useCallback(()=>{if(O>=kP){ae(!1),P(!0);return}const Be=Math.min(Gst*Math.pow(2,O),$st);ae(!0),ce(Math.ceil(Be/1e3)),U.current=setInterval(()=>{ce(Qe=>Qe<=1?(U.current&&clearInterval(U.current),0):Qe-1)},1e3),le.current=setTimeout(()=>{z(Qe=>Qe+1),ae(!1),T(!0),P(!1),W.current&&(W.current.src=""),D(Date.now())},Be)},[O]);y.useEffect(()=>{if(f!=="stream"||N||X||C){G.current&&(clearInterval(G.current),G.current=null);return}return G.current=setInterval(async()=>{try{const Be=await ne.getCameraStatus(l);(Be.stalled||!Be.active&&!k)&&(console.log(`Stream issue detected: stalled=${Be.stalled}, active=${Be.active}, reconnecting...`),G.current&&(clearInterval(G.current),G.current=null),T(!1),me())}catch{}},Wst),()=>{G.current&&(clearInterval(G.current),G.current=null)}},[f,N,k,X,C,l,me]);const pe=()=>{T(!1),f==="stream"&&O{if(T(!1),P(!1),z(0),ae(!1),le.current&&clearTimeout(le.current),U.current&&clearInterval(U.current),W.current&&!localStorage.getItem("cameraWindowState")){const Be=W.current,Qe=Be.naturalWidth,Ge=Be.naturalHeight;if(Qe>0&&Ge>0){const Xe=window.outerWidth-window.innerWidth,Nt=window.outerHeight-window.innerHeight,Vt=Qe+16+Xe,ht=Ge+45+16+Nt;try{window.resizeTo(Vt,ht)}catch{}}}},L=()=>{if(l>0){const Be={},Qe=ep();Qe&&(Be.Authorization=`Bearer ${Qe}`),fetch(`/api/v1/printers/${l}/camera/stop`,{method:"POST",headers:Be}).catch(()=>{})}},te=Be=>{f===Be||C||(E(!0),T(!0),P(!1),z(0),ae(!1),oe(1),ie({x:0,y:0}),le.current&&clearTimeout(le.current),U.current&&clearInterval(U.current),W.current&&(W.current.src=""),f==="stream"&&L(),setTimeout(()=>{g(Be),D(Date.now()),E(!1)},100))},be=()=>{C||(E(!0),T(!0),P(!1),z(0),ae(!1),le.current&&clearTimeout(le.current),U.current&&clearInterval(U.current),W.current&&(W.current.src=""),f==="stream"&&L(),setTimeout(()=>{D(Date.now()),E(!1)},100))},xe=()=>{H.current&&(document.fullscreenElement?document.exitFullscreen():H.current.requestFullscreen())},ve=()=>{oe(Be=>Math.min(Be+.5,4))},De=()=>{oe(Be=>{const Qe=Math.max(Be-.5,1);return Qe===1&&ie({x:0,y:0}),Qe})},je=Be=>{Be.preventDefault(),Be.deltaY<0?ve():De()},Te=Be=>{de>1&&(Be.preventDefault(),he(!0),q({x:Be.clientX-K.x,y:Be.clientY-K.y}))},qe=y.useCallback(()=>{if(!H.current)return{x:300,y:200};const Be=H.current.getBoundingClientRect(),Qe=Be.width*(de-1)/2,Ge=Be.height*(de-1)/2;return{x:Math.max(50,Qe),y:Math.max(50,Ge)}},[de]),Pe=Be=>{if(ue&&de>1){const Qe=Be.clientX-ge.x,Ge=Be.clientY-ge.y,Ee=qe();ie({x:Math.max(-Ee.x,Math.min(Ee.x,Qe)),y:Math.max(-Ee.y,Math.min(Ee.y,Ge))})}},Ie=()=>{he(!1)},Re=Be=>{if(Be.length<2)return 0;const Qe=Be[0].clientX-Be[1].clientX,Ge=Be[0].clientY-Be[1].clientY;return Math.sqrt(Qe*Qe+Ge*Ge)},Ue=Be=>Be.length<2?{x:Be[0].clientX,y:Be[0].clientY}:{x:(Be[0].clientX+Be[1].clientX)/2,y:(Be[0].clientY+Be[1].clientY)/2},ze=Be=>{Be.touches.length===2?(Be.preventDefault(),A(Re(Be.touches)),B(Ue(Be.touches))):Be.touches.length===1&&de>1&&(Be.preventDefault(),he(!0),q({x:Be.touches[0].clientX-K.x,y:Be.touches[0].clientY-K.y}))},it=Be=>{if(Be.touches.length===2&&Q!==null){Be.preventDefault();const Qe=Re(Be.touches),Ge=Qe/Q;oe(at=>{const Xe=Math.max(1,Math.min(4,at*Ge));return Xe===1&&ie({x:0,y:0}),Xe}),A(Qe);const Ee=Ue(Be.touches);if(F){const at=qe();ie(Xe=>({x:Math.max(-at.x,Math.min(at.x,Xe.x+(Ee.x-F.x))),y:Math.max(-at.y,Math.min(at.y,Xe.y+(Ee.y-F.y)))}))}B(Ee)}else if(Be.touches.length===1&&ue&&de>1){Be.preventDefault();const Qe=Be.touches[0].clientX-ge.x,Ge=Be.touches[0].clientY-ge.y,Ee=qe();ie({x:Math.max(-Ee.x,Math.min(Ee.x,Qe)),y:Math.max(-Ee.y,Math.min(Ee.y,Ge))})}},Oe=Be=>{Be.touches.length<2&&(A(null),B(null)),Be.touches.length===0&&he(!1)},tt=()=>{oe(1),ie({x:0,y:0})},Fe=i&&!p,Ye=Be=>p?`${Be}&token=${encodeURIComponent(p)}`:zn(Be),Ve=C||Fe?"":Ye(f==="stream"?`/api/v1/printers/${l}/camera/stream?fps=${u}&t=${j}`:`/api/v1/printers/${l}/camera/snapshot?t=${j}`),Me=N||C||X;return l?r.jsxs("div",{ref:H,className:"min-h-screen bg-black flex flex-col",children:[r.jsxs("div",{className:"flex items-center justify-between px-4 py-2 bg-bambu-dark-secondary border-b border-bambu-dark-tertiary",children:[r.jsxs("h1",{className:"text-sm font-medium text-white flex items-center gap-2",children:[r.jsx(wy,{className:"w-4 h-4"}),Z?.name||`Printer ${l}`]}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsxs("div",{className:"flex bg-bambu-dark rounded p-0.5",children:[r.jsx("button",{onClick:()=>te("stream"),disabled:Me,className:`px-3 py-1 text-xs rounded transition-colors ${f==="stream"?"bg-bambu-green text-white":"text-bambu-gray hover:text-white disabled:opacity-50"}`,children:t("camera.live")}),r.jsx("button",{onClick:()=>te("snapshot"),disabled:Me,className:`px-3 py-1 text-xs rounded transition-colors ${f==="snapshot"?"bg-bambu-green text-white":"text-bambu-gray hover:text-white disabled:opacity-50"}`,children:t("camera.snapshot")})]}),r.jsx("button",{onClick:()=>re.mutate(!J?.chamber_light),disabled:!J?.connected||re.isPending||!n("printers:control"),className:`p-1.5 rounded disabled:opacity-50 ${J?.chamber_light?"bg-yellow-500/20 hover:bg-yellow-500/30":"hover:bg-bambu-dark-tertiary"}`,title:n("printers:control")?t("camera.chamberLight"):t("printers.permission.noControl"),children:r.jsx(CO,{on:J?.chamber_light??!1,className:"w-4 h-4"})}),r.jsx("button",{onClick:()=>b(!0),disabled:!se||!n("printers:control"),className:`p-1.5 rounded disabled:opacity-50 ${se&&n("printers:control")?"hover:bg-bambu-dark-tertiary":""}`,title:n("printers:control")?t(se?"printers.skipObjects.tooltip":"printers.skipObjects.onlyWhilePrinting"):t("printers.permission.noControl"),children:r.jsx(JT,{className:"w-4 h-4 text-bambu-gray"})}),r.jsx("button",{onClick:be,disabled:Me,className:"p-1.5 hover:bg-bambu-dark-tertiary rounded disabled:opacity-50",title:t(f==="stream"?"camera.restartStream":"camera.refreshSnapshot"),children:r.jsx(tr,{className:`w-4 h-4 text-bambu-gray ${Me?"animate-spin":""}`})}),r.jsx("button",{onClick:()=>S(!0),className:"p-1.5 hover:bg-bambu-dark-tertiary rounded",title:t("camera.diagnose.button"),children:r.jsx(Ll,{className:"w-4 h-4 text-bambu-gray"})}),r.jsx("button",{onClick:xe,className:"p-1.5 hover:bg-bambu-dark-tertiary rounded",title:t(R?"camera.exitFullscreen":"camera.fullscreen"),children:R?r.jsx(cJ,{className:"w-4 h-4 text-bambu-gray"}):r.jsx(cye,{className:"w-4 h-4 text-bambu-gray"})})]})]}),r.jsx("div",{className:"flex-1 flex items-center justify-center p-2 overflow-hidden",onWheel:je,onMouseMove:Pe,onMouseUp:Ie,onMouseLeave:Ie,onTouchStart:ze,onTouchMove:it,onTouchEnd:Oe,style:{touchAction:"none"},children:r.jsxs("div",{className:"relative w-full h-full flex items-center justify-center",children:[(N||C)&&!X&&r.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/50 z-10",children:r.jsxs("div",{className:"text-center",children:[r.jsx(tr,{className:"w-8 h-8 text-bambu-gray animate-spin mx-auto mb-2"}),r.jsx("p",{className:"text-sm text-bambu-gray",children:t(f==="stream"?"camera.connectingToCamera":"camera.capturingSnapshot")})]})}),X&&r.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/80 z-10",children:r.jsxs("div",{className:"text-center p-4",children:[r.jsx(xu,{className:"w-10 h-10 text-orange-400 mx-auto mb-3"}),r.jsx("p",{className:"text-white mb-2",children:t("camera.connectionLost")}),r.jsx("p",{className:"text-sm text-bambu-gray mb-3",children:t("camera.reconnecting",{countdown:Y,attempt:Math.min(O+1,kP),max:kP})}),r.jsx("button",{onClick:be,className:"px-4 py-2 bg-bambu-green text-white text-sm rounded hover:bg-bambu-green/80 transition-colors",children:t("camera.reconnectNow")})]})}),k&&!X&&r.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black z-10",children:r.jsxs("div",{className:"text-center p-4",children:[r.jsx(xa,{className:"w-12 h-12 text-orange-400 mx-auto mb-3"}),r.jsx("p",{className:"text-white mb-2",children:t("camera.cameraUnavailable")}),r.jsx("p",{className:"text-xs text-bambu-gray mb-4 max-w-md",children:t("camera.cameraUnavailableDesc")}),r.jsxs("div",{className:"flex gap-2 justify-center",children:[r.jsx("button",{onClick:be,className:"px-4 py-2 bg-bambu-green text-white rounded hover:bg-bambu-green/80 transition-colors",children:t("camera.retry")}),r.jsx("button",{onClick:()=>S(!0),className:"px-4 py-2 bg-bambu-dark border border-bambu-dark-tertiary text-bambu-gray hover:text-white rounded transition-colors",children:t("camera.diagnose.button")})]})]})}),r.jsx("img",{ref:W,src:Ve,alt:t("camera.cameraStream"),className:"max-w-full max-h-full object-contain select-none",style:{transform:`scale(${de}) translate(${K.x/de}px, ${K.y/de}px) rotate(${Z?.camera_rotation||0}deg)`,...Z?.camera_rotation===90||Z?.camera_rotation===270?{maxWidth:"100vh",maxHeight:"100vw"}:{},cursor:de>1?ue?"grabbing":"grab":"default"},onError:Ve?pe:void 0,onLoad:Ve?V:void 0,onMouseDown:Te,draggable:!1},j),r.jsxs("div",{className:"absolute bottom-4 left-4 flex items-center gap-1.5 bg-black/60 rounded-lg px-2 py-1.5",children:[r.jsx("button",{onClick:De,disabled:de<=1,className:"p-1.5 hover:bg-white/10 rounded disabled:opacity-30",title:t("camera.zoomOut"),children:r.jsx(GI,{className:"w-4 h-4 text-white"})}),r.jsxs("button",{onClick:tt,className:"px-2 py-1 text-sm text-white hover:bg-white/10 rounded min-w-[48px]",title:t("camera.resetZoom"),children:[Math.round(de*100),"%"]}),r.jsx("button",{onClick:ve,disabled:de>=4,className:"p-1.5 hover:bg-white/10 rounded disabled:opacity-30",title:t("camera.zoomIn"),children:r.jsx(VI,{className:"w-4 h-4 text-white"})})]})]})}),r.jsx(PO,{printerId:l,isOpen:v,onClose:()=>b(!1)}),x&&r.jsx(ate,{printerId:l,printerName:Z?.name||null,onClose:()=>S(!1)})]}):r.jsx("div",{className:"min-h-screen bg-black flex items-center justify-center",children:r.jsx("p",{className:"text-white",children:t("camera.invalidPrinterId")})})}function Yst(t,e,a){if(!t)return"";if(!e)return t;const n=e.match(/plate_(\d+)\.gcode/);return n&&parseInt(n[1],10)>1?`${t} — ${a("printers.plateNumber","Plate {{number}}",{number:n[1]})}`:t}function Qst(t){const e=t.get("show")?.split(",")||["progress","layers","eta","filename","status"],a=parseInt(t.get("fps")||"15",10),n=Math.min(Math.max(isNaN(a)?15:a,1),30),i=t.get("camera"),s=i!=="false"&&i!=="0";return{size:t.get("size")||"medium",fps:n,showCamera:s,showProgress:e.includes("progress"),showLayers:e.includes("layers"),showEta:e.includes("eta"),showFilename:e.includes("filename"),showStatus:e.includes("status"),showPrinter:e.includes("printer")}}function Xst(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 Zst(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 Jst(){const{printerId:t}=FS(),[e]=mb(),{t:a}=wt(),n=ia(),i=parseInt(t||"0",10),[s,o]=y.useState(Date.now()),l=y.useMemo(()=>Qst(e),[e]),c=Zst(l.size),{data:d}=$e({queryKey:["printer",i],queryFn:()=>ne.getPrinter(i),enabled:i>0}),{data:u}=$e({queryKey:["printerStatus",i],queryFn:()=>ne.getPrinterStatus(i),enabled:i>0,refetchInterval:2e3}),{data:m}=$e({queryKey:["settings"],queryFn:ne.getSettings}),p=m?.time_format||"system";y.useEffect(()=>{if(!i)return;let x=null,S=!1;return(async()=>{let k;try{k=(await ne.getWebSocketToken()).token}catch{}if(S)return;const P=window.location.protocol==="https:"?"wss:":"ws:",N=k?`?token=${encodeURIComponent(k)}`:"",T=`${P}//${window.location.host}/api/v1/ws${N}`;x=new WebSocket(T),x.onmessage=j=>{try{const D=JSON.parse(j.data);D.type==="printer_status"&&D.printer_id===i&&n.setQueryData(["printerStatus",i],D.status)}catch{}},x.onerror=()=>{}})(),()=>{S=!0,x&&x.close()}},[i,n]),y.useEffect(()=>(document.title=d?`${d.name} - ${a("streamOverlay.title")}`:a("streamOverlay.title"),()=>{document.title="Bambuddy"}),[d,a]);const f=()=>{setTimeout(()=>{o(Date.now())},3e3)};if(!i)return r.jsx("div",{className:"min-h-screen bg-black flex items-center justify-center",children:r.jsx("p",{className:"text-white",children:a("streamOverlay.invalidPrinterId")})});if(!u)return r.jsx("div",{className:"min-h-screen bg-black flex items-center justify-center",children:r.jsx("p",{className:"text-gray-400",children:a("common.loading")})});const g=u.state==="RUNNING"||u.state==="PAUSE",v=u.progress||0,b=zn(`/api/v1/printers/${i}/camera/stream?fps=${l.fps}&t=${s}`);return r.jsxs("div",{className:"min-h-screen bg-black relative overflow-hidden",children:[l.showCamera&&r.jsx("img",{src:b,alt:a("streamOverlay.cameraStream"),className:"absolute inset-0 w-full h-full object-contain",style:d?.camera_rotation?{transform:`rotate(${d.camera_rotation}deg)`}:void 0,onError:f},s),r.jsx("a",{href:"https://github.com/maziggy/bambuddy",target:"_blank",rel:"noopener noreferrer",className:"absolute top-4 right-4 z-10",children:r.jsx("img",{src:"/img/bambuddy_logo_dark_transparent.png",alt:"Bambuddy",className:`${c.logoHeight} object-contain drop-shadow-lg hover:scale-105 transition-transform`})}),r.jsx("div",{className:"absolute bottom-0 left-0 right-0 z-10 bg-gradient-to-t from-black/80 via-black/60 to-transparent",children:r.jsxs("div",{className:`${c.container}`,children:[l.showPrinter&&d&&r.jsxs("div",{className:`flex items-center ${c.gap} mb-2`,children:[r.jsx(xr,{className:`${c.icon} text-white/70`}),r.jsx("span",{className:`${c.text} text-white font-medium`,children:d.name})]}),l.showFilename&&u.current_print&&r.jsx("div",{className:`${c.textLarge} text-white font-semibold mb-2 truncate drop-shadow-md`,children:Yst(u.current_print.replace(/\.gcode\.3mf$|\.3mf$|\.gcode$/i,""),u.gcode_file,a)}),l.showStatus&&r.jsx("div",{className:`${c.text} text-white/70 mb-2`,children:Xst(u,a)}),l.showProgress&&g&&r.jsxs("div",{className:"mb-3",children:[r.jsxs("div",{className:`flex items-center justify-between mb-1 ${c.text}`,children:[r.jsx("span",{className:"text-white/70",children:a("streamOverlay.progress")}),r.jsxs("span",{className:"text-white font-bold",children:[Math.round(v),"%"]})]}),r.jsx("div",{className:`w-full bg-white/20 rounded-full ${c.progressHeight}`,children:r.jsx("div",{className:`bg-bambu-green ${c.progressHeight} rounded-full transition-all duration-500`,style:{width:`${v}%`}})})]}),g&&(l.showLayers||l.showEta)&&r.jsxs("div",{className:`flex items-center ${c.gap} flex-wrap`,children:[l.showLayers&&u.layer_num!=null&&u.total_layers!=null&&u.total_layers>0&&r.jsxs("div",{className:`flex items-center ${c.gap} text-white/70`,children:[r.jsx(tn,{className:c.icon}),r.jsxs("span",{className:c.text,children:[r.jsx("span",{className:"text-white",children:u.layer_num}),r.jsx("span",{className:"mx-1",children:"/"}),r.jsx("span",{children:u.total_layers})]})]}),l.showEta&&u.remaining_time!=null&&u.remaining_time>0&&r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:`flex items-center ${c.gap} text-white/70`,children:[r.jsx(ru,{className:c.icon}),r.jsx("span",{className:`${c.text} text-white`,children:ds(u.remaining_time*60)})]}),r.jsxs("div",{className:`flex items-center ${c.gap} text-white/70`,children:[r.jsx(ar,{className:c.icon}),r.jsxs("span",{className:`${c.text} text-white`,children:[a("streamOverlay.eta")," ",YI(u.remaining_time,p,a)]})]})]})]}),!g&&r.jsx("div",{className:`${c.text} text-white/70 py-2`,children:u.connected?a("streamOverlay.printerIdle"):a("streamOverlay.printerOffline")})]})})]})}function eot(){const{t}=wt(),{id:e}=FS(),{mode:a}=gb(),{data:n,isLoading:i,error:s}=$e({queryKey:["external-link",e],queryFn:()=>ne.getExternalLink(Number(e)),enabled:!!e});return i?r.jsx("div",{className:"flex items-center justify-center h-full",children:r.jsx(lt,{className:"w-8 h-8 text-bambu-green animate-spin"})}):s||!n?r.jsxs("div",{className:"flex flex-col items-center justify-center h-full gap-4 text-bambu-gray",children:[r.jsx(xa,{className:"w-12 h-12"}),r.jsx("p",{children:t("common.linkNotFound")})]}):r.jsx("iframe",{src:n.url,className:"h-full w-full border-0",style:{colorScheme:a},title:n.name,sandbox:"allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox"})}function $X(){const{id:t}=FS(),e=Ii(),a=ia(),{t:n}=wt(),{showToast:i}=da(),s=!!t,[o,l]=y.useState(""),[c,d]=y.useState(""),[u,m]=y.useState([]),[p,f]=y.useState(""),[g,v]=y.useState(!1),{data:b,isLoading:x}=$e({queryKey:["group",t],queryFn:()=>ne.getGroup(Number(t)),enabled:s}),{data:S,isLoading:k}=$e({queryKey:["permissions"],queryFn:()=>ne.getPermissions()});s&&b&&!g&&(l(b.name),d(b.description||""),m(b.permissions),v(!0));const P=rt({mutationFn:Y=>ne.createGroup(Y),onSuccess:()=>{a.invalidateQueries({queryKey:["groups"]}),a.invalidateQueries({queryKey:["group"]}),i(n("groups.toast.created")),e("/settings?tab=users")},onError:Y=>{i(Y.message,"error")}}),N=rt({mutationFn:Y=>ne.updateGroup(Number(t),Y),onSuccess:Y=>{a.invalidateQueries({queryKey:["groups"]}),Y&&a.setQueryData(["group",t],Y),i(n("groups.toast.updated")),e("/settings?tab=users")},onError:Y=>{i(Y.message,"error")}}),T=P.isPending||N.isPending,j=()=>{if(!o.trim()){i(n("groups.toast.enterGroupName"),"error");return}s?N.mutate({name:o!==b?.name?o:void 0,description:c,permissions:u}):P.mutate({name:o,description:c||void 0,permissions:u})},D=Y=>{m(ce=>ce.includes(Y)?ce.filter(de=>de!==Y):[...ce,Y])},C=(Y,ce)=>{const de=Y.permissions.map(oe=>oe.value);m(oe=>{const K=oe.filter(ie=>!de.includes(ie));return ce?[...K,...de]:K})},E=Y=>Y.permissions.every(ce=>u.includes(ce.value)),R=Y=>{const ce=Y.permissions.filter(de=>u.includes(de.value)).length;return ce>0&&ce{S&&m(S.all_permissions)},O=()=>{m([])},z=p.toLowerCase(),X=y.useMemo(()=>S?z?S.categories.map(Y=>({...Y,permissions:Y.permissions.filter(ce=>ce.label.toLowerCase().includes(z))})).filter(Y=>Y.permissions.length>0):S.categories:[],[S,z]),ae=S?.all_permissions.length??0;return x||k?r.jsx("div",{className:"flex items-center justify-center py-16",children:r.jsx(lt,{className:"w-8 h-8 text-bambu-green animate-spin"})}):r.jsxs("div",{className:"space-y-6 max-w-5xl mx-auto",children:[r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("button",{onClick:()=>e("/settings?tab=users"),className:"p-2 rounded-lg hover:bg-bambu-dark-tertiary text-bambu-gray hover:text-white transition-colors",children:r.jsx(ev,{className:"w-5 h-5"})}),r.jsx("h1",{className:"text-xl font-bold text-white",children:n(s?"groups.editor.title":"groups.editor.createTitle")})]}),s&&b?.is_system&&r.jsxs("div",{className:"flex items-center gap-3 px-4 py-3 rounded-lg bg-yellow-500/10 border border-yellow-500/20 text-yellow-400 text-sm",children:[r.jsx(xa,{className:"w-4 h-4 shrink-0"}),n("groups.form.systemGroupWarning")]}),r.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:n("groups.form.groupName")}),r.jsx("input",{type:"text",value:o,onChange:Y=>l(Y.target.value),disabled:s&&b?.is_system,className:"w-full px-4 py-3 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors disabled:opacity-50",placeholder:n("groups.form.groupNamePlaceholder")})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:n("groups.form.description")}),r.jsx("input",{type:"text",value:c,onChange:Y=>d(Y.target.value),className:"w-full px-4 py-3 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors",placeholder:n("groups.form.descriptionPlaceholder")})]})]}),r.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-3",children:[r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsxs("span",{className:"text-sm text-bambu-gray",children:[n("groups.editor.permissionsSelected",{count:u.length})," / ",ae]}),r.jsx(Le,{size:"sm",variant:"ghost",onClick:I,children:n("groups.editor.selectAll")}),r.jsx(Le,{size:"sm",variant:"ghost",onClick:O,children:n("groups.editor.clearAll")})]}),r.jsxs("div",{className:"relative",children:[r.jsx(br,{className:"w-4 h-4 absolute left-3 top-1/2 -translate-y-1/2 text-bambu-gray"}),r.jsx("input",{type:"text",value:p,onChange:Y=>f(Y.target.value),placeholder:n("groups.editor.search"),className:"pl-9 pr-4 py-2 text-sm bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors w-64"})]})]}),X.length===0?r.jsx("div",{className:"text-center py-12 text-bambu-gray",children:n("groups.editor.noResults")}):r.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:X.map(Y=>{const ce=S.categories.find(ue=>ue.name===Y.name),de=ce.permissions.filter(ue=>u.includes(ue.value)).length,oe=ce.permissions.length,K=E(ce),ie=R(ce);return r.jsxs(Tt,{children:[r.jsxs("div",{className:"sticky top-0 z-10 flex items-center justify-between px-4 py-3 bg-bambu-dark-secondary border-b border-bambu-dark-tertiary rounded-t-xl",children:[r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsxs("button",{type:"button",onClick:()=>C(ce,!K),className:`w-5 h-5 rounded border flex items-center justify-center transition-colors shrink-0 ${K?"bg-bambu-green border-bambu-green":ie?"bg-bambu-green/50 border-bambu-green":"border-bambu-gray hover:border-white"}`,children:[K&&r.jsx(_r,{className:"w-3 h-3 text-white"}),ie&&!K&&r.jsx(hN,{className:"w-3 h-3 text-white"})]}),r.jsx(kl,{className:"w-4 h-4 text-bambu-gray shrink-0"}),r.jsx("span",{className:"text-white font-medium text-sm",children:Y.name})]}),r.jsxs("span",{className:"text-xs text-bambu-gray tabular-nums",children:[de,"/",oe]})]}),r.jsx("div",{className:"p-3 space-y-1",children:Y.permissions.map(ue=>r.jsxs("label",{className:"flex items-center gap-3 px-2 py-1.5 rounded hover:bg-bambu-dark-secondary cursor-pointer",children:[r.jsx("input",{type:"checkbox",checked:u.includes(ue.value),onChange:()=>D(ue.value),className:"w-4 h-4 rounded border-bambu-gray text-bambu-green focus:ring-bambu-green focus:ring-offset-0 bg-bambu-dark-secondary"}),r.jsx("span",{className:"text-sm text-bambu-gray",children:ue.label})]},ue.value))})]},Y.name)})}),r.jsx("div",{className:"h-16"}),r.jsxs("div",{className:"fixed bottom-0 left-0 right-0 z-20 px-6 py-3 bg-bambu-dark-secondary border-t border-bambu-dark-tertiary flex items-center justify-center gap-3",children:[r.jsx(Le,{variant:"secondary",onClick:()=>e("/settings?tab=users"),children:n("common.cancel")}),r.jsx(Le,{onClick:j,disabled:T||!o.trim(),children:T?r.jsxs(r.Fragment,{children:[r.jsx(lt,{className:"w-4 h-4 animate-spin"}),n("common.saving")]}):r.jsxs(r.Fragment,{children:[r.jsx(ms,{className:"w-4 h-4"}),n("common.save")]})})]})]})}const tot=1.65,WX=["#1DB954","#3B82F6","#F59E0B","#EF4444","#8B5CF6"];function Lw(t,e,a){return`${t}||${e??""}||${a??""}`}function Km(t,e){const a=new Date(t);return a.setDate(a.getDate()+Math.round(e)),a}function ES(t){return t.toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})}function Rw(t){return t.toLocaleDateString(void 0,{month:"short",day:"numeric"})}function aot(t){if(t.length<2)return null;const e=[...t].sort((c,d)=>new Date(c.created_at).getTime()-new Date(d.created_at).getTime()),a=Date.now(),n=Math.LN2/30,i=[];for(let c=1;cc+d.weight,0);if(s===0)return null;const o=i.reduce((c,d)=>c+d.rate*d.weight,0)/s,l=i.reduce((c,d)=>c+d.weight*(d.rate-o)**2,0)/s;return{rate:o,stdDev:Math.sqrt(l)}}function rot(t){const e=t.reduce((s,o)=>s+Math.max(0,o.weight_used-(o.weight_used_baseline??0)),0);if(e===0)return null;const a=Date.now(),n=t.reduce((s,o)=>{const l=new Date(o.created_at).getTime();return lne.getAllUsageHistory(5e3),staleTime:6e4,enabled:o}),{data:j=[]}=$e({queryKey:["shopping-list"],queryFn:ne.getShoppingList,staleTime:3e4,enabled:o}),D=P?.forecast_global_lead_time_days??0,C=y.useMemo(()=>{const ce=new Map;for(const de of N)ce.set(Lw(de.material,de.subtype,de.brand),de);return ce},[N]),E=y.useMemo(()=>{const ce=new Map;for(const de of T){const oe=ce.get(de.spool_id)??[];oe.push(de),ce.set(de.spool_id,oe)}return ce},[T]),R=y.useMemo(()=>{const ce=new Map;for(const de of t){if(de.archived_at)continue;const oe=Lw(de.material,de.subtype,de.brand),K=ce.get(oe)??{key:oe,material:de.material,subtype:de.subtype,brand:de.brand,spools:[]};K.spools.push(de),ce.set(oe,K)}return[...ce.values()]},[t]),I=y.useMemo(()=>{const ce=new Date;return ce.setHours(0,0,0,0),R.map(de=>{const oe=C.get(de.key)??null,K=oe?.lead_time_days??0,ie=Math.max(D,K),ue=oe?.safety_margin_value??14,he=oe?.safety_margin_unit??"days",ge=de.spools.reduce((L,te)=>L+Math.max(0,te.label_weight-te.weight_used),0),q=de.spools.reduce((L,te)=>L+te.label_weight,0),Q=de.spools.reduce((L,te)=>L+Math.max(0,te.weight_used-(te.weight_used_baseline??0)),0),A=[];for(const L of de.spools)A.push(...E.get(L.id)??[]);let F=null,B=null,W="none";const H=aot(A);if(H!==null)F=H.rate,B=H.stdDev,W="history";else{const L=rot(de.spools);L!==null&&(F=L,W="delta")}const le=B??(F!==null?F*.2:0),U=tot*le*Math.sqrt(ie),G=he==="g"?ue:F!==null?F*ue:ue*5,Z=U+G,J=F!==null?F*ie+Z:0,re=F&&F>0?Math.floor(ge/F):null,se=re!==null?Km(ce,re):null,fe=F&&F>0?Math.floor((ge-J)/F):null,me=fe!==null?Km(ce,Math.max(0,fe)):null,pe=re!==null&&ie>0&&re<=ie,V=!pe&&fe!==null&&fe<=0;return{group:de,settings:oe,totalRemainingG:ge,totalLabelG:q,totalSpools:de.spools.length,totalUsedG:Q,dailyRateG:F,dailyRateStdDev:B,rateTier:W,effectiveLeadTimeDays:ie,safetyStockG:Z,reorderPointG:J,daysRemaining:re,daysUntilROP:fe,projectedEmptyDate:se,reorderTriggerDate:me,reorderAlert:V,stockBreakAlert:pe}})},[R,C,E,D]),O=y.useMemo(()=>{const ce=[...I];return ce.sort((de,oe)=>{let K=0,ie=0;switch(u){case"material":K=[de.group.material,de.group.subtype??"",de.group.brand??""].join(" ").toLowerCase(),ie=[oe.group.material,oe.group.subtype??"",oe.group.brand??""].join(" ").toLowerCase();break;case"used":K=de.totalUsedG,ie=oe.totalUsedG;break;case"days_left":K=de.daysRemaining??999999,ie=oe.daysRemaining??999999;break;case"stock":K=de.totalRemainingG,ie=oe.totalRemainingG;break}const ue=Kie?1:0;return p==="asc"?ue:-ue}),ce},[I,u,p]),z=y.useMemo(()=>I.filter(ce=>!ce.settings?.alerts_snoozed&&(ce.stockBreakAlert||ce.reorderAlert)),[I]),X=y.useMemo(()=>[...I].filter(ce=>ce.dailyRateG!==null).sort((ce,de)=>de.totalUsedG-ce.totalUsedG).slice(0,5),[I]);if(!o)return r.jsxs("div",{className:"flex flex-col items-center justify-center py-16 text-bambu-gray gap-3",children:[r.jsx(mc,{className:"w-8 h-8 opacity-40"}),r.jsx("p",{className:"text-sm",children:n("forecast.noReadAccess")})]});function ae(ce){u===ce?f(de=>de==="asc"?"desc":"asc"):(m(ce),f(ce==="days_left"?"asc":"desc"))}const Y=j.length>0?j.length:null;return r.jsxs("div",{className:"space-y-5",children:[r.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[z.length>0&&r.jsxs("button",{onClick:()=>d(ce=>!ce),className:`flex items-center gap-2 px-3 py-1.5 rounded-lg border text-sm font-medium transition-colors ${z.some(ce=>ce.stockBreakAlert)?"bg-red-500/15 border-red-500/30 text-red-300 hover:bg-red-500/25":"bg-yellow-500/15 border-yellow-500/30 text-yellow-300 hover:bg-yellow-500/25"}`,children:[r.jsx(xa,{className:"w-4 h-4"}),n("forecast.alertCount",{count:z.length}),c?r.jsx(el,{className:"w-3.5 h-3.5"}):r.jsx(za,{className:"w-3.5 h-3.5"})]}),l&&r.jsx(cot,{value:D,onSave:ce=>{ne.updateSettings({forecast_global_lead_time_days:ce}).then(()=>{e.invalidateQueries({queryKey:["settings"]}),a(n("forecast.globalLeadTimeSaved"),"success")})}}),r.jsxs("button",{onClick:()=>x(ce=>!ce),className:"relative flex items-center gap-2 px-3 py-1.5 rounded-lg border border-bambu-dark-tertiary text-bambu-gray hover:bg-bambu-dark-tertiary text-sm transition-colors ml-auto",children:[r.jsx(fb,{className:"w-4 h-4"}),r.jsx("span",{className:"hidden sm:inline",children:n("forecast.shoppingList")}),Y&&r.jsx("span",{className:"absolute -top-1.5 -right-1.5 w-4 h-4 rounded-full bg-bambu-green text-white text-[10px] font-bold flex items-center justify-center",children:Y})]})]}),c&&z.length>0&&r.jsx("div",{className:"space-y-2",children:z.map(ce=>r.jsx(sot,{forecast:ce,onCart:()=>v(ce)},ce.group.key))}),b&&r.jsx(pot,{items:j,forecasts:I,globalLeadTime:D,canWrite:l,onClose:()=>x(!1),onRemove:ce=>{ne.removeFromShoppingList(ce).then(()=>e.invalidateQueries({queryKey:["shopping-list"]})).catch(()=>a(n("forecast.failedSaveSettings"),"error"))},onClear:()=>{ne.clearShoppingList().then(()=>e.invalidateQueries({queryKey:["shopping-list"]})).catch(()=>a(n("forecast.failedSaveSettings"),"error"))}}),X.length>0&&r.jsx(lot,{forecasts:X,days:S,onDaysChange:k}),I.length===0?r.jsxs("div",{className:"flex flex-col items-center justify-center py-16 text-bambu-gray",children:[r.jsx(GS,{className:"w-10 h-10 mb-3 opacity-40"}),r.jsx("p",{className:"text-sm",children:n("forecast.noSpools")})]}):r.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg overflow-hidden border border-bambu-dark-tertiary",children:[r.jsx("div",{className:"overflow-x-auto",children:r.jsxs("table",{className:"w-full",children:[r.jsx("thead",{children:r.jsxs("tr",{className:"border-b border-bambu-dark-tertiary bg-bambu-dark-tertiary/30",children:[r.jsx("th",{className:"w-8 px-4 py-3"}),r.jsx(_P,{col:"material",active:u,dir:p,onSort:ae,children:n("forecast.sku")}),r.jsx(_P,{col:"stock",active:u,dir:p,onSort:ae,children:n("forecast.stock")}),r.jsx(_P,{col:"used",active:u,dir:p,onSort:ae,children:n("forecast.dailyRate")}),r.jsx(_P,{col:"days_left",active:u,dir:p,onSort:ae,children:n("forecast.daysLeft")}),r.jsx("th",{className:"px-4 py-3 text-left text-xs font-medium text-bambu-gray uppercase tracking-wide",children:n("forecast.emptyBy")}),r.jsx("th",{className:"px-4 py-3 text-left text-xs font-medium text-bambu-gray uppercase tracking-wide",children:n("forecast.reorderBy")}),r.jsx("th",{className:"w-24 px-4 py-3"})]})}),r.jsx("tbody",{className:"divide-y divide-bambu-dark-tertiary",children:O.map(ce=>r.jsx(dot,{forecast:ce,globalLeadTime:D,canWrite:l,onSaved:()=>e.invalidateQueries({queryKey:["sku-settings"]}),onCart:()=>v(ce),showToast:a},ce.group.key))})]})}),r.jsxs("div",{className:"flex flex-wrap items-center gap-4 px-4 py-3 text-xs text-bambu-gray border-t border-bambu-dark-tertiary bg-bambu-dark-tertiary/20",children:[r.jsxs("span",{className:"flex items-center gap-1.5",children:[r.jsx("span",{className:"w-2 h-2 rounded-full bg-bambu-green inline-block"}),n("forecast.trendLegend")]}),r.jsxs("span",{className:"flex items-center gap-1.5",children:[r.jsx("span",{className:"w-2 h-2 rounded-full bg-blue-400 inline-block"}),n("forecast.estimatedLegend")]}),r.jsxs("span",{className:"flex items-center gap-1.5",children:[r.jsx("span",{className:"w-2 h-2 rounded-full bg-bambu-gray/40 inline-block"}),n("forecast.noDataLegend")]})]})]}),g&&r.jsx(fot,{forecast:g,onClose:()=>v(null),onAdd:ce=>{ne.addToShoppingList(ce).then(()=>{e.invalidateQueries({queryKey:["shopping-list"]}),a(n("forecast.addedToCart"),"success"),v(null),x(!0)}).catch(()=>a(n("forecast.failedAddItem"),"error"))}})]})}function _P({col:t,active:e,dir:a,onSort:n,children:i}){const s=e===t;return r.jsx("th",{className:"px-4 py-3 text-left text-xs font-medium text-bambu-gray uppercase tracking-wide cursor-pointer select-none hover:text-white transition-colors",onClick:()=>n(t),children:r.jsxs("span",{className:"inline-flex items-center",children:[i,s?a==="asc"?r.jsx(Qm,{className:"w-3 h-3 ml-1 text-bambu-green"}):r.jsx(Xh,{className:"w-3 h-3 ml-1 text-bambu-green"}):r.jsx(ET,{className:"w-3 h-3 ml-1 opacity-40"})]})})}function sot({forecast:t,onCart:e}){const{t:a}=wt(),n=[t.group.brand,t.group.material,t.group.subtype].filter(Boolean).join(" "),i=t.stockBreakAlert;return r.jsxs("div",{className:`flex items-center gap-3 px-4 py-3 rounded-lg border text-sm ${i?"bg-red-500/10 border-red-500/30 text-red-300":"bg-yellow-500/10 border-yellow-500/30 text-yellow-300"}`,children:[r.jsx(xa,{className:"w-4 h-4 flex-shrink-0"}),r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsx("span",{className:"font-medium",children:n}),i?r.jsxs("span",{className:"ml-2 text-xs opacity-80",children:[a("forecast.stockBreakRisk")," — ",a("forecast.stockBreakDetail",{days:t.daysRemaining,lt:t.effectiveLeadTimeDays})]}):r.jsxs("span",{className:"ml-2 text-xs opacity-80",children:[a("forecast.reorderNow")," — ",a("forecast.reorderTriggerPassed",{date:t.reorderTriggerDate?ES(t.reorderTriggerDate):"—"})]})]}),r.jsxs("button",{onClick:e,className:"flex items-center gap-1.5 px-2.5 py-1 rounded border border-current text-xs opacity-70 hover:opacity-100 transition-opacity",children:[r.jsx(fb,{className:"w-3 h-3"})," ",a("forecast.order")]})]})}const oot=[{label:"1W",value:7},{label:"1M",value:30},{label:"6M",value:180}];function lot({forecasts:t,days:e,onDaysChange:a}){const{t:n}=wt(),i=Array.from({length:e+1},(u,m)=>m),s=t.map((u,m)=>({key:u.group.key,label:[u.group.brand,u.group.material,u.group.subtype].filter(Boolean).join(" "),color:WX[m%WX.length],rop:u.reorderPointG,points:not(u,e)})),o=i.map(u=>{const m={day:u,label:Rw(Km(new Date,u))};for(const p of s){const f=p.points.find(g=>g.day===u);m[p.key]=f?.stock??0}return m}),l=(()=>{for(let u=e;u>=0;u--)if(s.some(m=>o[u]?.[m.key]>0))return u;return e})(),c=o.slice(0,l+1),d=s.filter(u=>u.rop>0);return r.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg overflow-hidden border border-bambu-dark-tertiary p-4",children:[r.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[r.jsx(GS,{className:"w-4 h-4 text-bambu-green"}),r.jsx("h3",{className:"text-sm font-semibold text-white",children:n("forecast.chartTitle")}),r.jsx("span",{className:"text-xs text-bambu-gray ml-1 hidden sm:inline",children:n("forecast.dashedLinesROP")}),r.jsx("div",{className:"ml-auto flex items-center bg-bambu-dark-tertiary rounded-lg p-0.5",children:oot.map(u=>r.jsx("button",{onClick:()=>a(u.value),className:`px-2.5 py-1 text-xs font-medium rounded-md transition-colors ${e===u.value?"bg-bambu-dark-secondary text-white shadow":"text-bambu-gray hover:text-white"}`,children:u.label},u.value))})]}),r.jsx(ou,{width:"100%",height:220,children:r.jsxs(jB,{data:c,margin:{top:4,right:8,bottom:0,left:0},children:[r.jsx("defs",{children:s.map(u=>r.jsxs("linearGradient",{id:`grad-${u.key}`,x1:"0",y1:"0",x2:"0",y2:"1",children:[r.jsx("stop",{offset:"5%",stopColor:u.color,stopOpacity:.25}),r.jsx("stop",{offset:"95%",stopColor:u.color,stopOpacity:.02})]},u.key))}),r.jsx(Em,{strokeDasharray:"3 3",stroke:"#374151",strokeOpacity:.5}),r.jsx(Dm,{dataKey:"label",tick:{fill:"#6B7280",fontSize:10},interval:Math.max(0,Math.ceil(l/8)-1),axisLine:!1,tickLine:!1}),r.jsx(Fm,{tick:{fill:"#6B7280",fontSize:10},axisLine:!1,tickLine:!1,tickFormatter:u=>u>=1e3?`${(u/1e3).toFixed(1)}kg`:`${u}g`,width:48}),r.jsx(cu,{contentStyle:{background:"#1a1a2e",border:"1px solid #374151",borderRadius:8,fontSize:12},labelStyle:{color:"#9CA3AF"},itemStyle:{color:"#E5E7EB"},formatter:(u,m)=>{if(typeof u!="number")return"";const p=s.find(f=>f.key===String(m));return`${u}g — ${p?.label??m}`}}),r.jsx(e4,{formatter:u=>{const m=s.find(p=>p.key===u);return r.jsx("span",{style:{color:"#9CA3AF",fontSize:11},children:m?.label??u})}}),s.map(u=>r.jsx(KA,{type:"monotone",dataKey:u.key,stroke:u.color,strokeWidth:2,fill:`url(#grad-${u.key})`,dot:!1,activeDot:{r:3}},u.key)),d.map(u=>r.jsx(du,{y:u.rop,stroke:u.color,strokeDasharray:"4 3",strokeOpacity:.6},`rop-${u.key}`))]})})]})}function cot({value:t,onSave:e}){const{t:a}=wt(),[n,i]=y.useState(!1),[s,o]=y.useState(String(t));function l(){const c=parseInt(s,10);isNaN(c)||c<0||(e(c),i(!1))}return r.jsxs("div",{className:"flex items-center gap-2 px-3 py-1.5 bg-bambu-dark-tertiary/40 rounded-lg border border-bambu-dark-tertiary text-xs text-bambu-gray",children:[r.jsx(yi,{className:"w-3.5 h-3.5 flex-shrink-0","aria-label":a("forecast.globalLeadTimeHint")}),r.jsxs("span",{className:"hidden sm:inline",children:[a("forecast.globalLeadTime"),":"]}),n?r.jsxs("form",{className:"flex items-center gap-1.5",onSubmit:c=>{c.preventDefault(),l()},children:[r.jsx("input",{type:"number",min:0,max:365,value:s,onChange:c=>o(c.target.value),className:"w-14 px-1.5 py-0.5 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-sm text-white focus:outline-none focus:border-bambu-green",autoFocus:!0}),r.jsx("span",{className:"text-bambu-gray",children:"d"}),r.jsx("button",{type:"submit",className:"px-2 py-0.5 bg-bambu-green text-white text-xs rounded hover:bg-bambu-green/80",children:a("forecast.save")}),r.jsx("button",{type:"button",onClick:()=>i(!1),className:"text-xs text-bambu-gray hover:text-white",children:"✕"})]}):r.jsxs("div",{className:"flex items-center gap-1.5",children:[r.jsxs("span",{className:"font-semibold text-white",children:[t,"d"]}),r.jsx("button",{onClick:()=>{o(String(t)),i(!0)},className:"p-0.5 text-bambu-gray hover:text-white rounded transition-colors",children:r.jsx(vc,{className:"w-3 h-3"})})]})]})}function dot({forecast:t,globalLeadTime:e,canWrite:a,onSaved:n,onCart:i,showToast:s}){const{t:o}=wt(),[l,c]=y.useState(!1),[d,u]=y.useState(!1),[m,p]=y.useState(!1),[f,g]=y.useState(String(t.settings?.lead_time_days??0)),[v,b]=y.useState(String(t.settings?.safety_margin_value??14)),[x,S]=y.useState(t.settings?.safety_margin_unit??"days");y.useEffect(()=>{d||g(String(t.settings?.lead_time_days??0))},[t.settings?.lead_time_days,d]),y.useEffect(()=>{m||(b(String(t.settings?.safety_margin_value??14)),S(t.settings?.safety_margin_unit??"days"))},[t.settings?.safety_margin_value,t.settings?.safety_margin_unit,m]);const k=rt({mutationFn:ne.upsertSkuSettings,onSuccess:()=>{n(),s(o("forecast.settingsSaved"),"success")},onError:()=>s(o("forecast.failedSaveSettings"),"error")}),P=t.settings?.alerts_snoozed??!1,N=[t.group.brand,t.group.material,t.group.subtype].filter(Boolean).join(" "),T=t.group.spools[0]?.rgba?al(t.group.spools[0].rgba):{backgroundColor:"#4B5563"},j=t.totalLabelG>0?Math.round(t.totalRemainingG/t.totalLabelG*100):0,D=P||t.daysRemaining===null?"text-bambu-gray":t.stockBreakAlert?"text-red-400":t.reorderAlert||t.daysRemaining<30?"text-yellow-400":"text-green-400";function C(O,z,X,ae=P){k.mutate({material:t.group.material,subtype:t.group.subtype,brand:t.group.brand,lead_time_days:O,safety_margin_value:z,safety_margin_unit:X,alerts_snoozed:ae})}function E(O){O.stopPropagation(),C(t.settings?.lead_time_days??0,t.settings?.safety_margin_value??14,t.settings?.safety_margin_unit??"days",!P)}const R=t.rateTier==="history"?r.jsxs("span",{className:"inline-flex items-center gap-1 text-xs px-1.5 py-0.5 rounded bg-bambu-green/15 text-bambu-green",children:[r.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-bambu-green"}),o("forecast.trend")]}):t.rateTier==="delta"?r.jsxs("span",{className:"inline-flex items-center gap-1 text-xs px-1.5 py-0.5 rounded bg-blue-400/15 text-blue-400",children:[r.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-blue-400"}),o("forecast.estimated")]}):r.jsxs("span",{className:"inline-flex items-center gap-1 text-xs px-1.5 py-0.5 rounded bg-bambu-dark-tertiary text-bambu-gray/60",children:[r.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-bambu-gray/40"}),o("forecast.noData")]}),I=P?"":t.stockBreakAlert?"bg-red-500/5":t.reorderAlert?"bg-yellow-500/5":"";return r.jsxs(r.Fragment,{children:[r.jsxs("tr",{className:`cursor-pointer hover:bg-bambu-dark-tertiary/40 transition-colors ${I} ${P?"opacity-50":""}`,onClick:()=>c(O=>!O),children:[r.jsx("td",{className:"px-4 py-3",children:r.jsx("span",{className:"block w-3 h-3 rounded-full border border-black/20",style:T})}),r.jsxs("td",{className:"px-4 py-3",children:[r.jsx("div",{className:"text-sm font-medium text-white",children:N}),r.jsx("div",{className:"text-xs text-bambu-gray",children:o("forecast.spoolCount",{count:t.totalSpools})})]}),r.jsxs("td",{className:"px-4 py-3 min-w-[120px]",children:[r.jsx("div",{className:"h-1.5 bg-bambu-dark-tertiary rounded-full overflow-hidden mb-1 w-24",children:r.jsx("div",{className:`h-full rounded-full ${j>50?"bg-bambu-green":j>20?"bg-yellow-500":"bg-red-500"}`,style:{width:`${Math.min(j,100)}%`}})}),r.jsxs("span",{className:"text-xs text-bambu-gray",children:[Math.round(t.totalRemainingG),"g"]})]}),r.jsxs("td",{className:"px-4 py-3",children:[r.jsx("div",{className:"text-sm text-white",children:t.dailyRateG!==null?`${t.dailyRateG.toFixed(1)}g/d`:"—"}),r.jsx("div",{className:"mt-0.5",children:R})]}),r.jsx("td",{className:"px-4 py-3",children:r.jsx("span",{className:`text-sm font-semibold ${D}`,children:t.daysRemaining!==null?`${t.daysRemaining}d`:r.jsx("span",{className:"text-bambu-gray font-normal",children:"—"})})}),r.jsx("td",{className:"px-4 py-3",children:r.jsx("span",{className:"text-sm text-bambu-gray",children:t.projectedEmptyDate?ES(t.projectedEmptyDate):"—"})}),r.jsx("td",{className:"px-4 py-3",children:r.jsx("span",{className:`text-sm font-medium ${!P&&t.reorderAlert?"text-yellow-400":"text-bambu-gray"}`,children:t.reorderTriggerDate?ES(t.reorderTriggerDate):"—"})}),r.jsx("td",{className:"px-4 py-3",onClick:O=>O.stopPropagation(),children:r.jsxs("div",{className:"flex items-center justify-end gap-1",children:[a&&r.jsx("button",{onClick:i,className:"p-1.5 text-bambu-gray hover:text-bambu-green rounded transition-colors",title:o("forecast.addToCart"),children:r.jsx(fb,{className:"w-4 h-4"})}),!P&&(t.stockBreakAlert?r.jsx(xa,{className:"w-4 h-4 text-red-400","aria-label":o("forecast.stockBreakRisk")}):t.reorderAlert?r.jsx(xa,{className:"w-4 h-4 text-yellow-400","aria-label":o("forecast.reorderNow")}):t.daysRemaining!==null?r.jsx(_r,{className:"w-4 h-4 text-bambu-green/50"}):null),a&&r.jsx("button",{onClick:E,className:`p-1 rounded transition-colors ${P?"text-bambu-gray/70 hover:text-white":"text-bambu-dark-tertiary hover:text-bambu-gray"}`,title:o(P?"forecast.alertsEnabled":"forecast.alertsSnoozed"),children:r.jsx(aJ,{className:"w-3.5 h-3.5"})}),r.jsx("button",{onClick:O=>{O.stopPropagation(),c(z=>!z)},className:"p-1.5 text-bambu-gray hover:text-white rounded transition-colors",children:l?r.jsx(el,{className:"w-4 h-4"}):r.jsx(za,{className:"w-4 h-4"})})]})})]}),l&&r.jsx("tr",{className:"bg-bambu-dark-tertiary/10",children:r.jsx("td",{colSpan:8,className:"px-6 py-4",children:r.jsxs("div",{className:"space-y-4",children:[r.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[r.jsx(LL,{label:o("forecast.effectiveLeadTime"),value:`${t.effectiveLeadTimeDays}d`,hint:o("forecast.effectiveLeadTimeHint",{global:e,sku:t.settings?.lead_time_days??0})}),r.jsx(LL,{label:o("forecast.safetyMarginLabel"),value:`${Math.round(t.safetyStockG)}g`,hint:o("forecast.safetyMarginHint")}),r.jsx(LL,{label:o("forecast.reorderPoint"),value:`${Math.round(t.reorderPointG)}g`,hint:o("forecast.reorderPointHint")})]}),a&&r.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[r.jsx(uot,{label:o("forecast.skuLeadTimeOverride"),hint:o("forecast.skuLeadTimeHint"),unit:o("forecast.leadTime"),editing:d,value:t.settings?.lead_time_days??0,inputValue:f,onInputChange:g,onEdit:()=>{g(String(t.settings?.lead_time_days??0)),u(!0)},onSave:()=>{const O=parseInt(f,10);!isNaN(O)&&O>=0&&(C(O,t.settings?.safety_margin_value??14,x),u(!1))},onCancel:()=>u(!1),isPending:k.isPending,saveLabel:o("forecast.save"),cancelLabel:o("forecast.cancel")}),r.jsx(mot,{value:t.settings?.safety_margin_value??14,unit:x,editing:m,inputValue:v,dailyRateG:t.dailyRateG,onInputChange:b,onUnitChange:O=>S(O),onEdit:()=>{b(String(t.settings?.safety_margin_value??14)),S(t.settings?.safety_margin_unit??"days"),p(!0)},onSave:()=>{const O=parseInt(v,10);!isNaN(O)&&O>=0&&(C(t.settings?.lead_time_days??0,O,x),p(!1))},onCancel:()=>p(!1),isPending:k.isPending,saveLabel:o("forecast.save"),cancelLabel:o("forecast.cancel"),safetyMarginLabel:o("forecast.safetyMarginLabel")})]}),t.group.spools.length>1&&r.jsxs("div",{className:"border-t border-bambu-dark-tertiary pt-3",children:[r.jsx("p",{className:"text-xs text-bambu-gray mb-2",children:o("forecast.individualSpools")}),r.jsx("div",{className:"bg-bambu-dark-secondary rounded-lg overflow-hidden border border-bambu-dark-tertiary",children:r.jsxs("table",{className:"w-full",children:[r.jsx("thead",{children:r.jsxs("tr",{className:"border-b border-bambu-dark-tertiary bg-bambu-dark-tertiary/30",children:[r.jsx("th",{className:"px-4 py-2 text-left text-xs font-medium text-bambu-gray uppercase tracking-wide",children:"#"}),r.jsx("th",{className:"px-4 py-2 text-left text-xs font-medium text-bambu-gray uppercase tracking-wide",children:o("inventory.remaining")}),r.jsx("th",{className:"px-4 py-2 text-left text-xs font-medium text-bambu-gray uppercase tracking-wide",children:o("inventory.used")}),r.jsx("th",{className:"px-4 py-2 text-left text-xs font-medium text-bambu-gray uppercase tracking-wide",children:o("forecast.labelWeight")})]})}),r.jsx("tbody",{className:"divide-y divide-bambu-dark-tertiary",children:t.group.spools.map(O=>{const z=Math.max(0,O.label_weight-O.weight_used),X=O.label_weight>0?z/O.label_weight*100:0;return r.jsxs("tr",{className:"hover:bg-bambu-dark-tertiary/30 transition-colors",children:[r.jsx("td",{className:"px-4 py-2",children:r.jsxs("span",{className:"text-xs font-mono text-bambu-gray/70",children:["#",O.id]})}),r.jsx("td",{className:"px-4 py-2",children:r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("div",{className:"w-24 h-1.5 bg-bambu-dark-tertiary rounded-full overflow-hidden flex-shrink-0",children:r.jsx("div",{className:`h-full rounded-full ${X>50?"bg-bambu-green":X>20?"bg-yellow-500":"bg-red-500"}`,style:{width:`${Math.min(X,100)}%`}})}),r.jsxs("span",{className:"text-sm text-white",children:[Math.round(z),"g"]})]})}),r.jsx("td",{className:"px-4 py-2",children:r.jsxs("span",{className:"text-sm text-bambu-gray",children:[Math.round(Math.max(0,O.weight_used-(O.weight_used_baseline??0))),"g"]})}),r.jsx("td",{className:"px-4 py-2",children:r.jsxs("span",{className:"text-sm text-bambu-gray",children:[O.label_weight,"g"]})})]},O.id)})})]})})]})]})})})]})}function LL({label:t,value:e,hint:a}){return r.jsxs("div",{className:"bg-bambu-dark-tertiary/40 rounded-lg p-3",title:a,children:[r.jsx("div",{className:"text-xs text-bambu-gray mb-1",children:t}),r.jsx("div",{className:"text-lg font-semibold text-white",children:e})]})}function uot({label:t,hint:e,unit:a,editing:n,value:i,inputValue:s,onInputChange:o,onEdit:l,onSave:c,onCancel:d,isPending:u,saveLabel:m="Save",cancelLabel:p="Cancel"}){return r.jsxs("div",{className:"bg-bambu-dark-tertiary/40 rounded-lg p-3 space-y-1",children:[r.jsxs("div",{className:"flex items-center gap-1.5",children:[r.jsx("span",{className:"text-xs font-medium text-white",children:t}),r.jsx("span",{title:e,children:r.jsx(yi,{className:"w-3 h-3 text-bambu-gray/50"})})]}),n?r.jsxs("form",{className:"flex items-center gap-2",onSubmit:f=>{f.preventDefault(),c()},children:[r.jsx("input",{type:"number",min:0,max:365,value:s,onChange:f=>o(f.target.value),className:"w-20 px-2 py-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-sm text-white focus:outline-none focus:border-bambu-green",autoFocus:!0,disabled:u}),r.jsx("span",{className:"text-xs text-bambu-gray",children:a}),r.jsx("button",{type:"submit",disabled:u,className:"px-2 py-1 bg-bambu-green text-white text-xs rounded hover:bg-bambu-green/80 disabled:opacity-50",children:m}),r.jsx("button",{type:"button",onClick:d,disabled:u,className:"px-2 py-1 text-xs text-bambu-gray hover:text-white",children:p})]}):r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("span",{className:"text-lg font-semibold text-white",children:i}),r.jsx("span",{className:"text-xs text-bambu-gray",children:a}),r.jsx("button",{onClick:l,className:"p-1 text-bambu-gray hover:text-white rounded transition-colors",children:r.jsx(vc,{className:"w-3 h-3"})})]})]})}function mot({value:t,unit:e,editing:a,inputValue:n,dailyRateG:i,onInputChange:s,onUnitChange:o,onEdit:l,onSave:c,onCancel:d,isPending:u,saveLabel:m="Save",cancelLabel:p="Cancel",safetyMarginLabel:f="Safety Margin"}){const{t:g}=wt(),v=e==="g"?t:i!==null?Math.round(i*t):null,b=e==="days"?g("forecast.safetyMarginHintDays",{approx:v!==null?g("forecast.safetyMarginHintDaysApprox",{g:v}):""}):g("forecast.safetyMarginHintG",{approx:i!==null?g("forecast.safetyMarginHintGApprox",{days:Math.round(t/i)}):""});return r.jsxs("div",{className:"bg-bambu-dark-tertiary/40 rounded-lg p-3 space-y-1",children:[r.jsxs("div",{className:"flex items-center gap-1.5",children:[r.jsx("span",{className:"text-xs font-medium text-white",children:f}),r.jsx("span",{title:b,children:r.jsx(yi,{className:"w-3 h-3 text-bambu-gray/50"})})]}),a?r.jsxs("form",{className:"flex items-center gap-2 flex-wrap",onSubmit:x=>{x.preventDefault(),c()},children:[r.jsx("input",{type:"number",min:0,max:e==="g"?1e4:365,value:n,onChange:x=>s(x.target.value),className:"w-20 px-2 py-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-sm text-white focus:outline-none focus:border-bambu-green",autoFocus:!0,disabled:u}),r.jsxs("div",{className:"flex bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded overflow-hidden text-xs",children:[r.jsx("button",{type:"button",onClick:()=>o("days"),className:`px-2 py-1 transition-colors ${e==="days"?"bg-bambu-green text-white":"text-bambu-gray hover:text-white"}`,children:"days"}),r.jsx("button",{type:"button",onClick:()=>o("g"),className:`px-2 py-1 transition-colors ${e==="g"?"bg-bambu-green text-white":"text-bambu-gray hover:text-white"}`,children:"g"})]}),r.jsx("button",{type:"submit",disabled:u,className:"px-2 py-1 bg-bambu-green text-white text-xs rounded hover:bg-bambu-green/80 disabled:opacity-50",children:m}),r.jsx("button",{type:"button",onClick:d,disabled:u,className:"px-2 py-1 text-xs text-bambu-gray hover:text-white",children:p})]}):r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("span",{className:"text-lg font-semibold text-white",children:t}),r.jsx("span",{className:"text-xs text-bambu-gray",children:e}),v!==null&&e==="days"&&r.jsxs("span",{className:"text-xs text-bambu-gray/60",children:["≈ ",v,"g"]}),e==="g"&&i!==null&&r.jsxs("span",{className:"text-xs text-bambu-gray/60",children:["≈ ",Math.round(t/i),"d"]}),r.jsx("button",{onClick:l,className:"p-1 text-bambu-gray hover:text-white rounded transition-colors",children:r.jsx(vc,{className:"w-3 h-3"})})]})]})}function pot({items:t,forecasts:e,globalLeadTime:a,canWrite:n,onClose:i,onRemove:s,onClear:o}){const{t:l}=wt(),c=ia(),[d,u]=y.useState("list"),m=rt({mutationFn:async({id:b,status:x,item:S,avgSpoolG:k})=>{if(await ne.updateShoppingListStatus(b,x),x==="received"&&S){const P=k??1e3,N={material:S.material,subtype:S.subtype,brand:S.brand,label_weight:P,core_weight:0,core_weight_catalog_id:null,color_name:null,rgba:null,extra_colors:null,effect_type:null,nozzle_temp_min:null,nozzle_temp_max:null,note:S.note??null,tag_uid:null,tray_uuid:null,data_origin:"manual",tag_type:null,cost_per_kg:null,last_scale_weight:null,last_weighed_at:null,weight_used:0,slicer_filament:null,slicer_filament_name:null,added_full:null,last_used:null,encode_time:null,category:"Stock",low_stock_threshold_pct:null};await ne.bulkCreateSpools(N,S.quantity_spools),await ne.removeFromShoppingList(b)}},onSuccess:()=>{c.invalidateQueries({queryKey:["shopping-list"]}),c.invalidateQueries({queryKey:["spools"]})}}),p=y.useMemo(()=>{const b=new Map;for(const x of e)b.set(x.group.key,x);return b},[e]),f=y.useMemo(()=>t.map(b=>({item:b,forecast:p.get(Lw(b.material,b.subtype,b.brand))??null})),[t,p]),g=y.useMemo(()=>f.filter(({forecast:b})=>!b||b.dailyRateG===null?!1:b.stockBreakAlert||b.daysRemaining!==null&&b.daysRemaining<=b.effectiveLeadTimeDays),[f]);function v(){const b=[l("forecast.qty"),l("forecast.material"),"Brand","Subtype",`${l("forecast.weight")} (g)`,`${l("forecast.leadTime")} (d)`,l("forecast.expectedRestock"),l("forecast.status"),l("forecast.note")],x=t.map(T=>{const j=p.get(Lw(T.material,T.subtype,T.brand))??null,D=j&&j.totalSpools>0?j.totalLabelG/j.totalSpools:1e3,C=Math.round(T.quantity_spools*D),E=j?.effectiveLeadTimeDays??a??0,R=E>0?ES(Km(new Date,E)):"";return[T.quantity_spools,T.material,T.brand??"",T.subtype??"",C,E||"",R,T.status,T.note??""].map(I=>`"${String(I).replace(/"/g,'""')}"`).join(",")}),S=[b.join(","),...x].join(`
+`+a+"}"}return String(t)}function ust({setting:t,onClose:e,onDeleted:a,onDuplicate:n,onEdit:i,hasPermission:s,t:o}){const{showToast:l}=da(),c=ia(),[d,u]=y.useState(!1),{data:m,isLoading:p}=$e({queryKey:["cloudSettingDetail",t.setting_id],queryFn:()=>ne.getCloudSettingDetail(t.setting_id)}),f=rt({mutationFn:()=>ne.deleteCloudSetting(t.setting_id),onSuccess:()=>{l(o("profiles.presets.toast.deleted")),c.invalidateQueries({queryKey:["cloudSettings"]}),a()},onError:b=>l(b.message,"error")}),g=MS(t.setting_id),v=T5(t.name,m?.setting?.inherits);return r.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:r.jsx(Tt,{className:"w-full max-w-3xl max-h-[90vh] flex flex-col overflow-hidden",children:r.jsxs(jt,{className:"p-0 flex flex-col min-h-0 flex-1",children:[r.jsxs("div",{className:"flex-shrink-0 flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("h2",{className:"text-xl font-semibold text-white truncate",children:t.name}),g&&r.jsx("span",{className:"px-2 py-0.5 text-xs font-medium bg-bambu-green/20 text-bambu-green rounded-full",children:o("profiles.presets.editable")})]}),r.jsxs("div",{className:"flex items-center gap-2 mt-1 text-sm text-bambu-gray",children:[r.jsx("span",{className:"capitalize",children:o(`profiles.presets.types.${t.type}`)}),v.printer&&r.jsxs(r.Fragment,{children:[r.jsx("span",{children:"•"}),r.jsx("span",{children:v.printer})]})]})]}),r.jsx("button",{onClick:e,className:"p-2 text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary rounded-lg transition-colors",children:r.jsx(Ht,{className:"w-5 h-5"})})]}),r.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto p-4",children:p?r.jsx("div",{className:"flex items-center justify-center py-16",children:r.jsx(lt,{className:"w-8 h-8 text-bambu-green animate-spin"})}):m?r.jsx("pre",{className:"text-xs text-bambu-gray font-mono whitespace-pre-wrap break-all bg-bambu-dark p-4 rounded-lg border border-bambu-dark-tertiary overflow-x-auto max-w-full",children:fI(m)}):r.jsx("div",{className:"text-center py-16 text-bambu-gray",children:o("profiles.presets.failedToLoadDetails")})}),d?r.jsxs("div",{className:"flex-shrink-0 p-4 border-t border-bambu-dark-tertiary bg-red-500/5",children:[r.jsxs("div",{className:"flex items-center gap-2 mb-3 text-red-400",children:[r.jsx(xa,{className:"w-5 h-5"}),r.jsx("span",{className:"font-medium",children:o("profiles.presets.deleteConfirm")})]}),r.jsx("p",{className:"text-sm text-bambu-gray mb-4",children:o("profiles.presets.deleteWarning",{name:t.name})}),r.jsxs("div",{className:"flex gap-2",children:[r.jsx(Le,{variant:"secondary",onClick:()=>u(!1),disabled:f.isPending,className:"flex-1",children:o("common.cancel")}),r.jsxs(Le,{variant:"danger",onClick:()=>f.mutate(),disabled:f.isPending,className:"flex-1",children:[f.isPending?r.jsx(lt,{className:"w-4 h-4 animate-spin"}):r.jsx(na,{className:"w-4 h-4"}),o("common.delete")]})]})]}):r.jsx("div",{className:"flex-shrink-0 p-4 border-t border-bambu-dark-tertiary",children:r.jsxs("div",{className:"flex gap-2",children:[r.jsx(Le,{variant:"secondary",onClick:e,className:"flex-1",children:o("common.close")}),r.jsxs(Le,{variant:"secondary",onClick:n,disabled:!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.presets.noDuplicatePermission"),children:[r.jsx(li,{className:"w-4 h-4"}),o("profiles.presets.duplicate")]}),g&&r.jsxs(r.Fragment,{children:[r.jsxs(Le,{variant:"secondary",onClick:i,disabled:p||!m||!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.presets.noEditPermission"),children:[r.jsx(ci,{className:"w-4 h-4"}),o("common.edit")]}),r.jsx(Le,{variant:"danger",onClick:()=>u(!0),disabled:!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.presets.noDeletePermission"),children:r.jsx(na,{className:"w-4 h-4"})})]})]})})]})})})}function Pde(){try{const t=localStorage.getItem("bambusy_preset_templates");return t?JSON.parse(t):[]}catch{return[]}}function Nde(t){localStorage.setItem("bambusy_preset_templates",JSON.stringify(t))}function mst({onClose:t,onApply:e,t:a}){const{showToast:n}=da(),[i,s]=y.useState(Pde),[o,l]=y.useState("all"),[c,d]=y.useState(null),[u,m]=y.useState(""),[p,f]=y.useState(""),[g,v]=y.useState("{}"),[b,x]=y.useState(null),[S,k]=y.useState(null),P=o==="all"?i:i.filter(O=>O.type===o),N=O=>{s(O),Nde(O)},T=O=>{const z=i.filter(X=>X.id!==O);N(z),k(null),n(a("profiles.templates.toast.deleted"))},j=O=>{d(O.id),m(O.name),f(O.description),v(JSON.stringify(O.settings,null,2)),x(null)},D=()=>{if(!(!c||!u.trim()))try{const O=JSON.parse(g),z=i.map(X=>X.id===c?{...X,name:u.trim(),description:p.trim(),settings:O}:X);N(z),d(null),n(a("profiles.templates.toast.updated"))}catch(O){x(O.message)}},C=()=>{d(null),m(""),f(""),v("{}"),x(null)},E=O=>{const z=i.map(X=>X.id===O?{...X,showInModal:!X.showInModal}:X);N(z)},R={filament:{label:a("profiles.presets.types.filament"),icon:RS,color:"text-amber-400"},print:{label:a("profiles.presets.types.process"),icon:xd,color:"text-blue-400"},printer:{label:a("profiles.presets.types.printer"),icon:xr,color:"text-purple-400"}},I=S?i.find(O=>O.id===S):null;return y.useEffect(()=>{const O=z=>{z.key==="Escape"&&(S?k(null):c?C():t())};return window.addEventListener("keydown",O),()=>window.removeEventListener("keydown",O)},[S,c,t]),r.jsxs("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:[I&&r.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-60",children:r.jsx(Tt,{className:"w-full max-w-md",children:r.jsxs(jt,{className:"p-6",children:[r.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[r.jsx("div",{className:"p-2 bg-red-500/20 rounded-lg",children:r.jsx(xa,{className:"w-6 h-6 text-red-400"})}),r.jsxs("div",{children:[r.jsx("h3",{className:"text-lg font-semibold text-white",children:a("profiles.templates.deleteTitle")}),r.jsx("p",{className:"text-sm text-bambu-gray",children:a("profiles.templates.deleteWarning")})]})]}),r.jsx("p",{className:"text-white mb-6",children:a("profiles.templates.deleteConfirm",{name:I.name})}),r.jsxs("div",{className:"flex gap-2",children:[r.jsx(Le,{variant:"secondary",onClick:()=>k(null),className:"flex-1",children:a("common.cancel")}),r.jsxs(Le,{onClick:()=>T(S),className:"flex-1 bg-red-500 hover:bg-red-600",children:[r.jsx(na,{className:"w-4 h-4"}),a("common.delete")]})]})]})})}),r.jsx(Tt,{className:"w-full max-w-2xl max-h-[80vh] flex flex-col",children:r.jsxs(jt,{className:"p-0 flex flex-col h-full",children:[r.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[r.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[r.jsx(Ug,{className:"w-5 h-5 text-amber-400"}),a("profiles.templates.title")]}),r.jsx("button",{onClick:t,className:"text-bambu-gray hover:text-white",children:r.jsx(Ht,{className:"w-5 h-5"})})]}),r.jsxs("div",{className:"flex items-center gap-2 p-4 border-b border-bambu-dark-tertiary",children:[r.jsx("span",{className:"text-sm text-bambu-gray",children:a("profiles.templates.typeFilter")}),["all","filament","print","printer"].map(O=>r.jsx("button",{onClick:()=>l(O),className:`px-3 py-1 text-sm rounded-lg transition-colors ${o===O?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:O==="all"?a("common.all"):R[O].label},O))]}),r.jsx("div",{className:"flex-1 overflow-y-auto p-4",children:P.length===0?r.jsxs("div",{className:"text-center py-12 text-bambu-gray",children:[r.jsx(Ug,{className:"w-12 h-12 mx-auto mb-4 opacity-30"}),r.jsx("p",{children:a("profiles.templates.noTemplates")}),r.jsx("p",{className:"text-sm mt-1",children:a("profiles.templates.createFirst")})]}):r.jsx("div",{className:"space-y-2",children:P.map(O=>{const z=R[O.type],X=z.icon;return c===O.id?r.jsxs("div",{className:"p-4 bg-bambu-dark rounded-lg border border-bambu-green",children:[r.jsxs("div",{className:"grid grid-cols-2 gap-3 mb-3",children:[r.jsx("input",{type:"text",value:u,onChange:ae=>m(ae.target.value),placeholder:a("profiles.templates.namePlaceholder"),className:"px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none",autoFocus:!0}),r.jsx("input",{type:"text",value:p,onChange:ae=>f(ae.target.value),placeholder:a("profiles.templates.descriptionPlaceholder"),className:"px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none"})]}),r.jsxs("div",{className:"mb-3",children:[r.jsx("label",{className:"text-xs text-bambu-gray mb-1 block",children:a("profiles.templates.settingsJson")}),r.jsx("textarea",{value:g,onChange:ae=>{v(ae.target.value),x(null)},rows:6,className:`w-full px-3 py-2 bg-bambu-dark-secondary border rounded text-white text-sm font-mono focus:outline-none ${b?"border-red-500":"border-bambu-dark-tertiary focus:border-bambu-green"}`}),b&&r.jsx("p",{className:"text-xs text-red-400 mt-1",children:b})]}),r.jsxs("div",{className:"flex gap-2",children:[r.jsxs(Le,{size:"sm",onClick:D,disabled:!u.trim(),children:[r.jsx(ms,{className:"w-4 h-4"}),"Save"]}),r.jsx(Le,{size:"sm",variant:"secondary",onClick:C,children:"Cancel"})]})]},O.id):r.jsxs("div",{className:"flex items-center gap-3 p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary hover:border-bambu-gray-dark transition-colors",children:[r.jsx(X,{className:`w-5 h-5 ${z.color} flex-shrink-0`}),r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsx("p",{className:"text-sm font-medium text-white",children:O.name}),r.jsx("p",{className:"text-xs text-bambu-gray truncate",children:O.description})]}),r.jsx("span",{className:"text-xs text-bambu-gray-dark px-2 py-1 bg-bambu-dark-secondary rounded",children:a("profiles.templates.fieldsCount",{count:Object.keys(O.settings).length})}),r.jsx("button",{onClick:()=>E(O.id),className:`p-1 transition-colors ${O.showInModal?"text-bambu-green hover:text-bambu-green/70":"text-bambu-gray hover:text-white"}`,title:O.showInModal?a("profiles.templates.shownInModals"):a("profiles.templates.hiddenInModals"),children:O.showInModal?r.jsx(tl,{className:"w-4 h-4"}):r.jsx(Zh,{className:"w-4 h-4"})}),r.jsx("button",{onClick:()=>e(O),className:"px-3 py-1 text-xs bg-bambu-green/20 text-bambu-green rounded hover:bg-bambu-green/30 transition-colors",children:a("profiles.templates.apply")}),r.jsx("button",{onClick:()=>j(O),className:"p-1 text-bambu-gray hover:text-white",title:a("common.edit"),children:r.jsx(ci,{className:"w-4 h-4"})}),r.jsx("button",{onClick:()=>k(O.id),className:"p-1 text-bambu-gray hover:text-red-400",title:a("common.delete"),children:r.jsx(na,{className:"w-4 h-4"})})]},O.id)})})})]})})]})}function Tde({onClose:t,leftPreset:e,rightPreset:a,leftLabel:n,rightLabel:i,t:s}){const[o,l]=y.useState("changes"),[c,d]=y.useState(""),u=y.useMemo(()=>{const g=new Set([...Object.keys(e),...Object.keys(a)]),v=[];for(const b of g){if(b==="inherits"||b==="version")continue;const x=e[b],S=a[b],k=b in e,P=b in a;let N;!k&&P?N="added":k&&!P?N="removed":JSON.stringify(x)!==JSON.stringify(S)?N="changed":N="same",v.push({key:b,left:x,right:S,status:N})}return v.sort((b,x)=>{const S={changed:0,added:1,removed:2,same:3};return S[b.status]!==S[x.status]?S[b.status]-S[x.status]:b.key.localeCompare(x.key)})},[e,a]),m=y.useMemo(()=>{let g=[...u];if(o==="changes"&&(g=g.filter(v=>v.status!=="same")),c){const v=c.toLowerCase();g=g.filter(b=>b.key.toLowerCase().includes(v)||String(b.left).toLowerCase().includes(v)||String(b.right).toLowerCase().includes(v))}return g},[u,o,c]),p=y.useMemo(()=>({added:u.filter(g=>g.status==="added").length,removed:u.filter(g=>g.status==="removed").length,changed:u.filter(g=>g.status==="changed").length,same:u.filter(g=>g.status==="same").length}),[u]),f=g=>{if(g===void 0)return"—";if(g===null)return"null";if(Array.isArray(g))return g.length===0?"[]":g.length===1?String(g[0]):g.join(", ");if(typeof g=="object")return JSON.stringify(g);const v=String(g);if(v.includes("\\n")||v.length>100){const b=v.split("\\n").length;if(b>1)return`[${b} lines of G-code/script]`;if(v.length>100)return v.substring(0,100)+"…"}return v};return y.useEffect(()=>{const g=v=>{v.key==="Escape"&&t()};return window.addEventListener("keydown",g),()=>window.removeEventListener("keydown",g)},[t]),r.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:r.jsx(Tt,{className:"w-full max-w-4xl max-h-[85vh] flex flex-col overflow-hidden",children:r.jsxs(jt,{className:"p-0 flex flex-col min-h-0 flex-1",children:[r.jsxs("div",{className:"flex-shrink-0 flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[r.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[r.jsx(sy,{className:"w-5 h-5 text-blue-400"}),s("profiles.diff.title")]}),r.jsx("button",{onClick:t,className:"text-bambu-gray hover:text-white",children:r.jsx(Ht,{className:"w-5 h-5"})})]}),r.jsxs("div",{className:"flex-shrink-0 grid grid-cols-2 gap-4 p-4 border-b border-bambu-dark-tertiary bg-bambu-dark",children:[r.jsxs("div",{className:"text-center",children:[r.jsx("span",{className:"text-sm text-bambu-gray",children:s("profiles.diff.left")}),r.jsx("p",{className:"text-white font-medium truncate",children:n})]}),r.jsxs("div",{className:"text-center",children:[r.jsx("span",{className:"text-sm text-bambu-gray",children:s("profiles.diff.right")}),r.jsx("p",{className:"text-white font-medium truncate",children:i})]})]}),r.jsxs("div",{className:"flex-shrink-0 flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"flex items-center gap-4 text-sm",children:[r.jsxs("span",{className:"flex items-center gap-1 text-green-400",children:[r.jsx(or,{className:"w-3.5 h-3.5"}),p.added," ",s("profiles.diff.added")]}),r.jsxs("span",{className:"flex items-center gap-1 text-red-400",children:[r.jsx(hN,{className:"w-3.5 h-3.5"}),p.removed," ",s("profiles.diff.removed")]}),r.jsxs("span",{className:"flex items-center gap-1 text-amber-400",children:[r.jsx(dN,{className:"w-3.5 h-3.5"}),p.changed," ",s("profiles.diff.changed")]}),r.jsxs("span",{className:"flex items-center gap-1 text-bambu-gray",children:[r.jsx(SE,{className:"w-3.5 h-3.5"}),p.same," ",s("profiles.diff.same")]})]}),r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsxs("div",{className:"relative",children:[r.jsx(br,{className:"absolute left-2 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),r.jsx("input",{type:"text",value:c,onChange:g=>d(g.target.value),placeholder:s("profiles.diff.searchFields"),className:"pl-8 pr-3 py-1.5 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none w-48"})]}),p.same>0&&r.jsxs("div",{className:"flex rounded overflow-hidden border border-bambu-dark-tertiary",children:[r.jsx("button",{onClick:()=>l("changes"),className:`px-3 py-1.5 text-sm transition-colors ${o==="changes"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:s("profiles.diff.changes")}),r.jsx("button",{onClick:()=>l("all"),className:`px-3 py-1.5 text-sm transition-colors ${o==="all"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:s("common.all")})]})]})]}),r.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto",children:m.length===0?r.jsxs("div",{className:"text-center py-12 text-bambu-gray",children:[r.jsx(SE,{className:"w-12 h-12 mx-auto mb-4 opacity-30"}),r.jsx("p",{children:s(o==="changes"?"profiles.diff.noDifferences":"profiles.diff.noFieldsMatch")})]}):r.jsxs("table",{className:"w-full",children:[r.jsx("thead",{className:"sticky top-0 bg-bambu-dark-secondary",children:r.jsxs("tr",{className:"text-sm text-bambu-gray border-b border-bambu-dark-tertiary",children:[r.jsx("th",{className:"text-left p-3 w-1/3",children:s("profiles.diff.field")}),r.jsx("th",{className:"text-left p-3 w-1/3",children:n}),r.jsx("th",{className:"text-left p-3 w-1/3",children:i})]})}),r.jsx("tbody",{children:m.map(g=>{const v={added:"bg-green-500/10",removed:"bg-red-500/10",changed:"bg-amber-500/10",same:""}[g.status],b={added:r.jsx(or,{className:"w-3.5 h-3.5 text-green-400"}),removed:r.jsx(hN,{className:"w-3.5 h-3.5 text-red-400"}),changed:r.jsx(dN,{className:"w-3.5 h-3.5 text-amber-400"}),same:r.jsx(SE,{className:"w-3.5 h-3.5 text-bambu-gray-dark"})}[g.status];return r.jsxs("tr",{className:`border-b border-bambu-dark-tertiary ${v}`,children:[r.jsx("td",{className:"p-3",children:r.jsxs("div",{className:"flex items-center gap-2",children:[b,r.jsx("span",{className:"text-sm text-white font-mono",children:g.key})]})}),r.jsx("td",{className:"p-3",children:r.jsx("span",{className:`text-sm font-mono break-all ${g.status==="removed"?"text-red-300":g.status==="changed"?"text-white":"text-bambu-gray"}`,children:f(g.left)})}),r.jsx("td",{className:"p-3",children:r.jsx("span",{className:`text-sm font-mono break-all ${g.status==="added"?"text-green-300":g.status==="changed"?"text-white":"text-bambu-gray"}`,children:f(g.right)})})]},g.key)})})]})})]})})})}function pst({onClose:t,initialData:e,allPresets:a,t:n}){const{showToast:i}=da(),s=ia(),o=!!e?.setting_id,[l,c]=y.useState("common"),[d,u]=y.useState(e?.type||"filament"),[m,p]=y.useState(e?.name?o?e.name:`${e.name} (Copy)`:""),[f,g]=y.useState(e?.base_id||""),[v,b]=y.useState(""),[x,S]=y.useState(e?.setting||{inherits:""}),[k,P]=y.useState(JSON.stringify(e?.setting||{inherits:""},null,2)),[N,T]=y.useState(null),[j,D]=y.useState(""),[C,E]=y.useState(!1),[R,I]=y.useState(""),[O,z]=y.useState(!1),[X,ae]=y.useState(Pde),[Y,ce]=y.useState(!1),[de,oe]=y.useState(""),[K,ie]=y.useState(""),[ue,he]=y.useState(!0),[ge,q]=y.useState(null),[Q,A]=y.useState(!1),F=y.useMemo(()=>({filament:a.filament,print:a.process,printer:a.printer})[d]||[],[a,d]),B=y.useMemo(()=>F.filter(Re=>MS(Re.setting_id)),[F]),{data:W}=$e({queryKey:["cloudFields",d],queryFn:()=>ne.getCloudFields(d==="print"?"process":d),staleTime:1e3*60*60}),{data:H}=$e({queryKey:["allPresetDetails",d,B.map(Re=>Re.setting_id).join(",")],queryFn:async()=>{const Re={};for(let ze=0;ze{try{const Fe=await ne.getCloudSettingDetail(tt.setting_id);return{id:tt.setting_id,detail:Fe}}catch{return null}}))).forEach(tt=>{tt&&(Re[tt.id]=tt.detail)})}return Re},enabled:B.length>0,staleTime:1e3*60*10}),{data:le,isLoading:U}=$e({queryKey:["cloudSettingDetail",f],queryFn:()=>ne.getCloudSettingDetail(f),enabled:!!f});y.useEffect(()=>{l!=="json"&&P(JSON.stringify(x,null,2))},[x,l]);const G=y.useMemo(()=>({filament:a.filament,print:a.process,printer:a.printer}[d]||[]).filter(Ue=>!MS(Ue.setting_id)).sort((Ue,ze)=>Ue.name.localeCompare(ze.name)),[a,d]);y.useEffect(()=>{if(!f)return;const Re=G.find(Ue=>Ue.setting_id===f);Re&&(b(Re.name),o||(S({inherits:Re.name}),P(JSON.stringify({inherits:Re.name},null,2))))},[f,G,o]);const Z=y.useMemo(()=>{const Re=W?.fields||[],Ue=new Set(Re.map(tt=>tt.key)),ze=new Set,it=new Set(["inherits","updated_time","compatible_printers","compatible_prints"]);H&&Object.values(H).forEach(tt=>{tt?.setting&&Object.keys(tt.setting).forEach(Fe=>{!Ue.has(Fe)&&!it.has(Fe)&&ze.add(Fe)})}),Object.keys(x).forEach(tt=>{!Ue.has(tt)&&!it.has(tt)&&ze.add(tt)});const Oe=Array.from(ze).sort().map(tt=>({key:tt,label:tt.replace(/_/g," ").replace(/\b\w/g,Fe=>Fe.toUpperCase()),type:"text",category:"discovered",description:n("profiles.presets.discoveredFromPresets")}));return[...Re,...Oe]},[W,H,x,n]),J=Z.filter(Re=>Re.label.toLowerCase().includes(j.toLowerCase())||Re.key.toLowerCase().includes(j.toLowerCase())),re=()=>{if(R.trim()){const Re=R.trim().toLowerCase().replace(/\s+/g,"_");se(Re,""),I(""),z(!1),i(n("profiles.presets.toast.fieldAdded",{key:Re}))}},se=(Re,Ue)=>{S(ze=>{const it={...ze};return Ue===""||Ue===void 0?delete it[Re]:it[Re]=Ue,it})},fe=Re=>{S(Ue=>({...Ue,...Re.settings})),q(Re.name),i(n("profiles.templates.toast.applied"))},me=()=>{if(!de.trim())return;const Re={...x};if(delete Re.inherits,Object.keys(Re).length===0){i(n("profiles.presets.noOverridesToSave"),"error");return}const Ue={id:Date.now().toString(),name:de.trim(),description:K.trim()||n("profiles.presets.customTemplate"),type:d,settings:Re,showInModal:ue},ze=[...X,Ue];ae(ze),Nde(ze),ce(!1),oe(""),ie(""),he(!0),i(n("profiles.templates.toast.created"))},pe=y.useMemo(()=>X.filter(Re=>Re.type===d&&Re.showInModal),[d,X]),V=Re=>{P(Re);try{const Ue=JSON.parse(Re);S(Ue),T(null)}catch(Ue){T(Ue.message)}},L=Re=>{Re.preventDefault(),E(!1);const Ue=Re.dataTransfer.files[0];if(Ue&&Ue.name.endsWith(".json")){const ze=new FileReader;ze.onload=it=>{try{const Oe=it.target?.result,tt=JSON.parse(Oe),Fe=tt.setting||tt;S(Ye=>({...Ye,...Fe})),P(JSON.stringify({...x,...Fe},null,2)),i(n("profiles.presets.fileImported"))}catch{i(n("profiles.presets.invalidJsonFile"),"error")}},ze.readAsText(Ue)}},te=rt({mutationFn:()=>{const Re={...x},Ue=d==="filament"?"filament_settings_id":d==="print"?"print_settings_id":"printer_settings_id";Re[Ue]=`"${m}"`;const ze={type:d,name:m,base_id:f,setting:Re};return ne.createCloudSetting(ze)},onSuccess:async()=>{i(n("profiles.presets.toast.created")),await s.refetchQueries({queryKey:["cloudSettings"]}),t()},onError:Re=>i(Re.message,"error")}),be=rt({mutationFn:()=>{if(!e?.setting_id)throw new Error(n("profiles.presets.noSettingId"));return ne.updateCloudSetting(e.setting_id,{name:m,setting:x})},onSuccess:async()=>{i(n("profiles.presets.toast.updated")),s.removeQueries({queryKey:["cloudSettingDetail"]}),await s.refetchQueries({queryKey:["cloudSettings"]}),t()},onError:Re=>i(Re.message,"error")}),xe=o?be:te,ve=le?.setting?.inherits,De=ve?G.find(Re=>Re.name===ve):void 0,{data:je}=$e({queryKey:["cloudSettingDetail",De?.setting_id],queryFn:()=>ne.getCloudSettingDetail(De.setting_id),enabled:!!De?.setting_id}),Te=y.useMemo(()=>{const Re=je?.setting||{},Ue=le?.setting||{},ze=f&&H?.[f]?.setting?H[f].setting:{};return{...Re,...Ue,...ze}},[f,le,je,H]),qe=Re=>{if(Re==null)return"";if(Array.isArray(Re)){const Ue=[...new Set(Re.map(ze=>String(ze)))];return Ue.length===1?Ue[0]:Re.join(", ")}return String(Re)},Pe=Re=>{const Ue=x[Re.key],ze=Te[Re.key],it=qe(ze),Oe=U?n("common.loading"):it||"",tt="w-full px-3 py-1.5 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none";if(Re.type==="boolean"){const Fe=Ue==="1"||Ue===void 0&&ze==="1";return r.jsx("button",{type:"button",onClick:()=>se(Re.key,Ue==="1"?"0":"1"),className:`w-8 h-5 rounded-full transition-colors ${Fe?"bg-bambu-green":"bg-bambu-dark-tertiary"}`,children:r.jsx("div",{className:`w-4 h-4 rounded-full bg-white shadow transition-transform ${Fe?"translate-x-3.5":"translate-x-0.5"}`})})}return Re.type==="select"?r.jsxs("select",{value:Ue||"",onChange:Fe=>se(Re.key,Fe.target.value),className:tt,children:[r.jsx("option",{value:"",children:Oe}),Re.options?.map(Fe=>r.jsx("option",{value:Fe.value,children:Fe.label},Fe.value))]}):r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("input",{type:Re.type==="number"?"number":"text",value:Ue!==void 0?String(Ue):"",onChange:Fe=>se(Re.key,Fe.target.value),step:Re.step,min:Re.min,max:Re.max,placeholder:Oe,className:tt}),Re.unit&&r.jsx("span",{className:"text-xs text-bambu-gray whitespace-nowrap",children:Re.unit})]})},Ie=y.useMemo(()=>le?.setting?le.setting:{},[le]);return r.jsxs("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",onDragOver:Re=>{Re.preventDefault(),E(!0)},onDragLeave:()=>E(!1),onDrop:L,children:[Q&&f&&r.jsx(Tde,{onClose:()=>A(!1),leftPreset:Ie,rightPreset:x,leftLabel:n("profiles.presets.baseLabel",{name:v||f}),rightLabel:n("profiles.presets.currentLabel",{name:m||n("profiles.presets.newPreset")}),t:n}),r.jsx(Tt,{className:"w-full max-w-6xl max-h-[90vh] flex flex-col overflow-y-auto",children:r.jsxs(jt,{className:"p-0 flex flex-col h-full",children:[r.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[r.jsxs("div",{children:[r.jsx("h2",{className:"text-xl font-semibold text-white",children:n(o?"profiles.presets.editPreset":e?"profiles.presets.duplicatePreset":"profiles.presets.createNewPreset")}),r.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:n("profiles.presets.customizeSettings")})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[f&&r.jsxs("button",{onClick:()=>A(!0),className:"flex items-center gap-2 px-3 py-2 text-sm text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary rounded-lg transition-colors",title:n("profiles.presets.compareWithBase"),children:[r.jsx(sy,{className:"w-4 h-4"}),n("profiles.presets.compare")]}),r.jsx("button",{onClick:t,className:"p-2 text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary rounded-lg transition-colors",children:r.jsx(Ht,{className:"w-5 h-5"})})]})]}),C&&r.jsx("div",{className:"absolute inset-0 bg-bambu-green/10 border-2 border-dashed border-bambu-green rounded-lg flex items-center justify-center z-10",children:r.jsxs("div",{className:"text-center",children:[r.jsx(Sn,{className:"w-12 h-12 text-bambu-green mx-auto mb-2"}),r.jsx("p",{className:"text-bambu-green font-medium",children:n("profiles.presets.dropJsonToImport")})]})}),r.jsxs("div",{className:"p-4 border-b border-bambu-dark-tertiary space-y-3",children:[r.jsxs("div",{className:"grid grid-cols-3 gap-4 max-[640px]:grid-cols-1",children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("common.type")}),r.jsxs("select",{value:d,onChange:Re=>{u(Re.target.value),g("")},className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[r.jsx("option",{value:"filament",children:n("profiles.presets.types.filament")}),r.jsx("option",{value:"print",children:n("profiles.presets.types.process")}),r.jsx("option",{value:"printer",children:n("profiles.presets.types.printer")})]})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("profiles.presets.basePreset")}),r.jsxs("select",{value:f,onChange:Re=>g(Re.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",children:[r.jsx("option",{value:"",children:n("profiles.presets.selectBasePreset")}),G.map(Re=>r.jsx("option",{value:Re.setting_id,children:Re.name},Re.setting_id))]})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("profiles.presets.presetName")}),r.jsx("input",{type:"text",value:m,onChange:Re=>p(Re.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",placeholder:n("profiles.presets.myCustomPreset")})]})]}),v&&r.jsx("div",{className:"text-xs text-bambu-gray",children:r.jsxs("p",{className:"flex items-center gap-1",children:[r.jsx(_r,{className:"w-3 h-3 text-bambu-green"}),n("profiles.presets.inheritsFrom")," ",r.jsx("span",{className:"text-white",children:v}),U&&r.jsx(lt,{className:"w-3 h-3 animate-spin ml-1"})]})})]}),r.jsxs("div",{className:"flex border-b border-bambu-dark-tertiary max-[640px]:flex-wrap max-[640px]:items-center",children:[r.jsxs("button",{onClick:()=>c("common"),className:`flex items-center gap-2 px-4 py-3 text-sm font-medium transition-colors border-b-2 -mb-px ${l==="common"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-white border-transparent"}`,children:[r.jsx(M8,{className:"w-4 h-4"}),n("profiles.presets.tabs.common")]}),r.jsxs("button",{onClick:()=>c("fields"),className:`flex items-center gap-2 px-4 py-3 text-sm font-medium transition-colors border-b-2 -mb-px ${l==="fields"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-white border-transparent"}`,children:[r.jsx(BS,{className:"w-4 h-4"}),n("profiles.presets.tabs.allFields")]}),r.jsxs("button",{onClick:()=>c("json"),className:`flex items-center gap-2 px-4 py-3 text-sm font-medium transition-colors border-b-2 -mb-px ${l==="json"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-white border-transparent"}`,children:[r.jsx(tv,{className:"w-4 h-4"}),"JSON",N&&r.jsx(wn,{className:"w-3 h-3 text-red-400"})]}),r.jsx("div",{className:"flex-1 max-[640px]:hidden"}),r.jsxs("button",{onClick:()=>{const Re={name:m,type:d,base_id:f,setting:x},Ue=new Blob([JSON.stringify(Re,null,2)],{type:"application/json"}),ze=URL.createObjectURL(Ue),it=document.createElement("a");it.href=ze,it.download=`${m||"preset"}.json`,document.body.appendChild(it),it.click(),document.body.removeChild(it),URL.revokeObjectURL(ze),i(n("profiles.presets.toast.exported"))},className:"flex items-center gap-2 px-4 py-3 text-sm text-bambu-gray hover:text-white transition-colors",title:n("profiles.presets.exportToJson"),children:[r.jsx(Ur,{className:"w-4 h-4"}),n("common.download")]}),r.jsxs("button",{onClick:()=>document.getElementById("file-import")?.click(),className:"flex items-center gap-2 px-4 py-3 text-sm text-bambu-gray hover:text-white transition-colors",title:n("profiles.presets.importFromJson"),children:[r.jsx(Sn,{className:"w-4 h-4"}),n("common.upload")]}),r.jsx("input",{id:"file-import",type:"file",accept:".json",className:"hidden",onChange:Re=>{const Ue=Re.target.files?.[0];if(Ue){const ze=new FileReader;ze.onload=it=>{try{const Oe=JSON.parse(it.target?.result),tt=Oe.setting||Oe;S(Fe=>({...Fe,...tt})),i(n("profiles.presets.fileImported"))}catch{i(n("profiles.presets.invalidJson"),"error")}},ze.readAsText(Ue)}}})]}),r.jsxs("div",{className:"flex-1 p-4",children:[l==="common"&&r.jsxs("div",{className:"space-y-6",children:[r.jsxs("div",{children:[r.jsxs("div",{className:"flex items-center justify-between mb-3",children:[r.jsxs("h3",{className:"text-sm font-medium text-white flex items-center gap-2",children:[r.jsx(Ug,{className:"w-4 h-4 text-amber-400"}),n("profiles.templates.title")]}),Object.keys(x).filter(Re=>Re!=="inherits").length>0&&r.jsxs("button",{onClick:()=>ce(!Y),className:"text-xs text-bambu-gray hover:text-white flex items-center gap-1 transition-colors",children:[r.jsx(ms,{className:"w-3 h-3"}),n("profiles.presets.saveAsTemplate")]})]}),Y&&r.jsxs("div",{className:"mb-3 p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"grid grid-cols-2 gap-2 mb-2",children:[r.jsx("input",{type:"text",value:de,onChange:Re=>oe(Re.target.value),placeholder:n("profiles.templates.namePlaceholder"),className:"px-3 py-1.5 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none",autoFocus:!0}),r.jsx("input",{type:"text",value:K,onChange:Re=>ie(Re.target.value),placeholder:n("profiles.templates.descriptionPlaceholder"),className:"px-3 py-1.5 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none"})]}),r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("div",{className:"flex gap-2",children:[r.jsxs(Le,{size:"sm",onClick:me,disabled:!de.trim(),children:[r.jsx(ms,{className:"w-3 h-3"}),n("common.save")]}),r.jsx(Le,{size:"sm",variant:"secondary",onClick:()=>ce(!1),children:n("common.cancel")})]}),r.jsxs("button",{onClick:()=>he(!ue),className:`flex items-center gap-1.5 text-xs transition-colors ${ue?"text-bambu-green":"text-bambu-gray hover:text-white"}`,children:[ue?r.jsx(tl,{className:"w-3.5 h-3.5"}):r.jsx(Zh,{className:"w-3.5 h-3.5"}),n(ue?"profiles.templates.shownInModals":"profiles.templates.hiddenInModals")]})]})]}),ge&&r.jsxs("div",{className:"mb-3 px-3 py-2 bg-bambu-green/10 border border-bambu-green/30 rounded-lg flex items-center gap-2",children:[r.jsx(_r,{className:"w-4 h-4 text-bambu-green"}),r.jsxs("span",{className:"text-sm text-bambu-green",children:[n("profiles.presets.templateApplied")," ",r.jsx("span",{className:"font-medium",children:ge})]}),r.jsx("button",{onClick:()=>q(null),className:"ml-auto text-bambu-green/70 hover:text-bambu-green",children:r.jsx(Ht,{className:"w-4 h-4"})})]}),r.jsxs("div",{className:"grid grid-cols-3 gap-2",children:[pe.map(Re=>r.jsxs("button",{onClick:()=>fe(Re),className:"p-3 text-left bg-bambu-dark border border-bambu-dark-tertiary rounded-lg hover:border-bambu-gray-dark transition-colors",children:[r.jsx("p",{className:"text-sm font-medium text-white",children:Re.name}),r.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:Re.description})]},Re.id)),pe.length===0&&r.jsx("p",{className:"col-span-3 text-center text-bambu-gray text-sm py-4",children:n("profiles.presets.noTemplatesSelected")})]}),r.jsx("p",{className:"text-xs text-bambu-gray-dark mt-2 text-center",children:n("profiles.presets.manageTemplatesHint")})]}),r.jsxs("div",{children:[r.jsx("h3",{className:"text-sm font-medium text-white mb-3",children:n("profiles.presets.commonSettings")}),r.jsx("div",{className:"grid grid-cols-2 gap-x-6 gap-y-3",children:Z.slice(0,10).map(Re=>r.jsxs("div",{className:"flex items-center justify-between gap-4 max-[640px]:flex-col max-[640px]:items-start",children:[r.jsx("label",{className:"text-sm text-bambu-gray flex-shrink-0",children:Re.label}),r.jsx("div",{className:"w-48 max-[640px]:w-full",children:Pe(Re)})]},Re.key))})]}),Object.keys(x).length>1&&r.jsxs("div",{children:[r.jsx("h3",{className:"text-sm font-medium text-white mb-3",children:n("profiles.presets.currentOverrides")}),r.jsx("div",{className:"flex flex-wrap gap-2",children:Object.entries(x).filter(([Re])=>Re!=="inherits").map(([Re,Ue])=>r.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-1 bg-bambu-green/10 text-bambu-green text-xs rounded",children:[Re,": ",String(Ue).slice(0,20),r.jsx("button",{onClick:()=>se(Re,void 0),className:"hover:text-white",children:r.jsx(Ht,{className:"w-3 h-3"})})]},Re))})]})]}),l==="fields"&&r.jsxs("div",{className:"grid grid-cols-2 gap-6",style:{height:"400px"},children:[r.jsxs("div",{className:"flex flex-col h-full overflow-hidden",children:[r.jsxs("div",{className:"flex items-center justify-between mb-3 flex-shrink-0",children:[r.jsx("h3",{className:"text-sm font-medium text-white",children:n("profiles.presets.availableFields")}),r.jsx("span",{className:"text-xs text-bambu-gray",children:H?n("profiles.templates.fieldsCount",{count:Z.length}):n("common.loading")})]}),r.jsxs("div",{className:"relative mb-3 flex-shrink-0",children:[r.jsx(br,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),r.jsx("input",{type:"text",value:j,onChange:Re=>D(Re.target.value),placeholder:n("profiles.presets.searchFieldsPlaceholder"),className:"w-full pl-10 pr-4 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder-bambu-gray-dark focus:border-bambu-green focus:outline-none"})]}),r.jsxs("div",{className:"flex-1 overflow-y-auto space-y-1 pr-2 min-h-0",children:[J.filter(Re=>!(Re.key in x)).map(Re=>{const Ue=Te[Re.key],ze=qe(Ue);return r.jsxs("div",{onClick:()=>{S(it=>({...it,[Re.key]:ze||""}))},className:"flex items-center justify-between gap-2 p-2 rounded-lg hover:bg-bambu-dark-tertiary transition-colors cursor-pointer group",children:[r.jsxs("div",{className:"min-w-0 flex-1",children:[r.jsx("p",{className:"text-sm text-white truncate",children:Re.label}),r.jsx("p",{className:"text-xs text-bambu-gray-dark truncate",children:Re.key})]}),r.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[ze&&r.jsxs("span",{className:"text-xs text-bambu-gray bg-bambu-dark px-2 py-0.5 rounded max-w-32 truncate",title:ze,children:[ze.slice(0,20),ze.length>20?"...":""]}),r.jsx("div",{className:"w-6 h-6 flex items-center justify-center rounded bg-bambu-dark-tertiary group-hover:bg-bambu-green/20 transition-colors",children:r.jsx(or,{className:"w-4 h-4 text-bambu-gray group-hover:text-bambu-green transition-colors"})})]})]},Re.key)}),J.filter(Re=>!(Re.key in x)).length===0&&r.jsx("p",{className:"text-center text-bambu-gray py-4 text-sm",children:n(j?"profiles.presets.noMatchingFields":"profiles.presets.allFieldsAdded")})]}),r.jsx("div",{className:"pt-3 mt-3 border-t border-bambu-dark-tertiary flex-shrink-0",children:O?r.jsxs("div",{className:"flex gap-2",children:[r.jsx("input",{type:"text",value:R,onChange:Re=>I(Re.target.value),onKeyDown:Re=>Re.key==="Enter"&&re(),placeholder:"custom_field_name",className:"flex-1 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white font-mono text-sm placeholder-bambu-gray-dark focus:border-bambu-green focus:outline-none",autoFocus:!0}),r.jsx(Le,{size:"sm",onClick:re,disabled:!R.trim(),children:r.jsx(or,{className:"w-4 h-4"})}),r.jsx(Le,{size:"sm",variant:"secondary",onClick:()=>{z(!1),I("")},children:r.jsx(Ht,{className:"w-4 h-4"})})]}):r.jsxs("button",{onClick:()=>z(!0),className:"w-full flex items-center justify-center gap-2 p-2 text-sm text-bambu-gray hover:text-white border border-dashed border-bambu-dark-tertiary hover:border-bambu-gray-dark rounded-lg transition-colors",children:[r.jsx(or,{className:"w-4 h-4"}),n("profiles.presets.addCustomField")]})})]}),r.jsxs("div",{className:"flex flex-col h-full overflow-hidden",children:[r.jsxs("div",{className:"flex items-center justify-between mb-3 flex-shrink-0",children:[r.jsx("h3",{className:"text-sm font-medium text-white",children:n("profiles.presets.yourOverrides")}),r.jsx("span",{className:"text-xs text-bambu-gray",children:n("profiles.templates.fieldsCount",{count:Object.keys(x).filter(Re=>Re!=="inherits").length})})]}),r.jsxs("div",{className:"flex-1 overflow-y-auto space-y-2 pr-2 min-h-0",children:[Object.entries(x).filter(([Re])=>Re!=="inherits").map(([Re,Ue])=>{const ze=Z.find(it=>it.key===Re);return r.jsxs("div",{className:"p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"flex items-center justify-between mb-2",children:[r.jsxs("div",{children:[r.jsx("p",{className:"text-sm font-medium text-white",children:ze?.label||Re}),r.jsx("p",{className:"text-xs text-bambu-gray-dark",children:Re})]}),r.jsx("button",{onClick:()=>se(Re,void 0),className:"p-1 text-bambu-gray hover:text-red-400 transition-colors",children:r.jsx(Ht,{className:"w-4 h-4"})})]}),ze?Pe(ze):r.jsx("input",{type:"text",value:String(Ue),onChange:it=>se(Re,it.target.value),className:"w-full px-3 py-1.5 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none"})]},Re)}),Object.keys(x).filter(Re=>Re!=="inherits").length===0&&r.jsxs("div",{className:"text-center py-8 text-bambu-gray",children:[r.jsx(M8,{className:"w-8 h-8 mx-auto mb-2 opacity-50"}),r.jsx("p",{className:"text-sm",children:n("profiles.presets.noOverridesYet")}),r.jsx("p",{className:"text-xs mt-1",children:n("profiles.presets.clickFieldsToAdd")})]})]}),Object.keys(x).filter(Re=>Re!=="inherits").length>0&&r.jsx("div",{className:"pt-3 mt-3 border-t border-bambu-dark-tertiary flex-shrink-0",children:r.jsxs("button",{onClick:()=>{ce(!0),c("common")},className:"w-full flex items-center justify-center gap-2 p-2 text-sm text-bambu-gray hover:text-white border border-dashed border-bambu-dark-tertiary hover:border-bambu-gray-dark rounded-lg transition-colors",children:[r.jsx(ms,{className:"w-4 h-4"}),n("profiles.presets.saveAsTemplate")]})})]})]}),l==="json"&&r.jsxs("div",{className:"space-y-2",children:[N&&r.jsxs("div",{className:"flex items-center gap-2 text-red-400 text-sm",children:[r.jsx(wn,{className:"w-4 h-4"}),N]}),r.jsx("textarea",{value:k,onChange:Re=>V(Re.target.value),className:`w-full h-80 px-3 py-2 bg-bambu-dark border rounded-lg text-white text-xs font-mono focus:outline-none resize-none ${N?"border-red-500 focus:border-red-500":"border-bambu-dark-tertiary focus:border-bambu-green"}`,spellCheck:!1}),r.jsx("p",{className:"text-xs text-bambu-gray",children:n("profiles.presets.jsonTip")})]})]}),r.jsxs("div",{className:"p-4 border-t border-bambu-dark-tertiary flex gap-2",children:[r.jsx(Le,{variant:"secondary",onClick:t,className:"flex-1",children:n("common.cancel")}),r.jsxs(Le,{onClick:()=>xe.mutate(),disabled:xe.isPending||!m.trim()||!o&&!f||!!N,className:"flex-1",children:[xe.isPending?r.jsx(lt,{className:"w-4 h-4 animate-spin"}):o?r.jsx(ms,{className:"w-4 h-4"}):r.jsx(or,{className:"w-4 h-4"}),n(o?"common.save":e?"common.duplicate":"common.create")]})]})]})})]})}function hst({settings:t,lastSyncTime:e,onRefresh:a,isRefreshing:n,printers:i,hasPermission:s,t:o}){const[l,c]=y.useState(""),[d,u]=y.useState("all"),[m,p]=y.useState("all"),[f,g]=y.useState("all"),[v,b]=y.useState("all"),[x,S]=y.useState("all"),[k,P]=y.useState("all"),[N,T]=y.useState(null),[j,D]=y.useState(!1),[C,E]=y.useState(!1),[R,I]=y.useState(null),[O,z]=y.useState(null),[X,ae]=y.useState(null),[Y,ce]=y.useState(!1),[de,oe]=y.useState([null,null]),[K,ie]=y.useState(!1),[ue,he]=y.useState(null),ge=ia(),q=y.useMemo(()=>[...t.filament.map(re=>({...re,type:"filament"})),...t.printer.map(re=>({...re,type:"printer"})),...t.process.map(re=>({...re,type:"process"}))].map(re=>({...re,meta:T5(re.name)})),[t]),Q=y.useMemo(()=>{const J=new Set,re=new Set,se=new Set;return q.forEach(fe=>{fe.meta.nozzle&&J.add(fe.meta.nozzle),fe.meta.filamentType&&re.add(fe.meta.filamentType),fe.meta.layerHeight&&se.add(fe.meta.layerHeight)}),{printers:i.map(fe=>({id:fe.id.toString(),name:fe.name})),nozzles:Array.from(J).sort((fe,me)=>parseFloat(fe)-parseFloat(me)),filaments:Array.from(re).sort(),layerHeights:Array.from(se).sort((fe,me)=>parseFloat(fe)-parseFloat(me))}},[q,i]),A=y.useMemo(()=>f==="all"?null:i.find(re=>re.id.toString()===f)?.model||null,[f,i]),F=y.useMemo(()=>q.filter(J=>d==="all"||J.type===d).filter(J=>{if(m==="all")return!0;const re=MS(J.setting_id);return m==="custom"?re:!re}).filter(J=>{if(f==="all"||!A)return!0;const re=J.meta.printer?.toLowerCase()||"",se=A.toLowerCase();return re.includes(se)||se.includes(re)}).filter(J=>v==="all"||J.meta.nozzle===v).filter(J=>x==="all"||J.meta.filamentType===x).filter(J=>k==="all"||J.meta.layerHeight===k).filter(J=>l===""||J.name.toLowerCase().includes(l.toLowerCase())).sort((J,re)=>J.name.localeCompare(re.name)),[q,d,m,f,A,v,x,k,l]),B=J=>{if(Y){const re=de[0]?.setting_id===J.setting_id,se=de[1]?.setting_id===J.setting_id;if(re)oe([de[1],null]);else if(se)oe([de[0],null]);else if(!de[0])oe([J,null]);else if(de[1]){if(de[0].type!==J.type)return;oe([de[0],J])}else{if(de[0].type!==J.type)return;oe([de[0],J])}}else T(J)},W=J=>{if(de[0]?.setting_id===J.setting_id)return 0;if(de[1]?.setting_id===J.setting_id)return 1},H=async J=>{try{const re=await ne.getCloudSettingDetail(J.setting_id),se=J.type==="process"?"print":J.type;I({type:se,name:J.name,base_id:re.base_id||"GFSA00",setting:re.setting||{}}),T(null)}catch(re){console.error("Failed to fetch preset details for duplication:",re)}},le=async J=>{try{ge.removeQueries({queryKey:["cloudSettingDetail",J.setting_id]});const re=await ne.getCloudSettingDetail(J.setting_id),se=J.type==="process"?"print":J.type;z({type:se,name:J.name,base_id:re.base_id||"GFSA00",setting:re.setting||{},setting_id:J.setting_id}),T(null)}catch(re){console.error("Failed to fetch preset details for editing:",re)}},U=()=>{u("all"),p("all"),g("all"),b("all"),S("all"),P("all"),c("")},G=d!=="all"||m!=="all"||f!=="all"||v!=="all"||x!=="all"||k!=="all"||l!=="",Z=t.filament.length+t.printer.length+t.process.length;return r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"space-y-4 mb-6",children:[r.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[r.jsxs("div",{className:"relative flex-1",children:[r.jsx(br,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),r.jsx("input",{type:"text",value:l,onChange:J=>c(J.target.value),placeholder:o("profiles.cloudView.searchPlaceholder"),className:"w-full pl-10 pr-4 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray-dark focus:border-bambu-green focus:outline-none"})]}),r.jsxs("div",{className:"flex gap-2 max-[550px]:flex-wrap max-[550px]:items-center",children:[r.jsxs(Le,{variant:Y?"primary":"secondary",onClick:()=>{Y?(ce(!1),oe([null,null])):ce(!0)},children:[r.jsx(sy,{className:"w-4 h-4"}),o(Y?"common.cancel":"profiles.presets.compare")]}),r.jsxs(Le,{variant:"secondary",onClick:()=>E(!0),disabled:!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.cloudView.noTemplatesPermission"),children:[r.jsx(Ug,{className:"w-4 h-4"}),o("profiles.cloudView.templates")]}),r.jsxs(Le,{variant:"secondary",onClick:a,disabled:n||!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.cloudView.noRefreshPermission"),children:[r.jsx(tr,{className:`w-4 h-4 ${n?"animate-spin":""}`}),o("profiles.cloudView.refresh")]}),r.jsxs(Le,{onClick:()=>D(!0),disabled:!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.cloudView.noCreatePermission"),children:[r.jsx(or,{className:"w-4 h-4"}),o("profiles.cloudView.newPreset")]})]})]}),r.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[r.jsx(av,{className:"w-4 h-4 text-bambu-gray"}),r.jsx(id,{label:o("profiles.cloudView.filters.type"),value:d,options:[{value:"all",label:o("profiles.cloudView.filters.all"),count:Z},{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:J=>u(J)}),r.jsx(id,{label:o("profiles.cloudView.filters.owner"),value:m,options:[{value:"all",label:o("profiles.cloudView.filters.all")},{value:"custom",label:o("profiles.cloudView.filters.myPresets")},{value:"builtin",label:o("profiles.cloudView.filters.builtIn")}],onChange:J=>p(J)}),Q.printers.length>0&&r.jsx(id,{label:o("profiles.cloudView.filters.printer"),value:f,options:[{value:"all",label:o("profiles.cloudView.filters.all")},...Q.printers.map(J=>({value:J.id,label:J.name}))],onChange:g}),Q.nozzles.length>0&&r.jsx(id,{label:o("profiles.cloudView.filters.nozzle"),value:v,options:[{value:"all",label:o("profiles.cloudView.filters.all")},...Q.nozzles.map(J=>({value:J,label:J}))],onChange:b}),Q.filaments.length>0&&(d==="all"||d==="filament")&&r.jsx(id,{label:o("profiles.cloudView.filters.filament"),value:x,options:[{value:"all",label:o("profiles.cloudView.filters.all")},...Q.filaments.map(J=>({value:J,label:J}))],onChange:S}),Q.layerHeights.length>0&&(d==="all"||d==="process")&&r.jsx(id,{label:o("profiles.cloudView.filters.layer"),value:k,options:[{value:"all",label:o("profiles.cloudView.filters.all")},...Q.layerHeights.map(J=>({value:J,label:J}))],onChange:P}),G&&r.jsx("button",{onClick:U,className:"px-3 py-2 text-sm text-bambu-gray hover:text-white transition-colors",children:o("profiles.cloudView.clearFilters")})]})]}),Y&&r.jsx("div",{className:"mb-4 p-3 bg-blue-500/10 border border-blue-500/30 rounded-lg",children:r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("div",{className:"flex items-center gap-4",children:[r.jsx(sy,{className:"w-5 h-5 text-blue-400"}),r.jsx("span",{className:"text-white font-medium",children:o("profiles.cloudView.compareMode")}),r.jsx("span",{className:"text-bambu-gray",children:de[0]?o("profiles.cloudView.selectAnotherPreset",{type:de[0].type}):o("profiles.cloudView.clickTwoPresets")})]}),r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("span",{className:`px-2 py-1 text-sm rounded truncate max-w-[200px] ${de[0]?"bg-blue-500/30 text-blue-700 dark:text-blue-300":"bg-bambu-dark text-bambu-gray"}`,children:de[0]?de[0].name:o("profiles.cloudView.selectFirst")}),r.jsx(dN,{className:"w-4 h-4 text-bambu-gray"}),r.jsx("span",{className:`px-2 py-1 text-sm rounded truncate max-w-[200px] ${de[1]?"bg-blue-500/30 text-blue-700 dark:text-blue-300":"bg-bambu-dark text-bambu-gray"}`,children:de[1]?de[1].name:o("profiles.cloudView.selectSecond")})]}),de[0]&&de[1]&&r.jsxs(Le,{size:"sm",onClick:async()=>{try{const[J,re]=await Promise.all([ne.getCloudSettingDetail(de[0].setting_id),ne.getCloudSettingDetail(de[1].setting_id)]);he([J.setting||{},re.setting||{}]),ie(!0)}catch{}},children:[r.jsx(sy,{className:"w-4 h-4"}),o("profiles.cloudView.compareNow")]})]})]})}),r.jsxs("div",{className:"flex flex-wrap items-center gap-4 mb-4 text-sm text-bambu-gray",children:[e&&r.jsxs("div",{className:"flex items-center gap-1",children:[r.jsx(ar,{className:"w-3 h-3"}),o("profiles.cloudView.lastSynced")," ",Om(e.toISOString(),"system",o)]}),r.jsx("span",{children:o("profiles.cloudView.showingCount",{showing:F.length,total:Z})}),r.jsxs("div",{className:"flex items-center gap-1",children:[r.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-bambu-green"}),r.jsxs("span",{children:["= ",o("profiles.presets.myPreset")]})]})]}),F.length===0?r.jsxs("div",{className:"text-center py-16",children:[r.jsx(tn,{className:"w-12 h-12 text-bambu-gray-dark mx-auto mb-4"}),r.jsx("p",{className:"text-bambu-gray",children:o("profiles.cloudView.noPresetsFound")}),G&&r.jsx("button",{onClick:U,className:"mt-2 text-sm text-bambu-green hover:text-bambu-green-light",children:o("profiles.cloudView.clearFilters")})]}):r.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-6",children:[r.jsxs("div",{children:[r.jsxs("div",{className:"flex items-center gap-2 mb-3 px-1",children:[r.jsx(RS,{className:"w-4 h-4 text-amber-400"}),r.jsx("h3",{className:"text-sm font-medium text-bambu-gray",children:o("profiles.cloudView.columns.filament")}),r.jsxs("span",{className:"text-xs text-bambu-gray-dark",children:["(",F.filter(J=>J.type==="filament").length,")"]})]}),r.jsxs("div",{className:"space-y-1 max-h-[calc(100vh-320px)] overflow-y-auto pr-1",children:[F.filter(J=>J.type==="filament").map(J=>r.jsx(EL,{setting:J,onClick:()=>B(J),onDuplicate:()=>H(J),compareMode:Y,isCompareSelected:W(J)!==void 0,compareIndex:W(J),compareDisabled:Y&&!!de[0]&&de[0].type!==J.type,t:o},J.setting_id)),F.filter(J=>J.type==="filament").length===0&&r.jsx("p",{className:"text-xs text-bambu-gray-dark px-3 py-2",children:o("profiles.cloudView.noFilamentPresets")})]})]}),r.jsxs("div",{children:[r.jsxs("div",{className:"flex items-center gap-2 mb-3 px-1",children:[r.jsx(xd,{className:"w-4 h-4 text-blue-400"}),r.jsx("h3",{className:"text-sm font-medium text-bambu-gray",children:o("profiles.cloudView.columns.process")}),r.jsxs("span",{className:"text-xs text-bambu-gray-dark",children:["(",F.filter(J=>J.type==="process").length,")"]})]}),r.jsxs("div",{className:"space-y-1 max-h-[calc(100vh-320px)] overflow-y-auto pr-1",children:[F.filter(J=>J.type==="process").map(J=>r.jsx(EL,{setting:J,onClick:()=>B(J),onDuplicate:()=>H(J),compareMode:Y,isCompareSelected:W(J)!==void 0,compareIndex:W(J),compareDisabled:Y&&!!de[0]&&de[0].type!==J.type,t:o},J.setting_id)),F.filter(J=>J.type==="process").length===0&&r.jsx("p",{className:"text-xs text-bambu-gray-dark px-3 py-2",children:o("profiles.cloudView.noProcessPresets")})]})]}),r.jsxs("div",{children:[r.jsxs("div",{className:"flex items-center gap-2 mb-3 px-1",children:[r.jsx(xr,{className:"w-4 h-4 text-purple-400"}),r.jsx("h3",{className:"text-sm font-medium text-bambu-gray",children:o("profiles.cloudView.columns.printer")}),r.jsxs("span",{className:"text-xs text-bambu-gray-dark",children:["(",F.filter(J=>J.type==="printer").length,")"]})]}),r.jsxs("div",{className:"space-y-1 max-h-[calc(100vh-320px)] overflow-y-auto pr-1",children:[F.filter(J=>J.type==="printer").map(J=>r.jsx(EL,{setting:J,onClick:()=>B(J),onDuplicate:()=>H(J),compareMode:Y,isCompareSelected:W(J)!==void 0,compareIndex:W(J),compareDisabled:Y&&!!de[0]&&de[0].type!==J.type,t:o},J.setting_id)),F.filter(J=>J.type==="printer").length===0&&r.jsx("p",{className:"text-xs text-bambu-gray-dark px-3 py-2",children:o("profiles.cloudView.noPrinterPresets")})]})]})]}),N&&r.jsx(ust,{setting:N,onClose:()=>T(null),onDeleted:()=>T(null),onDuplicate:()=>H(N),onEdit:()=>le(N),hasPermission:s,t:o}),(j||R||O||X)&&r.jsx(pst,{onClose:()=>{D(!1),I(null),z(null),ae(null)},initialData:O||R||(X?{type:X.type,name:"",base_id:"",setting:X.setting}:void 0),allPresets:t,t:o}),C&&r.jsx(mst,{onClose:()=>E(!1),onApply:J=>{ae({type:J.type,setting:J.settings}),E(!1)},t:o}),K&&ue&&de[0]&&de[1]&&r.jsx(Tde,{onClose:()=>{ie(!1),he(null)},leftPreset:ue[0],rightPreset:ue[1],leftLabel:de[0].name,rightLabel:de[1].name,t:o})]})}function fst(){const{t}=wt(),e=ia(),{showToast:a}=da(),{hasPermission:n}=lr(),[i,s]=y.useState("cloud"),[o,l]=y.useState(),{data:c,isLoading:d}=$e({queryKey:["cloudStatus"],queryFn:ne.getCloudStatus}),{data:u=[]}=$e({queryKey:["printers"],queryFn:ne.getPrinters}),{data:m,isLoading:p,refetch:f,dataUpdatedAt:g}=$e({queryKey:["cloudSettings"],queryFn:()=>ne.getCloudSettings(),enabled:!!c?.is_authenticated,retry:!1,staleTime:1e3*60*5});y.useEffect(()=>{g&&l(new Date(g))},[g]);const v=rt({mutationFn:ne.cloudLogout,onSuccess:()=>{e.invalidateQueries({queryKey:["cloudStatus"]}),e.removeQueries({queryKey:["cloudSettings"]}),a(t("profiles.toast.loggedOut"))}}),b=()=>{e.invalidateQueries({queryKey:["cloudStatus"]})};return d?r.jsx("div",{className:"p-4 md:p-8 flex items-center justify-center min-h-[400px]",children:r.jsx(lt,{className:"w-8 h-8 text-bambu-green animate-spin"})}):r.jsxs("div",{className:"p-4 md:p-8",children:[r.jsxs("div",{className:"mb-6",children:[r.jsxs("h1",{className:"text-2xl font-bold text-white flex items-center gap-3",children:[r.jsx(Im,{className:"w-7 h-7 text-bambu-green"}),t("profiles.title")]}),r.jsx("p",{className:"text-bambu-gray mt-1",children:t("profiles.subtitle")})]}),r.jsxs("div",{className:"flex border-b border-bambu-dark-tertiary mb-6",children:[r.jsxs("button",{onClick:()=>s("cloud"),className:`flex items-center gap-2 px-4 py-3 text-sm font-medium transition-colors border-b-2 -mb-px ${i==="cloud"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-white border-transparent"}`,children:[r.jsx(Im,{className:"w-4 h-4"}),t("profiles.tabs.bambuCloud")]}),r.jsxs("button",{onClick:()=>s("orca_cloud"),className:`flex items-center gap-2 px-4 py-3 text-sm font-medium transition-colors border-b-2 -mb-px ${i==="orca_cloud"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-white border-transparent"}`,children:[r.jsx(Im,{className:"w-4 h-4"}),t("profiles.tabs.orcaCloud")]}),r.jsxs("button",{onClick:()=>s("local"),className:`flex items-center gap-2 px-4 py-3 text-sm font-medium transition-colors border-b-2 -mb-px ${i==="local"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-white border-transparent"}`,children:[r.jsx(hb,{className:"w-4 h-4"}),t("profiles.tabs.local")]}),r.jsxs("button",{onClick:()=>s("kprofiles"),className:`flex items-center gap-2 px-4 py-3 text-sm font-medium transition-colors border-b-2 -mb-px ${i==="kprofiles"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-white border-transparent"}`,children:[r.jsx(zS,{className:"w-4 h-4"}),t("profiles.tabs.kprofiles")]})]}),i==="cloud"&&r.jsxs(r.Fragment,{children:[c?.is_authenticated&&r.jsxs("div",{className:"flex items-center justify-between p-3 mb-6 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("div",{className:"w-2 h-2 rounded-full bg-bambu-green animate-pulse"}),r.jsxs("span",{className:"text-sm text-bambu-gray",children:[t("profiles.connectedAs")," ",r.jsx("span",{className:"text-white",children:c.email}),c.region&&r.jsx("span",{className:"ml-2 px-2 py-0.5 text-xs rounded bg-bambu-dark-tertiary text-bambu-gray",children:c.region==="china"?t("profiles.login.regionChina"):t("profiles.login.regionGlobal")})]})]}),r.jsxs(Le,{variant:"secondary",size:"sm",onClick:()=>v.mutate(),disabled:v.isPending||!n("cloud:auth"),title:n("cloud:auth")?void 0:t("profiles.noLogoutPermission"),children:[r.jsx(Sg,{className:"w-4 h-4"}),t("profiles.logout")]})]}),c?.is_authenticated?p?r.jsx("div",{className:"flex items-center justify-center py-16",children:r.jsx(lt,{className:"w-8 h-8 text-bambu-green animate-spin"})}):m?r.jsx(hst,{settings:m,lastSyncTime:o,onRefresh:()=>f(),isRefreshing:p,printers:u,hasPermission:n,t}):r.jsxs("div",{className:"text-center py-16",children:[r.jsx("p",{className:"text-bambu-gray mb-4",children:t("profiles.failedToLoad")}),r.jsx(Le,{onClick:()=>f(),children:t("profiles.retry")})]}):r.jsx(cst,{onSuccess:b,t})]}),i==="orca_cloud"&&r.jsx(nst,{}),i==="local"&&r.jsx(Jit,{}),i==="kprofiles"&&r.jsx(Yit,{}),r.jsx(dst,{})]})}function gst(t,e){const a=(e||"").toUpperCase().replace(/[- ]/g,""),n=a.includes("X1"),i=a.includes("P1"),s=a.includes("A1MINI"),o=a.includes("A1")&&!s,l=a.includes("H2D"),c=a.includes("H2C"),d=a.includes("H2S"),u=l||c||d,m=a.includes("P2S"),p=a.includes("X2D"),f=m||p;switch(t){case"Lubricate Steel Rods":return f?"https://wiki.bambulab.com/en/p2s/maintenance/lubricate-x-y-z-axis":null;case"Clean Steel Rods":return f?"https://wiki.bambulab.com/en/p2s/maintenance/lubricate-x-y-z-axis":null;case"Lubricate Linear Rails":return s?"https://wiki.bambulab.com/en/a1-mini/maintenance/lubricate-y-axis":o?"https://wiki.bambulab.com/en/a1/maintenance/lubricate-y-axis":u?"https://wiki.bambulab.com/en/h2/maintenance/x-axis-lubrication":null;case"Clean Nozzle/Hotend":return n||i?"https://wiki.bambulab.com/en/x1/troubleshooting/nozzle-clog":s||o?"https://wiki.bambulab.com/en/a1-mini/troubleshooting/nozzle-clog":u?"https://wiki.bambulab.com/en/h2/maintenance/nozzl-cold-pull-maintenance-and-cleaning":f?"https://wiki.bambulab.com/en/p2s/maintenance/cold-pull-maintenance-hotend":"https://wiki.bambulab.com/en/x1/troubleshooting/nozzle-clog";case"Check Belt Tension":return n?"https://wiki.bambulab.com/en/x1/maintenance/belt-tension":i?"https://wiki.bambulab.com/en/p1/maintenance/p1p-maintenance":s?"https://wiki.bambulab.com/en/a1-mini/maintenance/belt_tension":o?"https://wiki.bambulab.com/en/a1/maintenance/belt_tension":l?"https://wiki.bambulab.com/en/h2/maintenance/belt-tension":c?"https://wiki.bambulab.com/en/h2c/maintenance/belt-tension":d?"https://wiki.bambulab.com/en/h2s/maintenance/belt-tension":f?"https://wiki.bambulab.com/en/p2s/maintenance/belt-tension":"https://wiki.bambulab.com/en/x1/maintenance/belt-tension";case"Clean Carbon Rods":return n||i?"https://wiki.bambulab.com/en/general/carbon-rods-clearance":null;case"Clean Linear Rails":return s?"https://wiki.bambulab.com/en/a1-mini/maintenance/lubricate-y-axis":o?"https://wiki.bambulab.com/en/a1/maintenance/lubricate-y-axis":u?"https://wiki.bambulab.com/en/h2/maintenance/x-axis-lubrication":null;case"Clean Build Plate":return"https://wiki.bambulab.com/en/filament-acc/acc/pei-plate-clean-guide";case"Check PTFE Tube":return n||i?"https://wiki.bambulab.com/en/x1/maintenance/replace-ptfe-tube":s||o?"https://wiki.bambulab.com/en/a1-mini/maintenance/ptfe-tube":l?"https://wiki.bambulab.com/en/h2/maintenance/replace-ptfe-tube-on-h2d-printer":d?"https://wiki.bambulab.com/en/h2s/maintenance/replace-ptfe-tube-on-h2s-printer":c?"https://wiki.bambulab.com/en/h2/maintenance/replace-ptfe-tube-on-h2d-printer":"https://wiki.bambulab.com/en/x1/maintenance/replace-ptfe-tube";case"Replace HEPA Filter":case"HEPA Filter":case"Replace Carbon Filter":case"Carbon Filter":return u?"https://wiki.bambulab.com/en/h2/maintenance/replace-smoke-purifier-air-filte":"https://wiki.bambulab.com/en/x1/maintenance/replace-carbon-filter";case"Lubricate Left Nozzle Rail":case"Left Nozzle Rail":return u?"https://wiki.bambulab.com/en/h2/maintenance/x-axis-lubrication":null;default:return null}}const nw={Droplet:RS,Flame:xm,Ruler:$ye,Sparkles:Ug,Square:so,Cable:RI,Wrench:Jm,Calendar:Cn,Timer:ru,Cog:bd,Fan:iJ,Zap:jc,Wind:xJ,Thermometer:VS,Layers:tn,Box:Ei,Target:fJ,RefreshCw:tr,Settings:Sy,Filter:av,CircleDot:Yge};function Dw(t){return t&&nw[t]||Jm}function qx(t,e,a){if(e==="days"){if(t<1)return a?a("common.today"):"Today";if(t===1)return a?a("maintenance.day"):"1 day";if(t<7){const i=Math.round(t);return a?a("maintenance.days",{count:i}):`${i} days`}if(t<180){const i=Math.round(t/7);return i===1?a?a("maintenance.week"):"1 week":a?a("maintenance.weeks",{count:i}):`${i} weeks`}const n=Math.round(t/30);return n===1?a?a("maintenance.month"):"1 month":a?a("maintenance.months",{count:n}):`${n} months`}else{if(t<1)return`${Math.round(t*60)}m`;if(t<24)return`${t<10?t.toFixed(1):Math.round(t)}h`;const n=t/24;if(n<7)return`${n<2?n.toFixed(1):Math.round(n)}d`;const i=n/7;return i<12?`${i<2?i.toFixed(1):Math.round(i)}w`:`${Math.round(i/4)}mo`}}function DL(t,e,a){return e==="days"?t===1?a?a("maintenance.day"):"1 day":t===7?a?a("maintenance.week"):"1 week":t===14?a?a("maintenance.weeks",{count:2}):"2 weeks":t===30?a?a("maintenance.month"):"1 month":t===60?a?a("maintenance.months",{count:2}):"2 months":t===90?a?a("maintenance.months",{count:3}):"3 months":t===180?a?a("maintenance.months",{count:6}):"6 months":t===365?a?a("maintenance.year"):"1 year":a?a("maintenance.days",{count:t}):`${t} days`:`${t}h`}function bst({item:t,onPerform:e,onToggle:a,hasPermission:n,t:i}){const s=Dw(t.maintenance_type_icon),o=t.interval_type||"hours",c=(()=>{if(o==="days"){const f=t.days_since_maintenance??0;return Math.max(0,Math.min(100,f/t.interval_hours*100))}return Math.max(0,Math.min(100,(t.interval_hours-t.hours_until_due)/t.interval_hours*100))})(),d=()=>t.enabled?t.is_due?"text-red-400":t.is_warning?"text-amber-400":"text-bambu-green":"text-bambu-gray",u=()=>t.enabled?t.is_due?"bg-red-500":t.is_warning?"bg-amber-500":"bg-bambu-green":"bg-bambu-gray/30",m=()=>t.enabled?t.is_due?"bg-red-500/5 border-red-500/20":t.is_warning?"bg-amber-500/5 border-amber-500/20":"bg-bambu-dark-secondary border-bambu-dark-tertiary":"bg-bambu-dark-secondary/50",p=()=>{if(!t.enabled)return i("common.disabled");if(o==="days"){const f=t.days_until_due??0;return t.is_due?i("maintenance.overdueBy",{duration:qx(Math.abs(f),"days",i)}):t.is_warning?i("maintenance.dueIn",{duration:qx(f,"days",i)}):i("maintenance.timeLeft",{duration:qx(f,"days",i)})}else return t.is_due?i("maintenance.overdueBy",{duration:qx(Math.abs(t.hours_until_due),"hours",i)}):t.is_warning?i("maintenance.dueIn",{duration:qx(t.hours_until_due,"hours",i)}):i("maintenance.timeLeft",{duration:qx(t.hours_until_due,"hours",i)})};return r.jsx("div",{className:`rounded-xl border p-4 transition-all ${m()}`,children:r.jsxs("div",{className:"flex items-start gap-3 max-[550px]:flex-wrap",children:[r.jsxs("div",{className:`relative p-2.5 rounded-lg shrink-0 ${t.is_due?"bg-red-500/20":t.is_warning?"bg-amber-500/20":t.enabled?"bg-bambu-dark":"bg-bambu-dark/50"}`,children:[r.jsx(s,{className:`w-5 h-5 ${d()}`}),t.enabled&&(t.is_due||t.is_warning)&&r.jsx("span",{className:`absolute -top-1 -right-1 w-2.5 h-2.5 rounded-full ${t.is_due?"bg-red-500":"bg-amber-500"} animate-pulse`})]}),r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("h3",{className:`font-medium truncate ${t.enabled?"text-white":"text-bambu-gray"}`,children:t.maintenance_type_name}),o==="days"&&r.jsx("span",{title:i("maintenance.timeBasedInterval"),children:r.jsx(Cn,{className:"w-3.5 h-3.5 text-bambu-gray shrink-0"})}),(()=>{const f=t.maintenance_type_wiki_url||gst(t.maintenance_type_name,t.printer_model);return f?r.jsx("a",{href:f,target:"_blank",rel:"noopener noreferrer",className:"text-bambu-gray hover:text-bambu-green transition-colors shrink-0",title:i("maintenance.viewDocumentation"),onClick:g=>g.stopPropagation(),children:r.jsx(Tr,{className:"w-3.5 h-3.5"})}):null})()]}),r.jsx("div",{className:"mt-2 mb-1.5",children:r.jsx("div",{className:"w-full h-1.5 bg-bambu-dark rounded-full overflow-hidden",children:r.jsx("div",{className:`h-full rounded-full transition-all duration-500 ${u()}`,style:{width:`${c}%`}})})}),r.jsxs("div",{className:`text-xs flex items-center gap-1 ${d()}`,children:[t.is_due&&r.jsx(xa,{className:"w-3 h-3"}),t.is_warning&&!t.is_due&&r.jsx(ar,{className:"w-3 h-3"}),!t.is_due&&!t.is_warning&&t.enabled&&r.jsx(_r,{className:"w-3 h-3"}),p()]})]}),r.jsxs("div",{className:"flex items-center gap-2 shrink-0 max-[550px]:w-full max-[550px]:justify-end max-[550px]:mt-1",children:[r.jsx("span",{title:n("maintenance:update")?void 0:i("maintenance.noPermissionUpdate"),children:r.jsx(Fa,{checked:t.enabled,onChange:f=>a(t.id,f),disabled:!n("maintenance:update")})}),r.jsxs(Le,{size:"sm",variant:t.is_due?"primary":"secondary",onClick:()=>e(t.id),disabled:!t.enabled||!n("maintenance:update"),title:n("maintenance:update")?void 0:i("maintenance.noPermissionPerform"),className:"!px-3",children:[r.jsx(bs,{className:"w-3.5 h-3.5"}),i("common.reset")]})]})]})})}function xst({overview:t,onPerform:e,onToggle:a,onSetHours:n,hasPermission:i,t:s}){const[o,l]=y.useState(!1),[c,d]=y.useState(!1),[u,m]=y.useState(t.total_print_hours.toFixed(1)),p=[...t.maintenance_items].sort((v,b)=>v.is_due&&!b.is_due?-1:!v.is_due&&b.is_due?1:v.is_warning&&!b.is_warning?-1:!v.is_warning&&b.is_warning?1:v.maintenance_type_id-b.maintenance_type_id),f=p.find(v=>v.enabled&&(v.is_due||v.is_warning)),g=()=>{const v=parseFloat(u);!isNaN(v)&&v>=0&&(n(t.printer_id,v),d(!1))};return r.jsxs(Tt,{className:"overflow-hidden",children:[r.jsxs("div",{className:"p-5",children:[r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("div",{className:"flex items-center gap-4",children:[r.jsx("h2",{className:"text-xl font-semibold text-white",children:t.printer_name}),r.jsxs("div",{className:"flex items-center gap-2",children:[t.due_count>0&&r.jsxs("span",{className:"px-2.5 py-1 bg-red-500/20 text-red-400 text-xs font-medium rounded-full flex items-center gap-1.5",children:[r.jsx(xa,{className:"w-3 h-3"}),s("maintenance.overdueCount",{count:t.due_count})]}),t.warning_count>0&&r.jsxs("span",{className:"px-2.5 py-1 bg-amber-500/20 text-amber-400 text-xs font-medium rounded-full flex items-center gap-1.5",children:[r.jsx(ar,{className:"w-3 h-3"}),s("maintenance.dueSoonCount",{count:t.warning_count})]}),t.due_count===0&&t.warning_count===0&&r.jsxs("span",{className:"px-2.5 py-1 bg-bambu-green/20 text-bambu-green text-xs font-medium rounded-full flex items-center gap-1.5",children:[r.jsx(_r,{className:"w-3 h-3"}),s("maintenance.allGood")]})]})]}),r.jsxs("button",{onClick:()=>l(!o),className:"flex items-center gap-1.5 px-3 py-1.5 text-sm text-bambu-gray hover:text-white hover:bg-bambu-dark rounded-lg transition-colors",children:[o?r.jsx(el,{className:"w-4 h-4"}):r.jsx(za,{className:"w-4 h-4"}),s(o?"common.collapse":"common.expand")]})]}),r.jsxs("div",{className:"flex items-center gap-6 mt-4",children:[r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("div",{className:"p-2 bg-bambu-dark/50 rounded-lg",children:r.jsx(ru,{className:"w-4 h-4 text-bambu-gray"})}),c?r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("input",{type:"number",value:u,onChange:v=>m(v.target.value),onKeyDown:v=>{v.key==="Enter"&&g(),v.key==="Escape"&&d(!1)},className:"w-24 px-2 py-1 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-sm",min:"0",step:"1",autoFocus:!0}),r.jsx("span",{className:"text-xs text-bambu-gray",children:s("common.hours")}),r.jsx(Le,{size:"sm",onClick:g,children:s("common.save")}),r.jsx(Le,{size:"sm",variant:"secondary",onClick:()=>d(!1),children:s("common.cancel")})]}):r.jsxs("button",{onClick:()=>{i("maintenance:update")&&(m(Math.round(t.total_print_hours).toString()),d(!0))},className:`group ${i("maintenance:update")?"":"cursor-not-allowed opacity-60"}`,title:i("maintenance:update")?void 0:s("maintenance.noPermissionEditHours"),children:[r.jsxs("div",{className:`text-sm font-medium text-white ${i("maintenance:update")?"group-hover:text-bambu-green":""} transition-colors flex items-center gap-1`,children:[Math.round(t.total_print_hours)," ",s("common.hours"),r.jsx(Bg,{className:`w-3 h-3 text-bambu-gray ${i("maintenance:update")?"group-hover:text-bambu-green":""}`})]}),r.jsx("div",{className:"text-xs text-bambu-gray",children:s("maintenance.totalPrintTime")})]})]}),r.jsx("div",{className:"w-px h-10 bg-bambu-dark-tertiary"}),f&&r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("div",{className:`p-2 rounded-lg ${f.is_due?"bg-red-500/20":"bg-amber-500/20"}`,children:(()=>{const v=Dw(f.maintenance_type_icon);return r.jsx(v,{className:`w-4 h-4 ${f.is_due?"text-red-400":"text-amber-400"}`})})()}),r.jsxs("div",{children:[r.jsx("div",{className:`text-sm font-medium ${f.is_due?"text-red-400":"text-amber-400"}`,children:f.maintenance_type_name}),r.jsx("div",{className:`text-xs ${f.is_due?"text-red-400/70":"text-amber-400/70"}`,children:f.is_due?s("common.overdue"):s("maintenance.dueSoon")})]})]})]})]}),o&&r.jsx(jt,{className:"pt-0 border-t border-bambu-dark-tertiary",children:r.jsx("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-3 pt-4",children:p.map(v=>r.jsx(bst,{item:v,onPerform:e,onToggle:a,hasPermission:i,t:s},v.id))})})]})}function yst({overview:t,types:e,onUpdateInterval:a,onAddType:n,onUpdateType:i,onDeleteType:s,onRestoreDefaults:o,isRestoringDefaults:l,onAssignType:c,onRemoveItem:d,hasPermission:u,t:m}){const[p,f]=y.useState(null),[g,v]=y.useState(""),[b,x]=y.useState("hours"),[S,k]=y.useState(!1),[P,N]=y.useState(""),[T,j]=y.useState("100"),[D,C]=y.useState("hours"),[E,R]=y.useState("Wrench"),[I,O]=y.useState(""),[z,X]=y.useState(new Set),[ae,Y]=y.useState(null),[ce,de]=y.useState(null),oe=y.useMemo(()=>t?t.map(V=>({id:V.printer_id,name:V.printer_name})):[],[t]),K=V=>t?t.filter(L=>L.maintenance_items.some(te=>te.maintenance_type_id===V)).map(L=>({printerId:L.printer_id,printerName:L.printer_name,itemId:L.maintenance_items.find(te=>te.maintenance_type_id===V)?.id})):[],ie=V=>{if(!t)return[];const L=new Set(K(V).map(te=>te.printerId));return oe.filter(te=>!L.has(te.id))},[ue,he]=y.useState(null),[ge,q]=y.useState(""),[Q,A]=y.useState(""),[F,B]=y.useState("hours"),[W,H]=y.useState("Wrench"),[le,U]=y.useState(""),G=V=>{he(V),q(V.name),A(V.default_interval_hours.toString()),B(V.interval_type||"hours"),H(V.icon||"Wrench"),U(V.wiki_url||"")},Z=()=>{ue&&ge.trim()&&parseFloat(Q)>0&&(i(ue.id,{name:ge.trim(),default_interval_hours:parseFloat(Q),interval_type:F,icon:W,wiki_url:le.trim()||null}),he(null))},J=(V,L,te)=>{const be=parseFloat(g);if(!isNaN(be)&&be>0){const xe=Math.abs(be-L)<.01?null:be;a(V,{custom_interval_hours:xe,custom_interval_type:b!==te?b:null})}f(null)},re=V=>{V.preventDefault(),P.trim()&&parseFloat(T)>0&&z.size>0&&(n({name:P.trim(),default_interval_hours:parseFloat(T),interval_type:D,icon:E,wiki_url:I.trim()||null},Array.from(z)),N(""),j("100"),C("hours"),O(""),X(new Set),k(!1))},se=V=>{X(L=>{const te=new Set(L);return te.has(V)?te.delete(V):te.add(V),te})},fe=t?.map(V=>({printerId:V.printer_id,printerName:V.printer_name,items:V.maintenance_items.sort((L,te)=>L.maintenance_type_id-te.maintenance_type_id)})).sort((V,L)=>V.printerName.localeCompare(L.printerName))||[],me=e.filter(V=>V.is_system),pe=e.filter(V=>!V.is_system);return r.jsxs("div",{className:"space-y-8",children:[r.jsxs("div",{children:[r.jsxs("div",{className:"flex items-center justify-between mb-4",children:[r.jsxs("div",{children:[r.jsx("h2",{className:"text-lg font-semibold text-white",children:m("maintenance.maintenanceTypes")}),r.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:m("maintenance.maintenanceTypesDescription")})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(Le,{variant:"secondary",onClick:o,disabled:!u("maintenance:delete")||l,title:u("maintenance:delete")?void 0:m("maintenance.noPermissionDeleteTypes"),children:m("maintenance.restoreDefaults")}),r.jsxs(Le,{onClick:()=>k(!S),disabled:!u("maintenance:create"),title:u("maintenance:create")?void 0:m("maintenance.noPermissionEditTypes"),children:[r.jsx(or,{className:"w-4 h-4"}),m("maintenance.addCustomType")]})]})]}),S&&r.jsx(Tt,{className:"mb-6",children:r.jsx(jt,{className:"py-4",children:r.jsxs("form",{onSubmit:re,children:[r.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4",children:[r.jsxs("div",{className:"lg:col-span-2",children:[r.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:m("common.name")}),r.jsx("input",{type:"text",value:P,onChange:V=>N(V.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",placeholder:m("maintenance.exampleName"),autoFocus:!0})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:m("maintenance.intervalType")}),r.jsxs("select",{value:D,onChange:V=>{C(V.target.value),V.target.value==="days"?j("30"):j("100")},className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",children:[r.jsx("option",{value:"hours",children:m("maintenance.printHours")}),r.jsx("option",{value:"days",children:m("maintenance.calendarDays")})]})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:m("maintenance.intervalValue",{type:D==="days"?m("maintenance.calendarDays").toLowerCase():m("common.hours")})}),r.jsx("input",{type:"number",value:T,onChange:V=>j(V.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",min:"1"})]})]}),r.jsx("div",{className:"mt-4 flex items-end justify-between",children:r.jsxs("div",{children:[r.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:m("maintenance.icon")}),r.jsx("div",{className:"flex gap-1",children:Object.keys(nw).map(V=>{const L=nw[V];return r.jsx("button",{type:"button",onClick:()=>R(V),className:`p-2 rounded-lg transition-colors ${E===V?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary"}`,children:r.jsx(L,{className:"w-4 h-4"})},V)})})]})}),r.jsxs("div",{className:"mt-4",children:[r.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:m("maintenance.documentationLink")}),r.jsx("input",{type:"url",value:I,onChange:V=>O(V.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",placeholder:"https://wiki.bambulab.com/..."})]}),r.jsxs("div",{className:"mt-4",children:[r.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:m("maintenance.assignToPrinters")}),r.jsx("div",{className:"flex flex-wrap gap-2",children:oe.map(V=>r.jsx("button",{type:"button",onClick:()=>se(V.id),className:`px-3 py-1.5 rounded-lg text-sm transition-colors ${z.has(V.id)?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary"}`,children:V.name},V.id))}),z.size===0&&r.jsx("p",{className:"text-xs text-orange-400 mt-1",children:m("maintenance.selectAtLeastOnePrinter")})]}),r.jsxs("div",{className:"mt-4 flex justify-end gap-2",children:[r.jsx(Le,{type:"button",variant:"secondary",onClick:()=>{k(!1),X(new Set)},children:m("common.cancel")}),r.jsx(Le,{type:"submit",disabled:!P.trim()||z.size===0,children:m("maintenance.addType")})]})]})})}),r.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3",children:[me.map(V=>{const L=Dw(V.icon),te=V.interval_type||"hours";return r.jsx("div",{className:"bg-bambu-dark-secondary rounded-xl p-4 border border-bambu-dark-tertiary",children:r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("div",{className:"p-2.5 bg-bambu-dark rounded-lg",children:r.jsx(L,{className:"w-5 h-5 text-bambu-gray"})}),r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsx("div",{className:"text-sm font-medium text-white truncate",children:V.name}),r.jsxs("div",{className:"text-xs text-bambu-gray mt-0.5 flex items-center gap-1",children:[te==="days"?r.jsx(Cn,{className:"w-3 h-3"}):r.jsx(ru,{className:"w-3 h-3"}),DL(V.default_interval_hours,te,m)]})]}),r.jsx("button",{onClick:()=>{u("maintenance:delete")&&de(V)},disabled:!u("maintenance:delete"),title:u("maintenance:delete")?void 0:m("maintenance.noPermissionDeleteTypes"),className:`p-2 rounded-lg hover:bg-bambu-dark text-bambu-gray hover:text-red-400 transition-colors ${u("maintenance:delete")?"":"opacity-50 cursor-not-allowed"}`,children:r.jsx(na,{className:"w-4 h-4"})})]})},V.id)}),pe.map(V=>{const L=Dw(V.icon),te=V.interval_type||"hours";if(ue?.id===V.id)return r.jsx("div",{className:"bg-bambu-dark-secondary rounded-xl p-4 border border-bambu-green",children:r.jsxs("div",{className:"space-y-3",children:[r.jsx("input",{type:"text",value:ge,onChange:je=>q(je.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",placeholder:m("common.name"),autoFocus:!0}),r.jsxs("div",{className:"flex gap-2",children:[r.jsxs("select",{value:F,onChange:je=>B(je.target.value),className:"flex-1 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",children:[r.jsx("option",{value:"hours",children:m("maintenance.printHours")}),r.jsx("option",{value:"days",children:m("maintenance.calendarDays")})]}),r.jsx("input",{type:"number",value:Q,onChange:je=>A(je.target.value),className:"w-24 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",min:"1"})]}),r.jsx("div",{className:"flex flex-wrap gap-1",children:Object.keys(nw).map(je=>{const Te=nw[je];return r.jsx("button",{type:"button",onClick:()=>H(je),className:`p-1.5 rounded transition-colors ${W===je?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:r.jsx(Te,{className:"w-3.5 h-3.5"})},je)})}),r.jsx("input",{type:"url",value:le,onChange:je=>U(je.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",placeholder:m("maintenance.documentationLink")}),r.jsxs("div",{className:"flex gap-2",children:[r.jsx(Le,{size:"sm",onClick:Z,disabled:!ge.trim(),children:m("common.save")}),r.jsx(Le,{size:"sm",variant:"secondary",onClick:()=>he(null),children:m("common.cancel")})]})]})},V.id);const xe=K(V.id),ve=ie(V.id),De=ae===V.id;return r.jsxs("div",{className:"bg-bambu-dark-secondary rounded-xl p-4 border border-bambu-green/30",children:[r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("div",{className:"p-2.5 bg-bambu-green/20 rounded-lg",children:r.jsx(L,{className:"w-5 h-5 text-bambu-green"})}),r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("span",{className:"text-sm font-medium text-white truncate",children:V.name}),r.jsx("span",{className:"px-1.5 py-0.5 bg-bambu-green/20 text-bambu-green text-[10px] font-medium rounded",children:m("maintenance.custom")})]}),r.jsxs("div",{className:"text-xs text-bambu-gray mt-0.5 flex items-center gap-1",children:[te==="days"?r.jsx(Cn,{className:"w-3 h-3"}):r.jsx(ru,{className:"w-3 h-3"}),DL(V.default_interval_hours,te,m)]})]}),r.jsxs("button",{onClick:()=>Y(De?null:V.id),className:`px-2 py-1 rounded-lg border transition-colors flex items-center gap-1 ${xe.length>0?"border-bambu-green/50 bg-bambu-green/10 text-bambu-green hover:bg-bambu-green/20":"border-orange-400/50 bg-orange-400/10 text-orange-400 hover:bg-orange-400/20"}`,title:m("maintenance.printersAssignedClick",{count:xe.length}),children:[r.jsx(xr,{className:"w-3 h-3"}),r.jsx("span",{className:"text-xs font-medium",children:xe.length}),r.jsx(za,{className:`w-3 h-3 transition-transform ${De?"rotate-180":""}`})]}),r.jsx("button",{onClick:()=>G(V),disabled:!u("maintenance:update"),title:u("maintenance:update")?void 0:m("maintenance.noPermissionEditTypes"),className:`p-2 rounded-lg hover:bg-bambu-dark text-bambu-gray hover:text-white transition-colors ${u("maintenance:update")?"":"opacity-50 cursor-not-allowed"}`,children:r.jsx(Bg,{className:"w-4 h-4"})}),r.jsx("button",{onClick:()=>{confirm(m("maintenance.deleteTypeConfirm",{name:V.name}))&&s(V.id)},disabled:!u("maintenance:delete"),title:u("maintenance:delete")?void 0:m("maintenance.noPermissionDeleteTypes"),className:`p-2 rounded-lg hover:bg-bambu-dark text-bambu-gray hover:text-red-400 transition-colors ${u("maintenance:delete")?"":"opacity-50 cursor-not-allowed"}`,children:r.jsx(na,{className:"w-4 h-4"})})]}),De&&r.jsxs("div",{className:"mt-3 pt-3 border-t border-bambu-dark-tertiary",children:[r.jsx("p",{className:"text-xs text-bambu-gray mb-2",children:m("maintenance.assignedToPrinters")}),xe.length===0?r.jsx("p",{className:"text-xs text-orange-400",children:m("maintenance.noPrintersAssigned")}):r.jsx("div",{className:"flex flex-wrap gap-1 mb-2",children:xe.map(je=>r.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-1 bg-bambu-dark rounded text-xs text-white",children:[je.printerName,r.jsx("button",{onClick:()=>je.itemId&&d(je.itemId),disabled:!u("maintenance:delete"),title:u("maintenance:delete")?m("maintenance.removeFromPrinter"):m("maintenance.noPermissionRemovePrinter"),className:`ml-1 ${u("maintenance:delete")?"hover:text-red-400":"opacity-50 cursor-not-allowed"}`,children:"×"})]},je.printerId))}),ve.length>0&&r.jsxs("div",{className:"flex flex-wrap gap-1",children:[r.jsx("span",{className:"text-xs text-bambu-gray mr-1",children:m("maintenance.addPrinterShort")}),ve.map(je=>r.jsxs("button",{onClick:()=>c(je.id,V.id),disabled:!u("maintenance:create"),title:u("maintenance:create")?void 0:m("maintenance.noPermissionAssignPrinter"),className:`px-2 py-1 bg-bambu-dark rounded text-xs transition-colors ${u("maintenance:create")?"hover:bg-bambu-green/20 text-bambu-gray hover:text-bambu-green":"opacity-50 cursor-not-allowed text-bambu-gray"}`,children:["+ ",je.name]},je.id))]})]})]},V.id)})]})]}),fe.length>0&&r.jsxs("div",{children:[r.jsxs("div",{className:"mb-4",children:[r.jsx("h2",{className:"text-lg font-semibold text-white",children:m("maintenance.intervalOverrides")}),r.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:m("maintenance.intervalOverridesDescription")})]}),r.jsx("div",{className:"space-y-4",children:fe.map(V=>r.jsx(Tt,{children:r.jsxs(jt,{className:"py-4",children:[r.jsx("h3",{className:"text-sm font-medium text-white mb-3",children:V.printerName}),r.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-2",children:V.items.map(L=>{const te=Dw(L.maintenance_type_icon),be=e.find(Te=>Te.id===L.maintenance_type_id),xe=be?.default_interval_hours||L.interval_hours,ve=be?.interval_type||"hours",De=L.interval_type||"hours",je=p===L.id;return r.jsxs("div",{className:"flex items-center gap-2 p-2.5 bg-bambu-dark rounded-lg",children:[r.jsx(te,{className:"w-4 h-4 text-bambu-gray shrink-0"}),r.jsx("span",{className:"text-xs text-bambu-gray flex-1 truncate",children:L.maintenance_type_name}),je?r.jsxs("div",{className:"flex items-center gap-1",children:[b==="days"?r.jsx(Cn,{className:"w-3.5 h-3.5 text-bambu-gray shrink-0"}):r.jsx(ru,{className:"w-3.5 h-3.5 text-bambu-gray shrink-0"}),r.jsxs("select",{value:b,onChange:Te=>x(Te.target.value),className:"px-1.5 py-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-xs",children:[r.jsx("option",{value:"hours",children:m("maintenance.printHours")}),r.jsx("option",{value:"days",children:m("maintenance.calendarDays")})]}),r.jsx("input",{type:"number",value:g,onChange:Te=>v(Te.target.value),onKeyDown:Te=>{Te.key==="Enter"&&J(L.id,xe,ve),Te.key==="Escape"&&f(null)},className:"w-16 px-2 py-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-xs",min:"1"}),r.jsx(Le,{size:"sm",onClick:()=>J(L.id,xe,ve),children:"OK"})]}):r.jsxs("button",{onClick:()=>{u("maintenance:update")&&(f(L.id),v(L.interval_hours.toString()),x(De))},disabled:!u("maintenance:update"),title:u("maintenance:update")?void 0:m("maintenance.noPermissionEditIntervals"),className:`px-2 py-1 bg-bambu-dark-tertiary border border-bambu-dark-tertiary rounded text-xs font-medium text-white transition-colors flex items-center gap-1 ${u("maintenance:update")?"hover:bg-bambu-dark-secondary hover:border-bambu-green":"opacity-50 cursor-not-allowed"}`,children:[De==="days"?r.jsx(Cn,{className:"w-3 h-3"}):r.jsx(ru,{className:"w-3 h-3"}),DL(L.interval_hours,De,m),r.jsx(Bg,{className:"w-3 h-3 text-bambu-gray"})]})]},L.id)})})]})},V.printerId))})]}),fe.length===0&&r.jsx(Tt,{children:r.jsxs(jt,{className:"text-center py-12",children:[r.jsx(ar,{className:"w-12 h-12 mx-auto mb-4 text-bambu-gray/30"}),r.jsx("p",{className:"text-bambu-gray",children:m("common.noPrinters")}),r.jsx("p",{className:"text-sm text-bambu-gray/70 mt-1",children:m("maintenance.intervalOverridesDescription")})]})}),ce&&r.jsx(ka,{title:m("maintenance.deleteSystemTypeTitle"),message:m("maintenance.deleteSystemTypeMessage",{name:ce.name}),confirmText:m("common.delete"),cancelText:m("common.cancel"),variant:"danger",cancelVariant:"primary",cardClassName:"bg-red-950/70 border border-red-800/70",onConfirm:()=>{s(ce.id),de(null)},onCancel:()=>de(null)})]})}function vst(){const{t}=wt(),e=ia(),{showToast:a}=da(),{hasPermission:n}=lr(),[i,s]=y.useState("status"),{data:o,isLoading:l}=$e({queryKey:["maintenanceOverview"],queryFn:ne.getMaintenanceOverview}),{data:c}=$e({queryKey:["maintenanceTypes"],queryFn:ne.getMaintenanceTypes}),d=rt({mutationFn:({id:T,notes:j})=>ne.performMaintenance(T,j),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]}),e.invalidateQueries({queryKey:["maintenanceSummary"]}),a(t("maintenance.maintenanceComplete"))},onError:T=>{a(T.message,"error")}}),u=rt({mutationFn:({id:T,data:j})=>ne.updateMaintenanceItem(T,j),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]})},onError:T=>{a(T.message,"error")}}),m=rt({mutationFn:({id:T,data:j})=>ne.updateMaintenanceType(T,j),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceTypes"]}),e.invalidateQueries({queryKey:["maintenanceOverview"]}),a(t("maintenance.typeUpdated"))},onError:T=>{a(T.message,"error")}}),p=rt({mutationFn:ne.deleteMaintenanceType,onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceTypes"]}),e.invalidateQueries({queryKey:["maintenanceOverview"]}),a(t("maintenance.typeDeleted"))},onError:T=>{a(T.message,"error")}}),f=rt({mutationFn:ne.restoreDefaultMaintenanceTypes,onSuccess:T=>{e.invalidateQueries({queryKey:["maintenanceTypes"]}),e.invalidateQueries({queryKey:["maintenanceOverview"]}),a(t("maintenance.defaultsRestored",{count:T.restored}))},onError:T=>{a(T.message,"error")}}),g=rt({mutationFn:({printerId:T,hours:j})=>ne.setPrinterHours(T,j),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]}),e.invalidateQueries({queryKey:["maintenanceSummary"]}),a(t("maintenance.printHoursUpdated"))},onError:T=>{a(T.message,"error")}}),v=rt({mutationFn:({printerId:T,typeId:j})=>ne.assignMaintenanceType(T,j),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]}),a(t("maintenance.printerAssigned"))},onError:T=>{a(T.message,"error")}}),b=rt({mutationFn:ne.removeMaintenanceItem,onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]}),a(t("maintenance.printerRemoved"))},onError:T=>{a(T.message,"error")}}),x=T=>{d.mutate({id:T})},S=(T,j)=>{u.mutate({id:T,data:{enabled:j}})},k=(T,j)=>{g.mutate({printerId:T,hours:j})};if(l)return r.jsx("div",{className:"p-4 md:p-8 flex justify-center",children:r.jsx(lt,{className:"w-8 h-8 text-bambu-green animate-spin"})});const P=o?.reduce((T,j)=>T+j.due_count,0)||0,N=o?.reduce((T,j)=>T+j.warning_count,0)||0;return r.jsxs("div",{className:"p-4 md:p-8",children:[r.jsxs("div",{className:"mb-6",children:[r.jsxs("h1",{className:"text-2xl font-bold text-white flex items-center gap-3",children:[r.jsx(Jm,{className:"w-7 h-7 text-bambu-green"}),t("maintenance.title")]}),r.jsx("p",{className:"text-bambu-gray mt-1",children:i==="status"?r.jsxs(r.Fragment,{children:[P>0&&r.jsx("span",{className:"text-red-400",children:t("maintenance.dueCount",{count:P})}),P>0&&N>0&&" · ",N>0&&r.jsx("span",{className:"text-amber-400",children:t("maintenance.warningCount",{count:N})}),P===0&&N===0&&r.jsx("span",{className:"text-bambu-green",children:t("maintenance.allOk")})]}):t("maintenance.configureSettings")})]}),r.jsxs("div",{className:"flex gap-1 mb-6 border-b border-bambu-dark-tertiary",children:[r.jsx("button",{onClick:()=>s("status"),className:`px-4 py-2 text-sm font-medium border-b-2 -mb-px transition-colors ${i==="status"?"text-bambu-green border-bambu-green":"text-bambu-gray border-transparent hover:text-white"}`,children:t("maintenance.statusTab")}),r.jsx("button",{onClick:()=>s("settings"),className:`px-4 py-2 text-sm font-medium border-b-2 -mb-px transition-colors ${i==="settings"?"text-bambu-green border-bambu-green":"text-bambu-gray border-transparent hover:text-white"}`,children:t("maintenance.settingsTab")})]}),i==="status"?r.jsx("div",{className:"space-y-6",children:o&&o.length>0?[...o].sort((T,j)=>{const D=T.due_count*10+T.warning_count,C=j.due_count*10+j.warning_count;return D!==C?C-D:T.printer_name.localeCompare(j.printer_name)}).map(T=>r.jsx(xst,{overview:T,onPerform:x,onToggle:S,onSetHours:k,hasPermission:n,t},T.printer_id)):r.jsx(Tt,{children:r.jsxs(jt,{className:"text-center py-16",children:[r.jsx(Jm,{className:"w-16 h-16 mx-auto mb-4 text-bambu-gray/30"}),r.jsx("p",{className:"text-lg font-medium text-white mb-2",children:t("common.noPrinters")}),r.jsx("p",{className:"text-bambu-gray",children:t("maintenance.configureSettings")})]})})}):r.jsx(yst,{overview:o,types:c||[],onUpdateInterval:(T,j)=>u.mutate({id:T,data:j}),onAddType:async(T,j)=>{const D=await ne.createMaintenanceType(T);for(const C of j)await ne.assignMaintenanceType(C,D.id);e.invalidateQueries({queryKey:["maintenanceTypes"]}),e.invalidateQueries({queryKey:["maintenanceOverview"]}),a(t("maintenance.typeUpdated"))},onUpdateType:(T,j)=>m.mutate({id:T,data:j}),onDeleteType:T=>p.mutate(T),onRestoreDefaults:()=>f.mutate(),isRestoringDefaults:f.isPending,onAssignType:(T,j)=>v.mutate({printerId:T,typeId:j}),onRemoveItem:T=>b.mutate(T),hasPermission:n,t})]})}const qX=["#ef4444","#f97316","#eab308","#22c55e","#06b6d4","#3b82f6","#8b5cf6","#ec4899","#6b7280"];function Ade({project:t,onClose:e,onSave:a,isLoading:n,currencySymbol:i,t:s}){const[o,l]=y.useState(t?.name||""),[c,d]=y.useState(t?.description||""),[u,m]=y.useState(t?.color||qX[0]),[p,f]=y.useState(t?.target_count?.toString()||""),[g,v]=y.useState(t?.target_parts_count?.toString()||""),[b,x]=y.useState(t?.status||"active"),[S,k]=y.useState(t?.tags||""),[P,N]=y.useState(t?.due_date?.split("T")[0]||""),[T,j]=y.useState(t?.priority||"normal"),[D,C]=y.useState(t?.budget?.toString()||""),[E,R]=y.useState(t?.url||""),[I,O]=y.useState(null),z=ia(),[X,ae]=y.useState(t?.cover_image_filename||null),Y=y.useRef(null),[ce,de]=y.useState(!1),[oe,K]=y.useState(0),ie=async ge=>{const q=ge.target.files?.[0];if(!(!q||!t)){de(!0);try{const Q=await ne.uploadProjectCoverImage(t.id,q);ae(Q.filename),K(A=>A+1),z.invalidateQueries({queryKey:["projects"]})}catch{}finally{de(!1),Y.current&&(Y.current.value="")}}},ue=async()=>{if(t){de(!0);try{await ne.deleteProjectCoverImage(t.id),ae(null),K(ge=>ge+1),z.invalidateQueries({queryKey:["projects"]})}finally{de(!1)}}},he=ge=>{ge.preventDefault();const q=E.trim();if(q&&!/^https?:\/\//i.test(q)){O(s("projects.urlInvalid"));return}O(null),a({name:o.trim(),description:c.trim()||void 0,color:u,target_count:p?parseInt(p,10):void 0,target_parts_count:g?parseInt(g,10):void 0,tags:S.trim()||void 0,due_date:P||void 0,priority:T,budget:D.trim()?parseFloat(D):null,url:t?q||null:q||void 0,...t&&{status:b}})};return r.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:r.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-md border border-bambu-dark-tertiary flex flex-col max-h-[calc(100vh-2rem)]",children:[r.jsx("div",{className:"p-4 border-b border-bambu-dark-tertiary flex-shrink-0",children:r.jsx("h2",{className:"text-lg font-semibold text-white",children:s(t?"projects.editProject":"projects.newProject")})}),r.jsxs("form",{onSubmit:he,className:"flex flex-col flex-1 min-h-0",children:[r.jsxs("div",{className:"p-4 space-y-4 overflow-y-auto flex-1",children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("common.name")}),r.jsx("input",{type:"text",value:o,onChange:ge=>l(ge.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:s("projects.namePlaceholder"),required:!0})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("common.description")}),r.jsx("textarea",{value:c,onChange:ge=>d(ge.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green resize-none",placeholder:s("projects.descriptionPlaceholder"),rows:2})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("projects.urlLabel")}),r.jsx("input",{type:"url",value:E,onChange:ge=>{R(ge.target.value),I&&O(null)},className:`w-full bg-bambu-dark border rounded px-3 py-2 text-white placeholder-bambu-gray focus:outline-none ${I?"border-red-500 focus:border-red-500":"border-bambu-dark-tertiary focus:border-bambu-green"}`,placeholder:s("projects.urlPlaceholder"),maxLength:2048}),I&&r.jsx("p",{className:"text-xs text-red-400 mt-1",children:I})]}),t&&r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("projects.coverImageLabel")}),r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("div",{className:"w-20 h-20 rounded bg-bambu-dark border border-bambu-dark-tertiary overflow-hidden flex items-center justify-center flex-shrink-0",children:X?r.jsx("img",{src:`${ne.getProjectCoverImageUrl(t.id)}?v=${oe}`,alt:s("projects.coverImageAlt"),className:"w-full h-full object-cover"}):r.jsx(gu,{className:"w-6 h-6 text-bambu-gray"})}),r.jsxs("div",{className:"flex flex-col gap-2",children:[r.jsx("input",{ref:Y,type:"file",accept:"image/jpeg,image/png,image/gif,image/webp",onChange:ie,className:"hidden"}),r.jsxs(Le,{type:"button",variant:"secondary",onClick:()=>Y.current?.click(),disabled:ce,children:[ce?r.jsx(lt,{className:"w-4 h-4 animate-spin"}):r.jsx(Sn,{className:"w-4 h-4 mr-1"}),s(X?"projects.coverImageReplace":"projects.coverImageUpload")]}),X&&r.jsxs(Le,{type:"button",variant:"secondary",onClick:ue,disabled:ce,children:[r.jsx(Ht,{className:"w-4 h-4 mr-1"}),s("projects.coverImageRemove")]})]})]})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("projects.color")}),r.jsx("div",{className:"flex gap-2 flex-wrap",children:qX.map(ge=>r.jsx("button",{type:"button",onClick:()=>m(ge),className:`w-8 h-8 rounded-full transition-transform ${u===ge?"ring-2 ring-white ring-offset-2 ring-offset-bambu-dark-secondary scale-110":""}`,style:{backgroundColor:ge}},ge))})]}),r.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("projects.targetPlates")}),r.jsx("input",{type:"number",value:p,onChange:ge=>f(ge.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:s("projects.targetPlatesPlaceholder"),min:"1"}),r.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:s("projects.targetPlatesHelp")})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("projects.targetParts")}),r.jsx("input",{type:"number",value:g,onChange:ge=>v(ge.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:s("projects.targetPartsPlaceholder"),min:"1"}),r.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:s("projects.targetPartsHelp")})]})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("projects.tagsLabel")}),r.jsx("input",{type:"text",value:S,onChange:ge=>k(ge.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:s("projects.tagsPlaceholder")})]}),r.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("projects.dueDate")}),r.jsx("input",{type:"date",value:P,onChange:ge=>N(ge.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white focus:outline-none focus:border-bambu-green"})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("projects.priority")}),r.jsxs("select",{value:T,onChange:ge=>j(ge.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white focus:outline-none focus:border-bambu-green",children:[r.jsx("option",{value:"low",children:s("projects.priorityLow")}),r.jsx("option",{value:"normal",children:s("projects.priorityNormal")}),r.jsx("option",{value:"high",children:s("projects.priorityHigh")}),r.jsx("option",{value:"urgent",children:s("projects.priorityUrgent")})]})]})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("projectDetail.cost.budget")}),r.jsxs("div",{className:"relative",children:[r.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-bambu-gray pointer-events-none",children:i}),r.jsx("input",{type:"number",step:"0.01",min:"0",value:D,onChange:ge=>C(ge.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded pl-8 pr-3 py-2 text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:"0.00"})]})]}),t&&r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("common.status")}),r.jsxs("select",{value:b,onChange:ge=>x(ge.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white focus:outline-none focus:border-bambu-green",children:[r.jsx("option",{value:"active",children:s("projects.statusActive")}),r.jsx("option",{value:"completed",children:s("projects.statusCompleted")}),r.jsx("option",{value:"archived",children:s("projects.statusArchived")})]})]})]}),r.jsxs("div",{className:"flex justify-end gap-2 p-4 border-t border-bambu-dark-tertiary flex-shrink-0",children:[r.jsx(Le,{type:"button",variant:"secondary",onClick:e,children:s("common.cancel")}),r.jsx(Le,{type:"submit",disabled:!o.trim()||n,children:n?r.jsx(lt,{className:"w-4 h-4 animate-spin"}):s(t?"common.save":"projects.create")})]})]})]})})}function wst({projectId:t,altText:e}){const a=y.useRef(null),[n,i]=y.useState(!1),[s,o]=y.useState(null),l=()=>{if(!a.current)return;const d=a.current.getBoundingClientRect(),u=384,m=8,p=window.innerWidth,f=window.innerHeight;let g=d.right+m;g+u>p-8&&(g=d.left-u-m);let v=d.top;v+u>f-8&&(v=f-u-8),v<8&&(v=8),o({left:g,top:v}),i(!0)},c=()=>i(!1);return r.jsxs("div",{ref:a,className:"relative flex-shrink-0",onMouseEnter:l,onMouseLeave:c,onClick:d=>d.stopPropagation(),children:[r.jsx("div",{className:"w-10 h-10 rounded-lg overflow-hidden bg-bambu-dark border border-bambu-dark-tertiary",children:r.jsx("img",{src:ne.getProjectCoverImageUrl(t),alt:e,className:"w-full h-full object-cover",loading:"lazy"})}),n&&s&&xc.createPortal(r.jsx("div",{className:"fixed z-[100] w-96 h-96 rounded-lg overflow-hidden border border-bambu-dark-tertiary shadow-2xl bg-bambu-dark pointer-events-none",style:{left:s.left,top:s.top},"aria-hidden":"true",children:r.jsx("img",{src:ne.getProjectCoverImageUrl(t),alt:"",className:"w-full h-full object-contain",loading:"lazy"})}),document.body)]})}function Sst({project:t,onClick:e,onEdit:a,onDelete:n,hasPermission:i,t:s}){const o=t.target_count?Math.round(t.archive_count/t.target_count*100):0,l=t.target_parts_count?Math.round(t.completed_count/t.target_parts_count*100):0,c=t.status==="completed",d=t.status==="archived",[u,m]=y.useState(!1),f=c?{icon:to,color:"text-bambu-green",bg:"bg-bambu-green/10"}:d?{icon:ro,color:"text-bambu-gray",bg:"bg-bambu-gray/10"}:t.queue_count>0?{icon:ar,color:"text-blue-400",bg:"bg-blue-400/10"}:{icon:no,color:"text-bambu-gray",bg:"bg-bambu-gray/10"};return r.jsxs("div",{className:"group relative bg-gradient-to-br from-bambu-card to-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary hover:border-bambu-green/50 hover:shadow-lg hover:shadow-bambu-green/5 transition-all duration-300 cursor-pointer overflow-hidden",onClick:e,children:[r.jsx("div",{className:"absolute top-0 left-0 w-1.5 h-full",style:{backgroundColor:t.color||"#6b7280",boxShadow:`0 0 12px ${t.color||"#6b7280"}40`}}),r.jsxs("div",{className:"p-5 pl-6",children:[r.jsxs("div",{className:"flex items-start justify-between mb-4",children:[r.jsxs("div",{className:"flex items-center gap-3 min-w-0 flex-1",children:[t.cover_image_filename?r.jsx(wst,{projectId:t.id,altText:s("projects.coverImageAlt")}):r.jsx("div",{className:`p-2 rounded-lg ${f.bg} flex-shrink-0`,children:r.jsx(f.icon,{className:`w-5 h-5 ${f.color}`})}),r.jsxs("div",{className:"min-w-0 flex-1",children:[r.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[r.jsx("h3",{className:"font-semibold text-white truncate",children:t.name}),t.url&&r.jsx("a",{href:t.url,target:"_blank",rel:"noopener noreferrer",onClick:g=>g.stopPropagation(),title:t.url,"aria-label":s("projects.openExternalUrl"),className:"inline-flex items-center justify-center w-6 h-6 rounded bg-bambu-dark border border-bambu-dark-tertiary text-bambu-green hover:bg-bambu-green/10 hover:border-bambu-green transition-colors flex-shrink-0",children:r.jsx(Tr,{className:"w-3.5 h-3.5"})}),t.target_parts_count?r.jsxs("span",{className:`text-xs px-2 py-0.5 rounded-full whitespace-nowrap font-medium ${l>=100?"bg-bambu-green/20 text-bambu-green":"bg-bambu-dark text-bambu-gray"}`,children:[t.completed_count,"/",t.target_parts_count," ",s("projects.parts")]}):t.target_count?r.jsxs("span",{className:`text-xs px-2 py-0.5 rounded-full whitespace-nowrap font-medium ${o>=100?"bg-bambu-green/20 text-bambu-green":"bg-bambu-dark text-bambu-gray"}`,children:[t.archive_count,"/",t.target_count," ",s("projects.plates")]}):t.completed_count>0?r.jsxs("span",{className:"text-xs px-2 py-0.5 rounded-full whitespace-nowrap font-medium bg-bambu-dark text-bambu-gray",children:[t.completed_count," ",s("projects.parts")]}):null,c&&r.jsx("span",{className:"text-xs bg-bambu-green/20 text-bambu-green px-2 py-0.5 rounded-full whitespace-nowrap",children:s("projects.done")}),d&&r.jsx("span",{className:"text-xs bg-bambu-gray/20 text-bambu-gray px-2 py-0.5 rounded-full whitespace-nowrap",children:s("projects.statusArchived")})]}),t.description&&r.jsx("p",{className:"text-sm text-bambu-gray/70 mt-1 line-clamp-1",children:t.description}),t.archives&&t.archives.length>0&&(()=>{const g=t.archives.map(S=>S.filament_type).filter(Boolean).flatMap(S=>S.split(",").map(k=>k.trim())).filter(Boolean),v=[...new Set(g)],b=t.archives.map(S=>S.filament_color).filter(Boolean).flatMap(S=>S.split(",").map(k=>k.trim())).filter(S=>S.startsWith("#")||/^[0-9A-Fa-f]{6}$/.test(S)),x=[...new Set(b)];return v.length===0&&x.length===0?null:r.jsxs("div",{className:"flex items-center gap-2 mt-1.5",children:[v.slice(0,3).map(S=>r.jsx("span",{className:"text-[10px] px-1.5 py-0.5 bg-bambu-dark text-bambu-gray rounded",children:S},S)),x.length>0&&r.jsxs("div",{className:"flex items-center gap-0.5",children:[x.slice(0,5).map(S=>r.jsx("div",{className:"w-3 h-3 rounded-full border border-black/20",style:{backgroundColor:S.startsWith("#")?S:`#${S}`},title:S},S)),x.length>5&&r.jsxs("span",{className:"text-[10px] text-bambu-gray ml-0.5",children:["+",x.length-5]})]})]})})()]})]}),r.jsxs("div",{className:"relative",onClick:g=>g.stopPropagation(),children:[r.jsx("button",{className:"p-1.5 rounded-lg hover:bg-bambu-dark text-bambu-gray hover:text-white transition-colors opacity-0 group-hover:opacity-100",onClick:()=>m(!u),children:r.jsx(Cm,{className:"w-4 h-4"})}),u&&r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>m(!1)}),r.jsxs("div",{className:"absolute right-0 top-8 z-20 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl py-1 min-w-[120px]",children:[r.jsxs("button",{className:`w-full px-3 py-2 text-left text-sm flex items-center gap-2 ${i("projects:update")?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{i("projects:update")&&(a(),m(!1))},disabled:!i("projects:update"),title:i("projects:update")?void 0:s("projects.noEditPermission"),children:[r.jsx(Bg,{className:"w-4 h-4"}),s("common.edit")]}),r.jsxs("button",{className:`w-full px-3 py-2 text-left text-sm flex items-center gap-2 ${i("projects:delete")?"text-red-400 hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{i("projects:delete")&&(n(),m(!1))},disabled:!i("projects:delete"),title:i("projects:delete")?void 0:s("projects.noDeletePermission"),children:[r.jsx(na,{className:"w-4 h-4"}),s("common.delete")]})]})]})]})]}),r.jsx("div",{className:"mb-4",children:t.target_count||t.target_parts_count?r.jsxs("div",{className:"space-y-3",children:[t.target_count&&r.jsxs("div",{children:[r.jsxs("div",{className:"flex items-center justify-between text-xs mb-1",children:[r.jsx("span",{className:"text-bambu-gray",children:s("projects.plates")}),r.jsxs("span",{className:o>=100?"text-bambu-green font-medium":"text-white",children:[t.archive_count," / ",t.target_count]})]}),r.jsx("div",{className:"h-2 bg-bambu-dark/80 rounded-full overflow-hidden backdrop-blur-sm",children:r.jsx("div",{className:"h-full transition-all duration-500 ease-out rounded-full relative",style:{width:`${Math.min(o,100)}%`,background:o>=100?"linear-gradient(90deg, #22c55e, #4ade80)":`linear-gradient(90deg, ${t.color||"#6b7280"}, ${t.color||"#6b7280"}cc)`,boxShadow:`0 0 8px ${o>=100?"#22c55e":t.color||"#6b7280"}60`}})})]}),t.target_parts_count&&r.jsxs("div",{children:[r.jsxs("div",{className:"flex items-center justify-between text-xs mb-1",children:[r.jsx("span",{className:"text-bambu-gray",children:s("projects.parts")}),r.jsxs("span",{className:l>=100?"text-bambu-green font-medium":"text-white",children:[t.completed_count," / ",t.target_parts_count]})]}),r.jsx("div",{className:"h-2 bg-bambu-dark/80 rounded-full overflow-hidden backdrop-blur-sm",children:r.jsx("div",{className:"h-full transition-all duration-500 ease-out rounded-full relative",style:{width:`${Math.min(l,100)}%`,background:l>=100?"linear-gradient(90deg, #22c55e, #4ade80)":`linear-gradient(90deg, ${t.color||"#6b7280"}, ${t.color||"#6b7280"}cc)`,boxShadow:`0 0 8px ${l>=100?"#22c55e":t.color||"#6b7280"}60`}})})]}),t.failed_count>0&&r.jsxs("div",{className:"text-xs text-red-400",children:[t.failed_count," ",s("projects.failed")]})]}):t.completed_count>0||t.failed_count>0?r.jsxs("div",{className:"flex items-center gap-4 text-xs",children:[t.completed_count>0&&r.jsxs("div",{className:"flex items-center gap-1.5 text-bambu-gray",children:[r.jsx(ro,{className:"w-3.5 h-3.5"}),r.jsxs("span",{children:[t.completed_count," ",s("projects.completed")]})]}),t.failed_count>0&&r.jsxs("div",{className:"flex items-center gap-1.5 text-red-400",children:[r.jsx(xa,{className:"w-3.5 h-3.5"}),r.jsxs("span",{children:[t.failed_count," ",s("projects.failed")]})]}),t.queue_count>0&&r.jsxs("div",{className:"flex items-center gap-1.5 text-blue-400",children:[r.jsx(ar,{className:"w-3.5 h-3.5"}),r.jsxs("span",{children:[t.queue_count," ",s("projects.inQueue")]})]})]}):r.jsx("div",{className:"text-xs text-bambu-gray/60 italic",children:s("projects.noPrintsYet")})}),t.archives&&t.archives.length>0&&r.jsxs("div",{className:"mb-4",children:[r.jsx("div",{className:"grid grid-cols-4 gap-1.5",children:t.archives.slice(0,4).map(g=>r.jsxs("div",{className:"relative aspect-square rounded-lg bg-bambu-dark overflow-hidden border border-bambu-dark-tertiary",title:g.print_name||"Unknown",children:[g.thumbnail_path?r.jsx("img",{src:ne.getArchiveThumbnail(g.id),alt:g.print_name||"",className:"w-full h-full object-cover"}):r.jsx("div",{className:"w-full h-full flex items-center justify-center text-bambu-gray/50",children:r.jsx(en,{className:"w-6 h-6"})}),g.status==="failed"&&r.jsx("div",{className:"absolute inset-0 bg-red-500/40 flex items-center justify-center",children:r.jsx(xa,{className:"w-4 h-4 text-white"})})]},g.id))}),t.archive_count>4&&r.jsx("p",{className:"text-xs text-bambu-gray mt-1.5 text-center",children:s("common.more",{count:t.archive_count-4})})]}),r.jsxs("div",{className:"flex items-center justify-between pt-3 border-t border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"flex items-center gap-4 text-xs text-bambu-gray",children:[r.jsxs("div",{className:"flex items-center gap-1.5",title:s("projects.printJobs"),children:[r.jsx(tn,{className:"w-3.5 h-3.5 text-blue-400"}),r.jsxs("span",{children:[t.archive_count," ",s("projects.plates")]})]}),r.jsxs("div",{className:"flex items-center gap-1.5",title:s("projects.partsPrinted"),children:[r.jsx(en,{className:"w-3.5 h-3.5 text-bambu-green"}),r.jsxs("span",{children:[t.completed_count," ",s("projects.parts")]})]}),t.failed_count>0&&r.jsxs("div",{className:"flex items-center gap-1.5 text-red-400",title:s("projects.failedParts"),children:[r.jsx(xa,{className:"w-3.5 h-3.5"}),r.jsx("span",{children:t.failed_count})]}),t.queue_count>0&&r.jsxs("div",{className:"flex items-center gap-1.5 text-yellow-400",title:s("projects.inQueue"),children:[r.jsx(c3,{className:"w-3.5 h-3.5"}),r.jsx("span",{children:t.queue_count})]})]}),r.jsx(Vn,{className:"w-4 h-4 text-bambu-gray/50 group-hover:text-bambu-gray transition-colors"})]})]})]})}function kst(){const{t}=wt(),e=Ii(),a=ia(),{showToast:n}=da(),{hasPermission:i}=lr(),[s,o]=y.useState(!1),[l,c]=y.useState(),[d,u]=y.useState("active"),[m,p]=y.useState(null),{data:f}=$e({queryKey:["settings"],queryFn:ne.getSettings}),g=Vo(f?.currency||"USD"),{data:v,isLoading:b}=$e({queryKey:["projects",d==="all"?void 0:d],queryFn:()=>ne.getProjects(d==="all"?void 0:d)}),x=rt({mutationFn:X=>ne.createProject(X),onSuccess:()=>{a.invalidateQueries({queryKey:["projects"]}),o(!1),n(t("projects.toast.created"),"success")},onError:X=>{n(X.message,"error")}}),S=rt({mutationFn:({id:X,data:ae})=>ne.updateProject(X,ae),onSuccess:()=>{a.invalidateQueries({queryKey:["projects"]}),o(!1),c(void 0),n(t("projects.toast.updated"),"success")},onError:X=>{n(X.message,"error")}}),k=rt({mutationFn:X=>ne.deleteProject(X),onSuccess:()=>{p(null),n(t("projects.toast.deleted"),"success"),setTimeout(()=>window.location.reload(),100)},onError:X=>{p(null),n(X.message,"error")}}),P=rt({mutationFn:X=>ne.importProject(X),onSuccess:()=>{a.invalidateQueries({queryKey:["projects"]}),n(t("projects.toast.imported"),"success")},onError:X=>{n(X.message,"error")}}),N=y.useRef(null),T=async()=>{try{const X=await ne.getProjects(),ae=await Promise.all(X.map(async oe=>await ne.exportProjectJson(oe.id))),Y=new Blob([JSON.stringify(ae,null,2)],{type:"application/json"}),ce=URL.createObjectURL(Y),de=document.createElement("a");de.href=ce,de.download=`bambuddy_projects_${new Date().toISOString().split("T")[0]}.json`,de.click(),URL.revokeObjectURL(ce),n(t("projects.toast.exported"),"success")}catch(X){n(X.message,"error")}},j=()=>{N.current?.click()},D=async X=>{const ae=X.target.files?.[0];if(ae){try{if(ae.name.toLowerCase().endsWith(".zip"))await ne.importProjectFile(ae),a.invalidateQueries({queryKey:["projects"]}),n(t("projects.toast.imported"),"success");else{const ce=await ae.text(),de=JSON.parse(ce),oe=Array.isArray(de)?de:[de];for(const K of oe)await P.mutateAsync(K);oe.length>1&&n(t("projects.toast.multipleImported",{count:oe.length}),"success")}}catch(Y){n(`${t("projects.toast.importFailed")}: ${Y.message}`,"error")}X.target.value=""}},C=X=>{l?S.mutate({id:l.id,data:X}):x.mutate(X)},E=X=>{c(X),o(!0)},R=X=>{e(`/projects/${X.id}`)},I=X=>{p(X)},O=()=>{m!==null&&k.mutate(m)},z=v?.reduce((X,ae)=>(X[ae.status]=(X[ae.status]||0)+1,X.all=(X.all||0)+1,X),{})||{};return r.jsxs("div",{className:"p-4 md:p-8 space-y-8",children:[r.jsx("input",{ref:N,type:"file",accept:".json,.zip",onChange:D,className:"hidden"}),r.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4",children:[r.jsxs("div",{children:[r.jsxs("h1",{className:"text-2xl font-bold text-white flex items-center gap-3",children:[r.jsx(no,{className:"w-7 h-7 text-bambu-green"}),t("projects.title")]}),r.jsx("p",{className:"text-bambu-gray mt-1",children:t("projects.subtitle")})]}),r.jsxs("div",{className:"flex gap-2",children:[r.jsxs(Le,{variant:"secondary",onClick:j,disabled:!i("projects:create"),title:i("projects:create")?t("projects.importProject"):t("projects.noImportPermission"),children:[r.jsx(Sn,{className:"w-4 h-4 mr-2"}),t("projects.import")]}),r.jsxs(Le,{variant:"secondary",onClick:T,disabled:!i("projects:read"),title:i("projects:read")?t("projects.exportAll"):t("projects.noExportPermission"),children:[r.jsx(Ur,{className:"w-4 h-4 mr-2"}),t("projects.export")]}),r.jsxs(Le,{onClick:()=>o(!0),className:"sm:w-auto w-full",disabled:!i("projects:create"),title:i("projects:create")?void 0:t("projects.noCreatePermission"),children:[r.jsx(or,{className:"w-4 h-4 mr-2"}),t("projects.newProject")]})]})]}),r.jsx("div",{className:"flex gap-1 p-1 bg-bambu-dark rounded-xl w-fit",children:[{key:"active",label:t("projects.statusActive"),icon:ar},{key:"completed",label:t("projects.statusCompleted"),icon:to},{key:"archived",label:t("projects.statusArchived"),icon:ro},{key:"all",label:t("common.all"),icon:no}].map(({key:X,label:ae,icon:Y})=>r.jsxs("button",{onClick:()=>u(X),className:`flex items-center gap-2 px-4 py-2 text-sm rounded-lg transition-all ${d===X?"bg-bambu-card text-white shadow-sm":"text-bambu-gray hover:text-white"}`,children:[r.jsx(Y,{className:"w-4 h-4"}),r.jsx("span",{children:ae}),z[X]>0&&r.jsx("span",{className:`text-xs px-1.5 py-0.5 rounded-full ${d===X?"bg-bambu-green/20 text-bambu-green":"bg-bambu-dark-tertiary"}`,children:z[X]})]},X))}),b?r.jsx("div",{className:"flex items-center justify-center py-20",children:r.jsxs("div",{className:"flex flex-col items-center gap-3",children:[r.jsx(lt,{className:"w-8 h-8 animate-spin text-bambu-green"}),r.jsx("p",{className:"text-sm text-bambu-gray",children:t("projects.loading")})]})}):v?.length===0?r.jsxs("div",{className:"flex flex-col items-center justify-center py-20 px-4",children:[r.jsx("div",{className:"p-4 bg-bambu-dark rounded-2xl mb-4",children:r.jsx(no,{className:"w-12 h-12 text-bambu-gray/50"})}),r.jsx("h3",{className:"text-lg font-medium text-white mb-2",children:d==="all"?t("projects.noProjects"):t("projects.noProjectsFiltered",{status:d})}),r.jsx("p",{className:"text-bambu-gray text-center max-w-md mb-6",children:d==="all"?t("projects.createFirst"):t("projects.noProjectsFilteredHelp",{status:d})}),d==="all"&&r.jsxs(Le,{onClick:()=>o(!0),disabled:!i("projects:create"),title:i("projects:create")?void 0:t("projects.noCreatePermission"),children:[r.jsx(or,{className:"w-4 h-4 mr-2"}),t("projects.createFirstButton")]})]}):r.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-8",children:v?.map(X=>r.jsx(Sst,{project:X,onClick:()=>R(X),onEdit:()=>E(X),onDelete:()=>I(X.id),hasPermission:i,t},X.id))}),m!==null&&r.jsx(ka,{title:t("projects.deleteProject"),message:t("projects.deleteConfirm"),confirmText:t("projects.deleteProject"),variant:"danger",onConfirm:O,onCancel:()=>p(null)}),s&&r.jsx(Ade,{project:l,onClose:()=>{o(!1),c(void 0)},onSave:C,isLoading:x.isPending||S.isPending,currencySymbol:g,t})]})}function _st(t){const e=t.toLowerCase();return e.endsWith(".gcode")||e.endsWith(".gcode.3mf")}function Cst(t){return t>=1e3?`${(t/1e3).toFixed(2)}kg`:`${Math.round(t)}g`}function Pst({status:t,t:e}){const a={active:"bg-bambu-green/20 text-bambu-green",completed:"bg-blue-500/20 text-blue-400",archived:"bg-bambu-gray/20 text-bambu-gray"},n=a[t]||a.active,i={active:e("projectDetail.status.active"),completed:e("projectDetail.status.completed"),archived:e("projectDetail.status.archived")};return r.jsx("span",{className:`px-2 py-1 rounded text-sm font-medium ${n}`,children:i[t]||t.charAt(0).toUpperCase()+t.slice(1)})}function VX({icon:t,label:e,value:a,subValue:n,hint:i,color:s="text-bambu-gray"}){return r.jsx(Tt,{children:r.jsx(jt,{className:"p-4",children:r.jsxs("div",{className:"flex items-center gap-3",title:i,children:[r.jsx("div",{className:`p-2 rounded-lg bg-bambu-dark ${s}`,children:r.jsx(t,{className:"w-5 h-5"})}),r.jsxs("div",{children:[r.jsx("p",{className:"text-sm text-bambu-gray",children:e}),r.jsx("p",{className:"text-xl font-semibold text-white",children:a}),n&&r.jsx("p",{className:"text-xs text-bambu-gray/70",children:n})]})]})})})}function Nst({archives:t,t:e}){return t.length===0?r.jsxs("div",{className:"text-center py-8 text-bambu-gray",children:[r.jsx(en,{className:"w-12 h-12 mx-auto mb-2 opacity-50"}),r.jsx("p",{children:e("projectDetail.noPrints")})]}):r.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6 gap-3",children:t.map(a=>r.jsxs(Ls,{to:`/archives?search=${encodeURIComponent(a.print_name||"")}`,className:"group relative aspect-square rounded-lg bg-bambu-dark border border-bambu-dark-tertiary overflow-hidden hover:border-bambu-green transition-colors",children:[a.thumbnail_path?r.jsx("img",{src:ne.getArchiveThumbnail(a.id),alt:a.print_name||"Print",className:"w-full h-full object-cover"}):r.jsx("div",{className:"w-full h-full flex items-center justify-center text-bambu-gray",children:r.jsx(en,{className:"w-8 h-8"})}),a.status==="failed"&&r.jsx("div",{className:"absolute inset-0 bg-red-500/30 flex items-center justify-center",children:r.jsx(Fr,{className:"w-8 h-8 text-white"})}),a.status==="completed"&&r.jsx("div",{className:"absolute top-1 right-1",children:r.jsx(fr,{className:"w-4 h-4 text-bambu-green"})}),r.jsx("div",{className:"absolute inset-x-0 bottom-0 bg-gradient-to-t from-black/80 to-transparent p-2 opacity-0 group-hover:opacity-100 transition-opacity",children:r.jsx("p",{className:"text-xs text-white truncate",children:a.print_name||"Unknown"})})]},a.id))})}function Tst({priority:t,t:e}){const a={low:{color:"bg-gray-500/20 text-gray-400",label:e("projectDetail.priority.low")},normal:{color:"bg-blue-500/20 text-blue-400",label:e("projectDetail.priority.normal")},high:{color:"bg-orange-500/20 text-orange-400",label:e("projectDetail.priority.high")},urgent:{color:"bg-red-500/20 text-red-400",label:e("projectDetail.priority.urgent")}},{color:n,label:i}=a[t]||a.normal;return r.jsxs("span",{className:`px-2 py-1 rounded text-xs font-medium flex items-center gap-1 ${n}`,children:[t==="urgent"&&r.jsx(xa,{className:"w-3 h-3"}),i]})}function FL(t,e){if(!t)return null;const a=Ga(t);if(!a)return null;const n=new Date,i=Math.ceil((a.getTime()-n.getTime())/(1e3*60*60*24));return i<0?{color:"text-red-400",label:e("projectDetail.dueDate.overdue")}:i===0?{color:"text-orange-400",label:e("projectDetail.dueDate.today")}:i<=3?{color:"text-yellow-400",label:e("projectDetail.dueDate.daysLeft",{count:i})}:{color:"text-bambu-gray",label:e("projectDetail.dueDate.daysLeft",{count:i})}}function Ast(){const{id:t}=FS(),e=Ii(),{t:a}=wt(),n=ia(),{showToast:i}=da(),{hasPermission:s}=lr(),[o,l]=y.useState(!1),[c,d]=y.useState(!1),[u,m]=y.useState(""),[p,f]=y.useState(null),[g,v]=y.useState(null),b=parseInt(t||"0",10),{data:x,isLoading:S,error:k}=$e({queryKey:["project",b],queryFn:()=>ne.getProject(b),enabled:b>0}),{data:P,isLoading:N}=$e({queryKey:["project-archives",b],queryFn:()=>ne.getProjectArchives(b),enabled:b>0}),{data:T,isLoading:j}=$e({queryKey:["project-bom",b],queryFn:()=>ne.getProjectBOM(b),enabled:b>0}),{data:D,isLoading:C}=$e({queryKey:["project-timeline",b],queryFn:()=>ne.getProjectTimeline(b,20),enabled:b>0}),{data:E}=$e({queryKey:["settings"],queryFn:ne.getSettings}),{data:R}=$e({queryKey:["project-folders",b],queryFn:()=>ne.getLibraryFoldersByProject(b),enabled:b>0}),{data:I,isLoading:O}=$e({queryKey:["project-files",b],queryFn:()=>ne.getLibraryFiles(null,!1,b),enabled:b>0}),z=y.useMemo(()=>{const Me=new Map;for(const Be of I??[])if(Be.folder_id!=null){const Qe=Me.get(Be.folder_id)??[];Qe.push(Be),Me.set(Be.folder_id,Qe)}return Me},[I]),X=Vo(E?.currency||"USD"),ae=E?.time_format||"system",Y=rt({mutationFn:Me=>ne.updateProject(b,Me),onSuccess:()=>{n.invalidateQueries({queryKey:["project",b]}),n.invalidateQueries({queryKey:["projects"]}),l(!1),d(!1),i(a("projectDetail.toast.projectUpdated"),"success")},onError:Me=>{i(Me.message,"error")}}),ce=()=>{m(x?.notes||""),d(!0)},de=()=>{Y.mutate({notes:u})},oe=()=>{d(!1),m("")},[K,ie]=y.useState(""),[ue,he]=y.useState(1),[ge,q]=y.useState(""),[Q,A]=y.useState(""),[F,B]=y.useState(""),[W,H]=y.useState(!1),[le,U]=y.useState(!1),[G,Z]=y.useState(null),[J,re]=y.useState(""),[se,fe]=y.useState(1),[me,pe]=y.useState(""),[V,L]=y.useState(""),[te,be]=y.useState(""),[xe,ve]=y.useState({isOpen:!1,title:"",message:"",onConfirm:()=>{}}),De=rt({mutationFn:Me=>ne.createBOMItem(b,Me),onSuccess:()=>{n.invalidateQueries({queryKey:["project-bom",b]}),n.invalidateQueries({queryKey:["project",b]}),ie(""),he(1),q(""),A(""),B(""),H(!1),i(a("projectDetail.toast.partAdded"),"success")},onError:Me=>i(Me.message,"error")}),je=rt({mutationFn:({itemId:Me,data:Be})=>ne.updateBOMItem(b,Me,Be),onSuccess:()=>{n.invalidateQueries({queryKey:["project-bom",b]}),n.invalidateQueries({queryKey:["project",b]}),Z(null)},onError:Me=>i(Me.message,"error")}),Te=rt({mutationFn:Me=>ne.deleteBOMItem(b,Me),onSuccess:()=>{n.invalidateQueries({queryKey:["project-bom",b]}),n.invalidateQueries({queryKey:["project",b]}),i(a("projectDetail.toast.partRemoved"),"success")},onError:Me=>i(Me.message,"error")}),qe=Me=>{Me.preventDefault(),K.trim()&&De.mutate({name:K.trim(),quantity_needed:ue,unit_price:ge?parseFloat(ge):void 0,sourcing_url:Q.trim()||void 0,remarks:F.trim()||void 0})},Pe=Me=>{const Be=Me.is_complete?0:Me.quantity_needed;je.mutate({itemId:Me.id,data:{quantity_acquired:Be}})},Ie=(Me,Be)=>{ve({isOpen:!0,title:a("projectDetail.bom.deletePart"),message:a("projectDetail.bom.deleteConfirm",{name:Be}),onConfirm:()=>{ve(Qe=>({...Qe,isOpen:!1})),Te.mutate(Me)}})},Re=Me=>{Z(Me),re(Me.name),fe(Me.quantity_needed),pe(Me.unit_price?.toString()||""),L(Me.sourcing_url||""),be(Me.remarks||"")},Ue=Me=>{Me.preventDefault(),!(!G||!J.trim())&&je.mutate({itemId:G.id,data:{name:J.trim(),quantity_needed:se,unit_price:me?parseFloat(me):void 0,sourcing_url:V.trim()||void 0,remarks:te.trim()||void 0}})},ze=()=>{Z(null)},it=async()=>{try{const{blob:Me,filename:Be}=await ne.exportProjectZip(Number(b)),Qe=URL.createObjectURL(Me),Ge=document.createElement("a");Ge.href=Qe,Ge.download=Be||`${x?.name||"project"}_${new Date().toISOString().split("T")[0]}.zip`,Ge.click(),URL.revokeObjectURL(Qe),i(a("projectDetail.toast.projectExported"),"success")}catch(Me){i(Me.message,"error")}},Oe=rt({mutationFn:()=>ne.createTemplateFromProject(b),onSuccess:()=>{n.invalidateQueries({queryKey:["projects"]}),i(a("projectDetail.toast.templateCreated"),"success")},onError:Me=>i(Me.message,"error")}),tt=Me=>Vg(Me,ae,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"});if(S)return r.jsx("div",{className:"flex items-center justify-center py-24",children:r.jsx(lt,{className:"w-8 h-8 animate-spin text-bambu-green"})});if(k||!x)return r.jsxs("div",{className:"text-center py-24",children:[r.jsx("p",{className:"text-bambu-gray",children:k?`${a("common.error")}: ${k.message}`:a("projectDetail.notFound")}),r.jsx(Le,{variant:"secondary",className:"mt-4",onClick:()=>e("/projects"),children:a("projectDetail.backToProjects")})]});const Fe=x.stats,Ye=Fe?.progress_percent??0,Ve=Fe?.parts_progress_percent??0;return r.jsxs("div",{className:"p-4 md:p-8 space-y-8",children:[r.jsxs("div",{className:"flex items-center gap-2 text-sm text-bambu-gray",children:[r.jsx(Ls,{to:"/projects",className:"hover:text-white transition-colors",children:a("nav.projects")}),r.jsx(Vn,{className:"w-4 h-4"}),r.jsx("span",{className:"text-white",children:x.name})]}),r.jsxs("div",{className:"flex items-start justify-between",children:[r.jsxs("div",{className:"flex items-center gap-4",children:[r.jsx("button",{onClick:()=>e("/projects"),className:"p-2 rounded-lg bg-bambu-card hover:bg-bambu-dark-tertiary transition-colors",children:r.jsx(ev,{className:"w-5 h-5 text-bambu-gray"})}),r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("div",{className:"w-4 h-4 rounded-full shrink-0",style:{backgroundColor:x.color||"#6b7280"}}),r.jsxs("div",{children:[r.jsx("h1",{className:"text-2xl font-bold text-white",children:x.name}),x.description&&r.jsx("p",{className:"text-bambu-gray mt-1",children:x.description})]})]}),r.jsx(Pst,{status:x.status,t:a})]}),r.jsxs("div",{className:"flex gap-2",children:[r.jsxs(Le,{variant:"secondary",onClick:it,disabled:!s("projects:read"),title:s("projects:read")?a("projectDetail.exportProject"):a("projectDetail.noExportPermission"),children:[r.jsx(Ur,{className:"w-4 h-4 mr-2"}),a("projectDetail.export")]}),r.jsxs(Le,{onClick:()=>l(!0),disabled:!s("projects:update"),title:s("projects:update")?void 0:a("projectDetail.noEditPermission"),children:[r.jsx(Bg,{className:"w-4 h-4 mr-2"}),a("common.edit")]})]})]}),(x.target_count||x.target_parts_count)&&r.jsx(Tt,{children:r.jsxs(jt,{className:"p-4 space-y-4",children:[x.target_count&&r.jsxs("div",{children:[r.jsxs("div",{className:"flex items-center justify-between mb-2",children:[r.jsx("span",{className:"text-sm text-bambu-gray",children:a("projectDetail.progress.platesProgress")}),r.jsxs("span",{className:"text-sm font-medium text-white",children:[Fe?.total_archives||0," / ",x.target_count," ",a("projectDetail.progress.printJobs")]})]}),r.jsx("div",{className:"h-3 bg-bambu-dark rounded-full overflow-hidden",children:r.jsx("div",{className:"h-full transition-all duration-500",style:{width:`${Math.min(Ye,100)}%`,backgroundColor:Ye>=100?"#22c55e":x.color||"#6b7280"}})}),r.jsxs("div",{className:"flex justify-between mt-1",children:[r.jsx("span",{className:"text-xs text-bambu-gray/70",children:a("projectDetail.progress.percentComplete",{percent:Ye.toFixed(0)})}),Fe?.remaining_prints!=null&&Fe.remaining_prints>0&&r.jsx("span",{className:"text-xs text-bambu-gray/70",children:a("projectDetail.progress.remaining",{count:Fe.remaining_prints})})]})]}),x.target_parts_count&&r.jsxs("div",{children:[r.jsxs("div",{className:"flex items-center justify-between mb-2",children:[r.jsx("span",{className:"text-sm text-bambu-gray",children:a("projectDetail.progress.partsProgress")}),r.jsxs("span",{className:"text-sm font-medium text-white",children:[Fe?.completed_prints||0," / ",x.target_parts_count," ",a("projectDetail.progress.parts")]})]}),r.jsx("div",{className:"h-3 bg-bambu-dark rounded-full overflow-hidden",children:r.jsx("div",{className:"h-full transition-all duration-500",style:{width:`${Math.min(Ve,100)}%`,backgroundColor:Ve>=100?"#22c55e":x.color||"#6b7280"}})}),r.jsxs("div",{className:"flex justify-between mt-1",children:[r.jsx("span",{className:"text-xs text-bambu-gray/70",children:a("projectDetail.progress.percentComplete",{percent:Ve.toFixed(0)})}),Fe?.remaining_parts!=null&&Fe.remaining_parts>0&&r.jsx("span",{className:"text-xs text-bambu-gray/70",children:a("projectDetail.progress.remaining",{count:Fe.remaining_parts})})]})]})]})}),Fe&&r.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[r.jsx(Tt,{children:r.jsx(jt,{className:"p-4",children:r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("div",{className:"p-2 rounded-lg bg-bambu-dark text-bambu-green",children:r.jsx(en,{className:"w-5 h-5"})}),r.jsxs("div",{children:[r.jsx("p",{className:"text-sm text-bambu-gray",children:a("projectDetail.stats.printJobs")}),r.jsxs("p",{className:"text-xl font-semibold text-white",children:[Fe.total_archives," ",r.jsx("span",{className:"text-sm font-normal text-bambu-gray",children:a("projectDetail.stats.total")})]}),Fe.failed_prints>0&&r.jsx("p",{className:"text-sm text-status-error",children:a("projectDetail.stats.failed",{count:Fe.failed_prints})}),r.jsx("p",{className:"text-sm text-bambu-gray",children:a("projectDetail.stats.partsPrinted",{count:Fe.completed_prints})})]})]})})}),r.jsx(VX,{icon:ar,label:a("projectDetail.stats.printTime"),value:L0e(Fe.total_print_time_hours),color:"text-yellow-400"}),r.jsx(VX,{icon:xr,label:a("projectDetail.stats.filamentUsed"),value:Cst(Fe.total_filament_grams),color:"text-purple-400"})]}),Fe&&(()=>{const Me=Fe.estimated_cost+Fe.total_energy_cost+Fe.bom_cost;return Fe.estimated_cost>0||Me>0||x.budget!==null})()&&r.jsx(Tt,{children:r.jsxs(jt,{className:"p-4",children:[r.jsx("h2",{className:"text-lg font-semibold text-white mb-3",children:a("projectDetail.cost.title")}),r.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[r.jsxs("div",{children:[r.jsx("p",{className:"text-xs text-bambu-gray uppercase",children:a("projectDetail.cost.filamentCost")}),r.jsxs("p",{className:"text-lg font-semibold text-white",children:[X,Fe.estimated_cost.toFixed(2)]})]}),Fe.total_energy_kwh>0&&r.jsxs("div",{children:[r.jsx("p",{className:"text-xs text-bambu-gray uppercase",children:a("projectDetail.cost.energy")}),r.jsxs("p",{className:"text-lg font-semibold text-white",children:[Fe.total_energy_kwh.toFixed(3)," kWh",Fe.total_energy_cost>0&&r.jsxs("span",{className:"text-sm text-bambu-gray ml-1",children:["(",X,Fe.total_energy_cost.toFixed(2),")"]})]})]}),(()=>{const Me=Fe.estimated_cost+Fe.total_energy_cost+Fe.bom_cost;return Me<=0?null:r.jsxs("div",{children:[r.jsx("p",{className:"text-xs text-bambu-gray uppercase",children:a("projectDetail.cost.totalCost")}),r.jsxs("p",{className:"text-lg font-semibold text-bambu-green",children:[X,Me.toFixed(2)]}),Fe.bom_cost>0&&r.jsx("p",{className:"text-xs text-bambu-gray/70",children:a("projectDetail.cost.includesBom")})]})})(),x.budget!==null&&(()=>{const Me=Fe.estimated_cost+Fe.total_energy_cost+Fe.bom_cost,Be=x.budget-Me;return r.jsxs("div",{children:[r.jsx("p",{className:"text-xs text-bambu-gray uppercase",children:a("projectDetail.cost.budget")}),r.jsxs("p",{className:"text-sm text-bambu-gray",children:[a("projectDetail.cost.total"),": ",r.jsxs("span",{className:"text-white font-semibold",children:[X,x.budget.toFixed(2)]})]}),r.jsxs("p",{className:`text-sm ${Be>=0?"text-bambu-green":"text-red-400"}`,children:[a("projectDetail.cost.remaining"),": ",r.jsxs("span",{className:"font-semibold",children:[X,Be.toFixed(2)]})]})]})})()]})]})}),x.children&&x.children.length>0&&r.jsx(Tt,{children:r.jsxs(jt,{className:"p-4",children:[r.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2 mb-3",children:[r.jsx(oxe,{className:"w-5 h-5"}),a("projectDetail.subProjects.title",{count:x.children.length})]}),r.jsx("div",{className:"space-y-2",children:x.children.map(Me=>r.jsxs(Ls,{to:`/projects/${Me.id}`,className:"flex items-center justify-between p-3 bg-bambu-dark rounded-lg hover:bg-bambu-dark-tertiary transition-colors",children:[r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("div",{className:"w-3 h-3 rounded-full",style:{backgroundColor:Me.color||"#6b7280"}}),r.jsx("span",{className:"text-white",children:Me.name}),r.jsx("span",{className:`text-xs px-2 py-0.5 rounded ${Me.status==="completed"?"bg-status-ok/20 text-status-ok":Me.status==="archived"?"bg-bambu-gray/20 text-bambu-gray":"bg-blue-500/20 text-blue-400"}`,children:Me.status})]}),Me.progress_percent!==null&&r.jsxs("span",{className:"text-sm text-bambu-gray",children:[Me.progress_percent.toFixed(0),"%"]})]},Me.id))})]})}),x.parent_id&&x.parent_name&&r.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[r.jsx(tn,{className:"w-4 h-4 text-bambu-gray"}),r.jsx("span",{className:"text-bambu-gray",children:a("projectDetail.partOf")}),r.jsx(Ls,{to:`/projects/${x.parent_id}`,className:"text-bambu-green hover:underline",children:x.parent_name})]}),(x.tags||x.due_date||x.priority!=="normal")&&r.jsxs("div",{className:"flex flex-wrap items-center gap-4",children:[x.priority&&x.priority!=="normal"&&r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("span",{className:"text-xs text-bambu-gray uppercase",children:a("projectDetail.priorityLabel")}),r.jsx(Tst,{priority:x.priority,t:a})]}),x.due_date&&r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(Cn,{className:"w-4 h-4 text-bambu-gray"}),r.jsx("span",{className:"text-sm text-white",children:qg(x.due_date,{year:"numeric",month:"short",day:"numeric"})}),FL(x.due_date,a)&&r.jsxs("span",{className:`text-xs ${FL(x.due_date,a).color}`,children:["(",FL(x.due_date,a).label,")"]})]}),x.tags&&r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(Xm,{className:"w-4 h-4 text-bambu-gray"}),r.jsx("div",{className:"flex flex-wrap gap-1",children:x.tags.split(",").map((Me,Be)=>r.jsx("span",{className:"px-2 py-0.5 bg-bambu-dark-tertiary text-bambu-gray text-xs rounded",children:Me.trim()},Be))})]})]}),r.jsx(Tt,{children:r.jsxs(jt,{className:"p-4",children:[r.jsxs("div",{className:"flex items-center justify-between mb-3",children:[r.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[r.jsx(us,{className:"w-5 h-5"}),a("projectDetail.notes.title")]}),c?r.jsxs("div",{className:"flex gap-2",children:[r.jsxs(Le,{variant:"secondary",size:"sm",onClick:oe,disabled:Y.isPending,children:[r.jsx(Ht,{className:"w-4 h-4 mr-1"}),a("common.cancel")]}),r.jsxs(Le,{size:"sm",onClick:de,disabled:Y.isPending,children:[Y.isPending?r.jsx(lt,{className:"w-4 h-4 animate-spin mr-1"}):r.jsx(ms,{className:"w-4 h-4 mr-1"}),a("common.save")]})]}):r.jsxs(Le,{variant:"secondary",size:"sm",onClick:ce,disabled:!s("projects:update"),title:s("projects:update")?void 0:a("projectDetail.notes.noEditPermission"),children:[r.jsx(Bg,{className:"w-4 h-4 mr-1"}),a("common.edit")]})]}),c?r.jsx(oI,{content:u,onChange:m,placeholder:a("projectDetail.notes.placeholder")}):x.notes?r.jsx("div",{className:"prose prose-invert prose-sm max-w-none",dangerouslySetInnerHTML:{__html:DB.sanitize(x.notes)}}):r.jsx("p",{className:"text-bambu-gray/70 text-sm italic",children:a("projectDetail.notes.empty")})]})}),r.jsx(Tt,{children:r.jsxs(jt,{className:"p-4",children:[r.jsx("div",{className:"flex items-center justify-between mb-3",children:r.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[r.jsx(Fl,{className:"w-5 h-5"}),a("projectDetail.files.title")]})}),r.jsxs("p",{className:"text-xs text-bambu-gray mb-3",children:[r.jsx(Ls,{to:"/files",className:"text-bambu-green hover:underline",children:a("projectDetail.files.linkFolders")})," ",a("projectDetail.files.forQuickAccess")]}),R&&R.length>0?r.jsx("div",{className:"space-y-4",children:R.map(Me=>{const Be=z.get(Me.id)??[],Qe=O;return r.jsxs("div",{children:[r.jsxs(Ls,{to:`/files?folder=${Me.id}`,className:"flex items-center justify-between p-3 bg-bambu-dark rounded-lg hover:bg-bambu-dark-tertiary transition-colors mb-2",children:[r.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[r.jsx(Fl,{className:"w-5 h-5 text-bambu-green shrink-0"}),r.jsxs("div",{className:"min-w-0",children:[r.jsx("p",{className:"text-sm text-white truncate",children:Me.name}),r.jsx("p",{className:"text-xs text-bambu-gray",children:a("projectDetail.files.fileCount",{count:Me.file_count})})]})]}),r.jsx(Vn,{className:"w-4 h-4 text-bambu-gray shrink-0"})]}),Qe?r.jsx("div",{className:"flex items-center gap-2 px-3 py-2 text-bambu-gray text-sm",children:r.jsx(lt,{className:"w-4 h-4 animate-spin"})}):Be.length===0?r.jsx("p",{className:"text-bambu-gray/60 text-xs italic px-3",children:a("projectDetail.files.noFiles")}):r.jsx("div",{className:"space-y-1 pl-3",children:Be.map(Ge=>{const Ee=_st(Ge.filename);return r.jsxs("div",{className:"flex items-center gap-3 p-2 rounded-lg hover:bg-bambu-dark-tertiary transition-colors",children:[r.jsx("div",{className:"w-10 h-10 shrink-0 rounded bg-bambu-dark overflow-hidden flex items-center justify-center",children:Ge.thumbnail_path?r.jsx("img",{src:ne.getLibraryFileThumbnailUrl(Ge.id),alt:Ge.print_name||Ge.filename,className:"w-full h-full object-cover"}):r.jsx(Rh,{className:"w-5 h-5 text-bambu-gray/40"})}),r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsx("p",{className:"text-sm text-white truncate",title:Ge.print_name||Ge.filename,children:Ge.print_name||Ge.filename}),r.jsx("span",{className:`text-xs px-1.5 py-0.5 rounded font-medium ${Ge.file_type==="3mf"?"bg-bambu-green/20 text-bambu-green":Ge.file_type==="gcode"||Ge.file_type==="gcode.3mf"?"bg-blue-500/20 text-blue-400":"bg-bambu-gray/20 text-bambu-gray"}`,children:Ge.file_type.toUpperCase()})]}),Ee&&r.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[r.jsx("button",{onClick:()=>f(Ge),title:a("projectDetail.files.print"),className:"p-1.5 rounded hover:bg-bambu-green/20 text-bambu-green transition-colors",children:r.jsx(gs,{className:"w-4 h-4"})}),r.jsx("button",{onClick:()=>v(Ge),title:a("projectDetail.files.addToQueue"),className:"p-1.5 rounded hover:bg-blue-500/20 text-blue-400 transition-colors",children:r.jsx(Age,{className:"w-4 h-4"})})]})]},Ge.id)})})]},Me.id)})}):r.jsx("p",{className:"text-bambu-gray/70 text-sm italic",children:a("projectDetail.files.empty")})]})}),r.jsx(Tt,{children:r.jsxs(jt,{className:"p-4",children:[r.jsxs("div",{className:"flex items-center justify-between mb-4",children:[r.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[r.jsx(fb,{className:"w-5 h-5"}),a("projectDetail.bom.title"),Fe&&Fe.bom_total_items>0&&r.jsxs("span",{className:"text-sm font-normal text-bambu-gray",children:["(",a("projectDetail.bom.acquired",{completed:Fe.bom_completed_items,total:Fe.bom_total_items}),")"]})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[T&&T.some(Me=>Me.is_complete)&&r.jsx("button",{onClick:()=>U(!le),className:`text-xs px-2 py-1 rounded transition-colors ${le?"bg-bambu-green/20 text-bambu-green":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:a(le?"projectDetail.bom.showAll":"projectDetail.bom.hideDone")}),!W&&r.jsxs(Le,{variant:"secondary",size:"sm",onClick:()=>H(!0),disabled:!s("projects:update"),title:s("projects:update")?void 0:a("projectDetail.bom.noAddPermission"),children:[r.jsx(or,{className:"w-4 h-4 mr-1"}),a("projectDetail.bom.addPart")]})]})]}),W&&r.jsxs("form",{onSubmit:qe,className:"bg-bambu-dark rounded-lg p-4 mb-4 space-y-3",children:[r.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[r.jsx("input",{type:"text",value:K,onChange:Me=>ie(Me.target.value),className:"bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:a("projectDetail.bom.partNamePlaceholder"),autoFocus:!0}),r.jsxs("div",{className:"flex gap-2",children:[r.jsx("input",{type:"number",value:ue,onChange:Me=>he(parseInt(Me.target.value)||1),className:"w-20 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white focus:outline-none focus:border-bambu-green",min:"1",placeholder:a("projectDetail.bom.qty")}),r.jsx("input",{type:"number",step:"0.01",value:ge,onChange:Me=>q(Me.target.value),className:"flex-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:a("projectDetail.bom.price",{currency:X})})]})]}),r.jsx("input",{type:"url",value:Q,onChange:Me=>A(Me.target.value),className:"w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:a("projectDetail.bom.sourcingUrlPlaceholder")}),r.jsx("input",{type:"text",value:F,onChange:Me=>B(Me.target.value),className:"w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:a("projectDetail.bom.remarksPlaceholder")}),r.jsxs("div",{className:"flex justify-end gap-2",children:[r.jsx(Le,{type:"button",variant:"secondary",size:"sm",onClick:()=>H(!1),children:a("common.cancel")}),r.jsx(Le,{type:"submit",size:"sm",disabled:!K.trim()||De.isPending,children:De.isPending?r.jsx(lt,{className:"w-4 h-4 animate-spin"}):a("projectDetail.bom.addPart")})]})]}),j?r.jsx("div",{className:"flex items-center justify-center py-4",children:r.jsx(lt,{className:"w-6 h-6 animate-spin text-bambu-green"})}):T&&T.length>0?r.jsxs("div",{className:"space-y-2",children:[T.filter(Me=>!le||!Me.is_complete).map(Me=>r.jsx("div",{className:`p-3 rounded-lg transition-colors ${Me.is_complete?"bg-status-ok/10":"bg-bambu-dark"}`,children:G?.id===Me.id?r.jsxs("form",{onSubmit:Ue,className:"space-y-3",children:[r.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[r.jsx("input",{type:"text",value:J,onChange:Be=>re(Be.target.value),className:"bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:a("projectDetail.bom.partName"),autoFocus:!0}),r.jsxs("div",{className:"flex gap-2",children:[r.jsx("input",{type:"number",value:se,onChange:Be=>fe(parseInt(Be.target.value)||1),className:"w-20 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white focus:outline-none focus:border-bambu-green",min:"1",placeholder:a("projectDetail.bom.qty")}),r.jsx("input",{type:"number",step:"0.01",value:me,onChange:Be=>pe(Be.target.value),className:"flex-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:a("projectDetail.bom.price",{currency:X})})]})]}),r.jsx("input",{type:"url",value:V,onChange:Be=>L(Be.target.value),className:"w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:a("projectDetail.bom.sourcingUrlPlaceholder")}),r.jsx("input",{type:"text",value:te,onChange:Be=>be(Be.target.value),className:"w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:a("projectDetail.bom.remarksPlaceholder")}),r.jsxs("div",{className:"flex justify-end gap-2",children:[r.jsx(Le,{type:"button",variant:"secondary",size:"sm",onClick:ze,children:a("common.cancel")}),r.jsx(Le,{type:"submit",size:"sm",disabled:!J.trim()||je.isPending,children:je.isPending?r.jsx(lt,{className:"w-4 h-4 animate-spin"}):a("common.save")})]})]}):r.jsxs("div",{className:"flex items-start gap-3",children:[r.jsx("button",{onClick:()=>s("projects:update")&&Pe(Me),disabled:je.isPending||!s("projects:update"),title:s("projects:update")?void 0:a("projectDetail.bom.noUpdatePermission"),className:`w-5 h-5 mt-0.5 rounded border-2 flex items-center justify-center transition-colors shrink-0 ${Me.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:Me.is_complete&&r.jsx(fr,{className:"w-3 h-3"})}),r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsxs("div",{className:"flex items-center justify-between gap-2",children:[r.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[r.jsxs("p",{className:`text-sm font-medium ${Me.is_complete?"text-bambu-gray line-through":"text-white"}`,children:[Me.name,r.jsxs("span",{className:"text-bambu-gray font-normal ml-2",children:["x",Me.quantity_needed]})]}),Me.unit_price!==null&&r.jsxs("span",{className:"text-xs text-bambu-green whitespace-nowrap",children:[X,(Me.unit_price*Me.quantity_needed).toFixed(2)]})]}),r.jsxs("div",{className:"flex items-center gap-1",children:[r.jsx("button",{onClick:()=>s("projects:update")&&Re(Me),disabled:!s("projects:update"),className:`p-1 rounded transition-colors shrink-0 ${s("projects:update")?"hover:bg-bambu-dark-tertiary text-bambu-gray hover:text-white":"text-bambu-gray/50 cursor-not-allowed"}`,title:s("projects:update")?a("common.edit"):a("projectDetail.bom.noEditPermission"),children:r.jsx(ci,{className:"w-4 h-4"})}),r.jsx("button",{onClick:()=>s("projects:update")&&Ie(Me.id,Me.name),disabled:!s("projects:update"),className:`p-1 rounded transition-colors shrink-0 ${s("projects:update")?"hover:bg-bambu-dark-tertiary text-bambu-gray hover:text-red-400":"text-bambu-gray/50 cursor-not-allowed"}`,title:s("projects:update")?a("common.delete"):a("projectDetail.bom.noDeletePermission"),children:r.jsx(na,{className:"w-4 h-4"})})]})]}),Me.sourcing_url&&r.jsxs("a",{href:Me.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:Be=>Be.stopPropagation(),children:[r.jsx(Tr,{className:"w-3 h-3 shrink-0"}),r.jsx("span",{className:"truncate",children:(()=>{try{return new URL(Me.sourcing_url).hostname.replace("www.","")}catch{return Me.sourcing_url}})()})]}),Me.remarks&&r.jsx("p",{className:"mt-1 text-xs text-bambu-gray/80 italic",children:Me.remarks})]})]})},Me.id)),Fe&&Fe.bom_cost>0&&r.jsxs("div",{className:"pt-2 mt-2 border-t border-bambu-dark-tertiary flex justify-between text-sm",children:[r.jsx("span",{className:"text-bambu-gray",children:a("projectDetail.bom.totalCost")}),r.jsxs("span",{className:"text-white font-medium",children:[X,Fe.bom_cost.toFixed(2)]})]})]}):r.jsx("p",{className:"text-bambu-gray/70 text-sm italic",children:a("projectDetail.bom.empty")})]})}),r.jsx(Tt,{children:r.jsxs(jt,{className:"p-4",children:[r.jsx("div",{className:"flex items-center justify-between mb-3",children:r.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[r.jsx(Jh,{className:"w-5 h-5"}),a("projectDetail.timeline.title")]})}),C?r.jsx("div",{className:"flex items-center justify-center py-4",children:r.jsx(lt,{className:"w-6 h-6 animate-spin text-bambu-green"})}):D&&D.length>0?r.jsx("div",{className:"space-y-3",children:D.slice(0,10).map((Me,Be)=>r.jsxs("div",{className:"flex gap-3",children:[r.jsxs("div",{className:`w-8 h-8 rounded-full flex items-center justify-center shrink-0 ${Me.event_type==="print_completed"?"bg-status-ok/20 text-status-ok":Me.event_type==="print_failed"?"bg-status-error/20 text-status-error":Me.event_type==="print_started"?"bg-yellow-500/20 text-yellow-400":"bg-bambu-dark-tertiary text-bambu-gray"}`,children:[Me.event_type==="print_completed"&&r.jsx(fr,{className:"w-4 h-4"}),Me.event_type==="print_failed"&&r.jsx(Fr,{className:"w-4 h-4"}),Me.event_type==="print_started"&&r.jsx(xr,{className:"w-4 h-4"}),Me.event_type==="queued"&&r.jsx(c3,{className:"w-4 h-4"}),Me.event_type==="project_created"&&r.jsx(or,{className:"w-4 h-4"})]}),r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsx("p",{className:"text-sm text-white",children:Me.title}),Me.description&&r.jsx("p",{className:"text-xs text-bambu-gray truncate",children:Me.description}),r.jsx("p",{className:"text-xs text-bambu-gray/70",children:tt(Me.timestamp)})]})]},Be))}):r.jsx("p",{className:"text-bambu-gray/70 text-sm italic",children:a("projectDetail.timeline.empty")})]})}),!x.is_template&&r.jsx("div",{className:"flex justify-end",children:r.jsxs(Le,{variant:"secondary",size:"sm",onClick:()=>Oe.mutate(),disabled:Oe.isPending||!s("projects:create"),title:s("projects:create")?void 0:a("projectDetail.template.noCreatePermission"),children:[Oe.isPending?r.jsx(lt,{className:"w-4 h-4 animate-spin mr-2"}):r.jsx(li,{className:"w-4 h-4 mr-2"}),a("projectDetail.template.saveAsTemplate")]})}),Fe&&(Fe.queued_prints>0||Fe.in_progress_prints>0)&&r.jsx(Tt,{children:r.jsxs(jt,{className:"p-4",children:[r.jsxs("div",{className:"flex items-center justify-between mb-3",children:[r.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[r.jsx(c3,{className:"w-5 h-5"}),a("projectDetail.queue.title")]}),r.jsx(Ls,{to:`/queue?project=${b}`,className:"text-sm text-bambu-green hover:underline",children:a("projectDetail.queue.viewAll")})]}),r.jsxs("div",{className:"flex items-center gap-4 text-sm",children:[Fe.in_progress_prints>0&&r.jsx("span",{className:"text-yellow-400",children:a("projectDetail.queue.printing",{count:Fe.in_progress_prints})}),Fe.queued_prints>0&&r.jsx("span",{className:"text-bambu-gray",children:a("projectDetail.queue.queued",{count:Fe.queued_prints})})]})]})}),r.jsxs("div",{children:[r.jsx("div",{className:"flex items-center justify-between mb-4",children:r.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[r.jsx(en,{className:"w-5 h-5"}),a("projectDetail.prints.title",{count:P?.length||0})]})}),N?r.jsx("div",{className:"flex items-center justify-center py-8",children:r.jsx(lt,{className:"w-6 h-6 animate-spin text-bambu-green"})}):r.jsx(Nst,{archives:P||[],t:a})]}),o&&r.jsx(Ade,{t:a,currencySymbol:X,project:{...x,archive_count:Fe?.total_archives||0,total_items:Fe?.total_items||0,completed_count:Fe?.completed_prints||0,failed_count:Fe?.failed_prints||0,queue_count:Fe?.queued_prints||0,progress_percent:Fe?.progress_percent||null,archives:[]},onClose:()=>l(!1),onSave:Me=>Y.mutate(Me),isLoading:Y.isPending}),xe.isOpen&&r.jsx(ka,{title:xe.title,message:xe.message,confirmText:a("common.delete"),variant:"danger",onConfirm:xe.onConfirm,onCancel:()=>ve(Me=>({...Me,isOpen:!1}))}),p&&r.jsx(Pc,{mode:"reprint",libraryFileId:p.id,archiveName:p.print_name||p.filename,projectId:b,onClose:()=>f(null),onSuccess:()=>{f(null),n.invalidateQueries({queryKey:["archives"]})}}),g&&r.jsx(Pc,{mode:"add-to-queue",libraryFileId:g.id,archiveName:g.print_name||g.filename,projectId:b,onClose:()=>v(null),onSuccess:()=>{v(null),n.invalidateQueries({queryKey:["queue"]})}})]})}function jst({archiveId:t,libraryFileId:e,title:a,fileType:n,onClose:i,onSliceWithBambuddy:s}){const{t:o}=wt(),{data:l}=$e({queryKey:["settings"],queryFn:ne.getSettings}),c=l?.open_in_slicer||l?.preferred_slicer||"bambu_studio",d=e!=null,[u,m]=y.useState(null),[p,f]=y.useState(null),[g,v]=y.useState(!0),[b,x]=y.useState(null),[S,k]=y.useState(!1),[P,N]=y.useState(null),[T,j]=y.useState(0),[D,C]=y.useState(!1),[E,R]=y.useState(null),[I,O]=y.useState(!1),[z,X]=y.useState(!1),ae=y.useRef(null),Y=y.useRef(null),ce=10,de=160,oe=240,K=.35;y.useEffect(()=>{const L=te=>{te.key==="Escape"&&i()};return window.addEventListener("keydown",L),()=>window.removeEventListener("keydown",L)},[i]),y.useEffect(()=>{if(v(!0),d){const L=(n||"").toLowerCase(),te=L==="3mf"||L==="gcode.3mf",be=te||L==="stl",xe=te||L==="gcode";f({has_model:be,has_gcode:xe,has_source:!1,build_volume:{x:256,y:256,z:256},filament_colors:[]}),m(be?"3d":xe?"gcode":null),v(!1);return}if(!t){f(null),m(null),v(!1);return}ne.getArchiveCapabilities(t).then(L=>{f(L),L.has_model?m("3d"):L.has_gcode&&m("gcode"),v(!1)}).catch(()=>{f({has_model:!0,has_gcode:!1,has_source:!1,build_volume:{x:256,y:256,z:256},filament_colors:[]}),m("3d"),v(!1)})},[t,n,d]),y.useEffect(()=>{if(k(!0),N(null),j(0),d){const L=(n||"").toLowerCase();if(!e||!(L==="3mf"||L==="gcode.3mf")){x(null),k(!1);return}ne.getLibraryFilePlates(e).then(be=>x(be)).catch(()=>x(null)).finally(()=>k(!1));return}if(!t){x(null),k(!1);return}ne.getArchivePlates(t).then(L=>x(L)).catch(()=>x(null)).finally(()=>k(!1))},[t,n,d,e]);const ie=y.useMemo(()=>b?.plates??[],[b]),ue=(b?.is_multi_plate??!1)&&ie.length>1,he=D&&ue,ge=P==null?null:ie.find(L=>L.index===P)??null,q=L=>L.object_count??L.objects?.length??0,Q=ie.reduce((L,te)=>L+q(te),0),A=ge?q(ge):Q,F=ge?o("modelViewer.plateNumber",{number:ge.index}):o("modelViewer.allPlates"),B=ie.length>0,W=y.useRef(null),H=y.useRef(null),[le,U]=y.useState(10),[G,Z]=y.useState(3),J=ie.length>le,re=Math.max(1,Math.ceil(ie.length/le)),se=J?ie.slice(T*le,(T+1)*le):ie;y.useEffect(()=>{if(!he){U(10),Z(3);return}const L=W.current,te=H.current;if(!L||!te)return;let be=0;const xe=()=>{const je=te.clientWidth,qe=Math.floor(je/210),Pe=Math.max(3,Math.min(5,qe||3));Z(Ye=>Ye===Pe?Ye:Pe);const Ie=window.getComputedStyle(L),Re=Number.parseFloat(Ie.rowGap||"0"),ze=L.querySelector("button")?.getBoundingClientRect().height??44,it=te.clientHeight,tt=Math.max(1,Math.floor((it+Re)/(ze+Re)))*Pe,Fe=Math.max(1,tt-1);U(Ye=>Ye===Fe?Ye:Fe)},ve=()=>{be&&cancelAnimationFrame(be),be=requestAnimationFrame(xe)};ve();const De=new ResizeObserver(ve);return De.observe(te),De.observe(L),()=>{be&&cancelAnimationFrame(be),De.disconnect()}},[he,ie.length]),y.useEffect(()=>{if(!J){j(0);return}j(L=>Math.min(L,re-1))},[ie.length,J,re]),y.useEffect(()=>{if(!J||P==null)return;const L=ie.findIndex(be=>be.index===P);if(L<0)return;const te=Math.floor(L/le);j(be=>be===te?be:te)},[ie,le,P,J]),y.useEffect(()=>{if(!he){R(null),X(!1);return}if(z)return;const L=ae.current,te=Y.current;if(!L||!te)return;const be=L.clientHeight;if(!be)return;const xe=Math.max(oe,be*K),ve=Math.max(de,be-ce-xe),De=Math.min(te.scrollHeight,ve);R(Math.max(de,De))},[he,z,ie.length,T,ce,de,oe,K]),y.useEffect(()=>{if(!I)return;const L=be=>{const xe=ae.current;if(!xe)return;const ve=xe.getBoundingClientRect(),De=ve.height;if(!De)return;const je=Math.max(oe,De*K),Te=Math.max(de,De-ce-je),qe=Math.min(Te,Math.max(de,be.clientY-ve.top));R(qe)},te=()=>{O(!1),X(!0)};return document.addEventListener("mousemove",L),document.addEventListener("mouseup",te),document.body.style.cursor="row-resize",document.body.style.userSelect="none",()=>{document.removeEventListener("mousemove",L),document.removeEventListener("mouseup",te),document.body.style.cursor="",document.body.style.userSelect=""}},[I,ce,de,oe,K]);const fe=d?(n||"").toLowerCase()==="3mf":!0,me=(()=>{const L=(n||"").toLowerCase();return L==="3mf"||L==="stl"||L==="step"||L==="stp"})(),pe=!!(d&&l?.use_slicer_api&&s&&me),V=async()=>{if(!fe)return;const L=a||"model";try{if(d){const{token:te}=await ne.createLibrarySlicerToken(e),be=ne.getLibrarySlicerDownloadUrl(e,te,L);Lm(`${window.location.origin}${be}`,c)}else{const{token:te}=await ne.createArchiveSlicerToken(t),be=ne.getArchiveSlicerDownloadUrl(t,te,L);Lm(`${window.location.origin}${be}`,c)}}catch{if(d){const te=`${window.location.origin}${ne.getLibraryFileDownloadUrl(e)}`;Lm(te,c)}else{const te=`${window.location.origin}${ne.getArchiveForSlicer(t,L)}`;Lm(te,c)}}};return r.jsx("div",{className:`fixed inset-0 bg-black/70 flex items-center justify-center z-50 ${D?"p-0":"p-8"}`,onClick:i,children:r.jsxs("div",{className:`bg-bambu-dark-secondary border border-bambu-dark-tertiary w-full flex flex-col ${D?"h-full max-w-none rounded-none":"h-[80vh] max-w-4xl rounded-xl"}`,onClick:L=>L.stopPropagation(),children:[r.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"flex items-center gap-3 min-w-0 flex-1 mr-4",children:[r.jsx("h2",{className:"text-lg font-semibold text-white truncate",children:a}),B&&r.jsxs("span",{className:"text-xs text-bambu-gray bg-bambu-dark-tertiary/70 px-2 py-1 rounded whitespace-nowrap",children:[F,": ",o("modelViewer.objectCount",{count:A})]})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[pe?r.jsxs(Le,{variant:"secondary",size:"sm",onClick:s,children:[r.jsx(bd,{className:"w-4 h-4"}),o("slice.action")]}):r.jsxs(Le,{variant:"secondary",size:"sm",onClick:V,disabled:!fe,children:[r.jsx(Tr,{className:"w-4 h-4"}),o("modelViewer.openInSlicer")]}),r.jsx(Le,{variant:"secondary",size:"sm",onClick:()=>C(L=>!L),title:D?"Exit fullscreen":"Enter fullscreen",children:D?r.jsx(UI,{className:"w-4 h-4"}):r.jsx(LT,{className:"w-4 h-4"})}),r.jsx(Le,{variant:"ghost",size:"sm",onClick:i,children:r.jsx(Ht,{className:"w-5 h-5"})})]})]}),p&&r.jsxs("div",{className:"flex border-b border-bambu-dark-tertiary",children:[r.jsxs("button",{onClick:()=>p.has_model&&m("3d"),disabled:!p.has_model,className:`flex items-center gap-2 px-6 py-3 text-sm font-medium transition-colors ${u==="3d"?"text-bambu-green border-b-2 border-bambu-green":p.has_model?"text-bambu-gray hover:text-white":"text-bambu-gray/30 cursor-not-allowed"}`,children:[r.jsx(Ei,{className:"w-4 h-4"}),o("modelViewer.tabs.model"),!p.has_model&&r.jsxs("span",{className:"text-xs",children:["(",o("modelViewer.notAvailable"),")"]})]}),r.jsxs("button",{onClick:()=>p.has_gcode&&m("gcode"),disabled:!p.has_gcode,className:`flex items-center gap-2 px-6 py-3 text-sm font-medium transition-colors ${u==="gcode"?"text-bambu-green border-b-2 border-bambu-green":p.has_gcode?"text-bambu-gray hover:text-white":"text-bambu-gray/30 cursor-not-allowed"}`,children:[r.jsx(obe,{className:"w-4 h-4"}),o("modelViewer.tabs.gcode"),!p.has_gcode&&r.jsxs("span",{className:"text-xs",children:["(",o("modelViewer.notSliced"),")"]})]})]}),r.jsx("div",{className:"flex-1 overflow-hidden p-4",children:g?r.jsx("div",{className:"w-full h-full flex items-center justify-center",children:r.jsx(lt,{className:"w-8 h-8 animate-spin text-bambu-green"})}):u==="3d"&&p?r.jsxs("div",{ref:ae,className:`w-full h-full flex flex-col ${he?"gap-0 min-h-0":"gap-3"}`,children:[ue&&r.jsxs("div",{ref:Y,style:he&&E!=null?{height:E}:void 0,className:`rounded-lg border border-bambu-dark-tertiary bg-bambu-dark p-3 ${he?"flex flex-col shrink-0":""}`,children:[r.jsxs("div",{className:"flex items-center gap-2 text-sm text-bambu-gray mb-2",children:[r.jsx(tn,{className:"w-4 h-4"}),o("modelViewer.plates"),S&&r.jsx(lt,{className:"w-3 h-3 animate-spin"})]}),r.jsxs("div",{className:he?"flex flex-col min-h-0 flex-1":void 0,children:[r.jsx("div",{ref:H,className:he?"min-h-0 overflow-hidden pr-1 flex-1":void 0,children:r.jsxs("div",{ref:W,className:he?"grid gap-2":"grid grid-cols-2 md:grid-cols-3 gap-2",style:he?{gridTemplateColumns:`repeat(${G}, minmax(0, 1fr))`}:void 0,children:[r.jsxs("button",{type:"button",onClick:()=>N(null),className:`flex items-center rounded-lg border text-left transition-colors ${he?"gap-1.5 p-1.5 w-full":"gap-2 p-2"} ${P==null?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary bg-bambu-dark-secondary hover:border-bambu-gray"}`,children:[r.jsx("div",{className:`rounded bg-bambu-dark-tertiary flex items-center justify-center ${he?"w-8 h-8":"w-10 h-10"}`,children:r.jsx(tn,{className:`${he?"w-4 h-4":"w-5 h-5"} text-bambu-gray`})}),r.jsxs("div",{className:"min-w-0 flex-1",children:[r.jsx("p",{className:`${he?"text-xs":"text-sm"} text-white font-medium truncate`,children:o("modelViewer.allPlates")}),r.jsx("p",{className:`${he?"text-[10px]":"text-xs"} text-bambu-gray truncate`,children:o("modelViewer.plateCount",{count:ie.length})})]}),P==null&&r.jsx(_r,{className:`${he?"w-3.5 h-3.5":"w-4 h-4"} text-bambu-green flex-shrink-0`})]}),se.map(L=>r.jsxs("button",{type:"button",onClick:()=>N(L.index),className:`flex items-center rounded-lg border text-left transition-colors ${he?"gap-1.5 p-1.5 w-full":"gap-2 p-2"} ${P===L.index?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary bg-bambu-dark-secondary hover:border-bambu-gray"}`,children:[L.has_thumbnail&&L.thumbnail_url?r.jsx("img",{src:L.thumbnail_url,alt:`Plate ${L.index}`,className:`${he?"w-8 h-8":"w-10 h-10"} rounded object-cover bg-bambu-dark-tertiary`}):r.jsx("div",{className:`rounded bg-bambu-dark-tertiary flex items-center justify-center ${he?"w-8 h-8":"w-10 h-10"}`,children:r.jsx(tn,{className:`${he?"w-4 h-4":"w-5 h-5"} text-bambu-gray`})}),r.jsxs("div",{className:"min-w-0 flex-1",children:[r.jsx("p",{className:`${he?"text-xs":"text-sm"} text-white font-medium truncate`,children:L.name||o("modelViewer.plateNumber",{number:L.index})}),r.jsx("p",{className:`${he?"text-[10px]":"text-xs"} text-bambu-gray truncate`,children:o("modelViewer.objectCount",{count:L.object_count??L.objects?.length??0})})]}),P===L.index&&r.jsx(_r,{className:`${he?"w-3.5 h-3.5":"w-4 h-4"} text-bambu-green flex-shrink-0`})]},L.index))]})}),(ge||J)&&r.jsxs("div",{className:"mt-auto pt-3 flex items-center gap-4 text-xs text-bambu-gray overflow-x-auto",children:[ge&&r.jsxs("div",{className:"flex items-center gap-3 whitespace-nowrap",children:[r.jsx("span",{children:o("modelViewer.plateNumber",{number:ge.index})}),ge.print_time_seconds!=null&&r.jsx("span",{children:o("modelViewer.eta",{minutes:Math.round(ge.print_time_seconds/60)})}),ge.filament_used_grams!=null&&r.jsxs("span",{children:[ge.filament_used_grams.toFixed(1)," g"]}),ge.filaments.length>0&&r.jsx("span",{children:o("modelViewer.filamentCount",{count:ge.filaments.length})})]}),J&&r.jsxs("div",{className:`flex items-center gap-2 whitespace-nowrap ${ge?"ml-auto":""}`,children:[r.jsx("span",{children:o("modelViewer.pagination.pageOf",{current:T+1,total:re})}),r.jsxs("div",{className:"flex items-center gap-1",children:[r.jsx("button",{type:"button",onClick:()=>j(L=>Math.max(L-1,0)),disabled:T===0,className:`px-2 py-1 rounded border text-xs ${T===0?"border-bambu-dark-tertiary text-bambu-gray/40 cursor-not-allowed":"border-bambu-dark-tertiary text-bambu-gray hover:text-white hover:border-bambu-gray"}`,children:o("modelViewer.pagination.prev")}),(()=>{let te=Math.max(0,T-Math.floor(2.5));const be=Math.min(re,te+5);be-te<5&&(te=Math.max(0,be-5));const xe=Array.from({length:be-te},(ve,De)=>te+De);return r.jsxs(r.Fragment,{children:[te>0&&r.jsx("button",{type:"button",onClick:()=>j(0),className:`px-2 py-1 rounded border text-xs ${T===0?"border-bambu-green text-bambu-green":"border-bambu-dark-tertiary text-bambu-gray hover:text-white hover:border-bambu-gray"}`,children:"1"}),te>1&&r.jsx("span",{className:"px-1",children:"…"}),xe.map(ve=>r.jsx("button",{type:"button",onClick:()=>j(ve),className:`px-2 py-1 rounded border text-xs ${T===ve?"border-bambu-green text-bambu-green":"border-bambu-dark-tertiary text-bambu-gray hover:text-white hover:border-bambu-gray"}`,children:ve+1},ve)),bej(re-1),className:`px-2 py-1 rounded border text-xs ${T===re-1?"border-bambu-green text-bambu-green":"border-bambu-dark-tertiary text-bambu-gray hover:text-white hover:border-bambu-gray"}`,children:re})]})})(),r.jsx("button",{type:"button",onClick:()=>j(L=>Math.min(L+1,re-1)),disabled:T>=re-1,className:`px-2 py-1 rounded border text-xs ${T>=re-1?"border-bambu-dark-tertiary text-bambu-gray/40 cursor-not-allowed":"border-bambu-dark-tertiary text-bambu-gray hover:text-white hover:border-bambu-gray"}`,children:o("modelViewer.pagination.next")})]})]})]})]})]}),he&&r.jsx("div",{role:"separator","aria-orientation":"horizontal",onMouseDown:L=>{L.preventDefault(),O(!0),X(!0)},className:`h-2 cursor-row-resize flex items-center justify-center ${I?"bg-bambu-dark-tertiary":"bg-bambu-dark-secondary/60 hover:bg-bambu-dark-tertiary"}`,children:r.jsx("div",{className:"w-12 h-1 rounded-full bg-bambu-gray/50"})}),r.jsx("div",{className:`flex-1 ${he?"min-h-0":""}`,children:r.jsx(yee,{url:d?ne.getLibraryFileDownloadUrl(e):p.has_source?ne.getSource3mfDownloadUrl(t):ne.getArchiveDownload(t),fileType:n,buildVolume:p.build_volume,filamentColors:p.filament_colors,selectedPlateId:P,className:"w-full h-full"})})]}):u==="gcode"&&p?r.jsx(tte,{gcodeUrl:d?ne.getLibraryFileGcodeUrl(e):ne.getArchiveGcode(t),filamentColors:p.filament_colors,className:"w-full h-full"}):r.jsx("div",{className:"w-full h-full flex items-center justify-center text-bambu-gray",children:o("modelViewer.noPreview")})})]})})}const Mst=90;function Est({onClose:t}){const{t:e}=wt(),a=ia(),{showToast:n}=da(),[i,s]=y.useState(Mst),[o,l]=y.useState(!0),[c,d]=y.useState(i);y.useEffect(()=>{const b=window.setTimeout(()=>d(i),300);return()=>window.clearTimeout(b)},[i]);const u=$e({queryKey:["library-purge-preview",c,o],queryFn:()=>ne.previewLibraryPurge(c,o),enabled:c>=1}),m=rt({mutationFn:()=>ne.executeLibraryPurge(i,o),onSuccess:b=>{n(e("libraryPurge.toast.success",{count:b.moved_to_trash}),"success"),a.invalidateQueries({queryKey:["library-files"]}),a.invalidateQueries({queryKey:["library-folders"]}),a.invalidateQueries({queryKey:["library-trash"]}),a.invalidateQueries({queryKey:["library-trash-count"]}),t()},onError:b=>n(b.message||e("libraryPurge.toast.failed"),"error")});y.useEffect(()=>{const b=x=>{x.key==="Escape"&&!m.isPending&&t()};return window.addEventListener("keydown",b),()=>window.removeEventListener("keydown",b)},[t,m.isPending]);const p=u.data,f=p?.count??0,g=p?.total_bytes??0,v=f>0&&!m.isPending;return r.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4",children:r.jsxs("div",{className:"bg-white dark:bg-gray-900 rounded-lg shadow-xl max-w-lg w-full",children:[r.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-gray-200 dark:border-gray-700",children:[r.jsxs("h2",{className:"text-lg font-semibold text-gray-900 dark:text-gray-100 flex items-center gap-2",children:[r.jsx(na,{className:"w-5 h-5"}),e("libraryPurge.title")]}),r.jsx("button",{onClick:t,className:"text-gray-400 hover:text-gray-600 dark:hover:text-gray-200","aria-label":e("common.close"),disabled:m.isPending,children:r.jsx(Ht,{className:"w-5 h-5"})})]}),r.jsxs("div",{className:"p-4 space-y-4",children:[r.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-400",children:e("libraryPurge.description")}),r.jsxs("div",{children:[r.jsx("label",{htmlFor:"purge-days",className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1",children:e("libraryPurge.ageLabel")}),r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("input",{id:"purge-days",type:"number",min:1,max:3650,value:i,onChange:b=>s(Math.max(1,Math.min(3650,parseInt(b.target.value||"0",10)||0))),className:"w-24 rounded border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-sm px-2 py-1 text-gray-900 dark:text-gray-100"}),r.jsx("span",{className:"text-sm text-gray-600 dark:text-gray-400",children:e("libraryPurge.days")})]})]}),r.jsxs("label",{className:"flex items-center gap-2 text-sm text-gray-700 dark:text-gray-300",children:[r.jsx("input",{type:"checkbox",checked:o,onChange:b=>l(b.target.checked),className:"rounded border-gray-300"}),e("libraryPurge.includeNeverPrinted")]}),r.jsxs("div",{className:"rounded border border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-800/30 p-3",children:[r.jsx("div",{className:"text-xs font-semibold uppercase tracking-wide text-gray-600 dark:text-gray-300 mb-2",children:e("libraryPurge.effectsTitle")}),r.jsxs("ul",{className:"text-xs text-gray-700 dark:text-gray-300 space-y-1 list-disc pl-4",children:[r.jsx("li",{children:e("libraryPurge.effect1")}),r.jsx("li",{children:e("libraryPurge.effect2")}),r.jsx("li",{children:e("libraryPurge.effect3")}),r.jsx("li",{children:e("libraryPurge.effect4")})]})]}),r.jsx("div",{className:"rounded border border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-800/50 p-3",children:u.isLoading||u.isFetching?r.jsxs("div",{className:"flex items-center gap-2 text-sm text-gray-500 dark:text-gray-400",children:[r.jsx(lt,{className:"w-4 h-4 animate-spin"})," ",e("libraryPurge.previewLoading")]}):u.isError?r.jsx("div",{className:"text-sm text-red-600 dark:text-red-400",children:u.error?.message??e("libraryPurge.previewFailed")}):r.jsxs("div",{className:"text-sm text-gray-900 dark:text-gray-100",children:[r.jsx("div",{className:"font-medium",children:e("libraryPurge.previewSummary",{count:f,size:cs(g)})}),p?.sample_filenames&&p.sample_filenames.length>0&&r.jsxs("ul",{className:"mt-2 text-xs text-gray-600 dark:text-gray-400 space-y-0.5 list-disc pl-4",children:[p.sample_filenames.map(b=>r.jsx("li",{className:"truncate",children:b},b)),f>p.sample_filenames.length&&r.jsx("li",{className:"list-none italic text-gray-500",children:e("libraryPurge.andMore",{count:f-p.sample_filenames.length})})]})]})}),r.jsxs("div",{className:"flex gap-2 items-start text-xs text-amber-700 dark:text-amber-400 bg-amber-50 dark:bg-amber-900/20 rounded px-3 py-2",children:[r.jsx(xa,{className:"w-4 h-4 mt-0.5 shrink-0"}),r.jsx("span",{children:e("libraryPurge.warning")})]})]}),r.jsxs("div",{className:"flex justify-end gap-2 p-4 border-t border-gray-200 dark:border-gray-700",children:[r.jsx(Le,{variant:"secondary",onClick:t,disabled:m.isPending,children:e("common.cancel")}),r.jsx(Le,{variant:"danger",disabled:!v,onClick:()=>m.mutate(),children:m.isPending?r.jsxs(r.Fragment,{children:[r.jsx(lt,{className:"w-4 h-4 animate-spin mr-1"}),e("libraryPurge.purging")]}):e("libraryPurge.confirmCta",{count:f})})]})]})})}function Dst({parentId:t,onClose:e,onSave:a,isLoading:n,t:i}){const[s,o]=y.useState(""),l=c=>{c.preventDefault(),a({name:s.trim(),parent_id:t})};return r.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:r.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-sm border border-bambu-dark-tertiary",children:[r.jsx("div",{className:"p-4 border-b border-bambu-dark-tertiary",children:r.jsx("h2",{className:"text-lg font-semibold text-white",children:i("fileManager.newFolder")})}),r.jsxs("form",{onSubmit:l,className:"p-4 space-y-4",children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:i("fileManager.folderName")}),r.jsx("input",{type:"text",value:s,onChange:c=>o(c.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:i("fileManager.folderNamePlaceholder"),autoFocus:!0,required:!0})]}),r.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[r.jsx(Le,{type:"button",variant:"secondary",onClick:e,children:i("common.cancel")}),r.jsx(Le,{type:"submit",disabled:!s.trim()||n,children:n?r.jsx(lt,{className:"w-4 h-4 animate-spin"}):i("common.create")})]})]})]})})}function Fst({onClose:t,onSave:e,isLoading:a,t:n}){const[i,s]=y.useState(""),[o,l]=y.useState(""),[c,d]=y.useState(!0),[u,m]=y.useState(!1),p=f=>{f.preventDefault(),e({name:i.trim(),external_path:o.trim(),readonly:c,show_hidden:u})};return r.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:r.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-md border border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"p-4 border-b border-bambu-dark-tertiary",children:[r.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[r.jsx(ow,{className:"w-5 h-5 text-bambu-green"}),n("fileManager.linkExternalFolder")]}),r.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:n("fileManager.linkExternalFolderDescription")})]}),r.jsxs("form",{onSubmit:p,className:"p-4 space-y-4",children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:n("fileManager.folderName")}),r.jsx("input",{type:"text",value:i,onChange:f=>s(f.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:n("fileManager.externalFolderNamePlaceholder"),autoFocus:!0,required:!0})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:n("fileManager.externalPath")}),r.jsx("input",{type:"text",value:o,onChange:f=>l(f.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green font-mono text-sm",placeholder:"/mnt/nas/3d-prints",required:!0}),r.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:n("fileManager.externalPathHelp")})]}),r.jsxs("div",{className:"space-y-2",children:[r.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[r.jsx("input",{type:"checkbox",checked:c,onChange:f=>d(f.target.checked),className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),r.jsx("span",{className:"text-sm text-white",children:n("fileManager.readOnly")}),r.jsxs("span",{className:"text-xs text-bambu-gray",children:["(",n("fileManager.readOnlyHelp"),")"]})]}),r.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[r.jsx("input",{type:"checkbox",checked:u,onChange:f=>m(f.target.checked),className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),r.jsx("span",{className:"text-sm text-white",children:n("fileManager.showHiddenFiles")})]})]}),r.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[r.jsx(Le,{type:"button",variant:"secondary",onClick:t,children:n("common.cancel")}),r.jsx(Le,{type:"submit",disabled:!i.trim()||!o.trim()||a,children:a?r.jsx(lt,{className:"w-4 h-4 animate-spin"}):n("fileManager.linkFolder")})]})]})]})})}const Lst='<>:"/\\|?*';function Rst(t){for(const e of t)if(Lst.includes(e)||e.charCodeAt(0)<32)return e;return null}function zst({type:t,currentName:e,onClose:a,onSave:n,isLoading:i,t:s}){const o=t==="file"?e.match(/(\.gcode\.3mf|\.3mf|\.gcode)$/i)?.[1]??"":"",l=t==="file"&&o?e.slice(0,-o.length):e,[c,d]=y.useState(l),u=t==="file"?Rst(c):null,m=u?s("fileManager.invalidFilenameChar",{char:u}):null,p=f=>{if(f.preventDefault(),m)return;const g=t==="file"?c.trim()+o:c.trim();c.trim()&&g!==e&&n(g)};return r.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:r.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-sm border border-bambu-dark-tertiary",children:[r.jsx("div",{className:"p-4 border-b border-bambu-dark-tertiary",children:r.jsx("h2",{className:"text-lg font-semibold text-white",children:s(t==="file"?"fileManager.renameFile":"fileManager.renameFolder")})}),r.jsxs("form",{onSubmit:p,className:"p-4 space-y-4",children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("common.name")}),r.jsxs("div",{className:`flex items-center bg-bambu-dark border rounded focus-within:border-bambu-green ${m?"border-red-500":"border-bambu-dark-tertiary"}`,children:[r.jsx("input",{type:"text",value:c,onChange:f=>d(f.target.value),className:"flex-1 bg-transparent px-3 py-2 text-white placeholder-bambu-gray focus:outline-none min-w-0",autoFocus:!0,required:!0}),o&&r.jsx("span",{className:"pr-3 text-bambu-gray text-sm select-none whitespace-nowrap",children:o})]}),m&&r.jsx("p",{className:"mt-1 text-xs text-red-400",children:m})]}),r.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[r.jsx(Le,{type:"button",variant:"secondary",onClick:a,children:s("common.cancel")}),r.jsx(Le,{type:"submit",disabled:!c.trim()||c.trim()===l||!!m||i,children:i?r.jsx(lt,{className:"w-4 h-4 animate-spin"}):s("common.rename")})]})]})]})})}function Ist({folders:t,selectedFiles:e,currentFolderId:a,onClose:n,onMove:i,isLoading:s,t:o}){const[l,c]=y.useState(null),d=(m,p=0)=>{const f=[];for(const g of m)f.push({id:g.id,name:g.name,depth:p}),g.children.length>0&&f.push(...d(g.children,p+1));return f},u=[{id:null,name:o("fileManager.rootNoFolder"),depth:0},...d(t)];return r.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:r.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-sm border border-bambu-dark-tertiary",children:[r.jsx("div",{className:"p-4 border-b border-bambu-dark-tertiary",children:r.jsx("h2",{className:"text-lg font-semibold text-white",children:o("fileManager.moveFiles",{count:e.length})})}),r.jsxs("div",{className:"p-4 space-y-4",children:[r.jsx("div",{className:"max-h-64 overflow-y-auto space-y-1",children:u.map(m=>r.jsxs("button",{onClick:()=>c(m.id),disabled:m.id===a,className:`w-full text-left px-3 py-2 rounded transition-colors flex items-center gap-2 ${l===m.id?"bg-bambu-green/20 text-bambu-green":m.id===a?"opacity-50 cursor-not-allowed text-bambu-gray":"hover:bg-bambu-dark text-white"}`,style:{paddingLeft:`${12+m.depth*16}px`},children:[r.jsx(Fl,{className:"w-4 h-4"}),m.name,m.id===a&&r.jsxs("span",{className:"text-xs text-bambu-gray ml-auto",children:["(",o("fileManager.current"),")"]})]},m.id??"root"))}),r.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[r.jsx(Le,{type:"button",variant:"secondary",onClick:n,children:o("common.cancel")}),r.jsx(Le,{onClick:()=>i(l),disabled:s,children:s?r.jsx(lt,{className:"w-4 h-4 animate-spin"}):o("common.move")})]})]})]})})}function Ost({folder:t,onClose:e,onLink:a,isLoading:n,t:i}){const[s,o]=y.useState("project"),[l,c]=y.useState(t.project_id||t.archive_id||null);y.useState(()=>{t.archive_id&&o("archive")});const{data:d}=$e({queryKey:["projects"],queryFn:()=>ne.getProjects(),select:g=>[...g].sort((v,b)=>v.name.localeCompare(b.name))}),{data:u}=$e({queryKey:["archives-for-link"],queryFn:()=>ne.getArchives(void 0,void 0,100)}),m=()=>{a(s==="project"?{project_id:l,archive_id:0}:{project_id:0,archive_id:l})},p=()=>{a({project_id:0,archive_id:0})},f=t.project_id||t.archive_id;return r.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:r.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-md border border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"p-4 border-b border-bambu-dark-tertiary flex items-center justify-between",children:[r.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[r.jsx(Oh,{className:"w-5 h-5 text-bambu-green"}),i("fileManager.linkFolder")]}),r.jsx("button",{onClick:e,className:"p-1 hover:bg-bambu-dark rounded",children:r.jsx(Ht,{className:"w-5 h-5 text-bambu-gray"})})]}),r.jsxs("div",{className:"p-4 space-y-4",children:[r.jsx("p",{className:"text-sm text-bambu-gray",children:i("fileManager.linkFolderDescription",{name:t.name})}),r.jsxs("div",{className:"flex gap-2",children:[r.jsxs("button",{onClick:()=>{o("project"),c(null)},className:`flex-1 flex items-center justify-center gap-2 px-3 py-2 rounded-lg border transition-colors ${s==="project"?"border-bambu-green bg-bambu-green/10 text-bambu-green":"border-bambu-dark-tertiary text-bambu-gray hover:text-white"}`,children:[r.jsx(rJ,{className:"w-4 h-4"}),i("fileManager.project")]}),r.jsxs("button",{onClick:()=>{o("archive"),c(null)},className:`flex-1 flex items-center justify-center gap-2 px-3 py-2 rounded-lg border transition-colors ${s==="archive"?"border-bambu-green bg-bambu-green/10 text-bambu-green":"border-bambu-dark-tertiary text-bambu-gray hover:text-white"}`,children:[r.jsx(ro,{className:"w-4 h-4"}),i("fileManager.archive")]})]}),r.jsx("div",{className:"max-h-64 overflow-y-auto space-y-1 bg-bambu-dark rounded-lg p-2",children:s==="project"?d&&d.length>0?d.map(g=>r.jsxs("button",{onClick:()=>c(g.id),className:`w-full text-left px-3 py-2 rounded transition-colors flex items-center gap-2 ${l===g.id?"bg-bambu-green/20 text-bambu-green":"hover:bg-bambu-dark-tertiary text-white"}`,children:[r.jsx("div",{className:"w-3 h-3 rounded-full flex-shrink-0",style:{backgroundColor:g.color||"#00ae42"}}),r.jsx("span",{className:"truncate",children:g.name})]},g.id)):r.jsx("p",{className:"text-sm text-bambu-gray text-center py-4",children:i("fileManager.noProjectsFound")}):u&&u.length>0?u.map(g=>r.jsxs("button",{onClick:()=>c(g.id),className:`w-full text-left px-3 py-2 rounded transition-colors flex items-center gap-2 ${l===g.id?"bg-bambu-green/20 text-bambu-green":"hover:bg-bambu-dark-tertiary text-white"}`,children:[r.jsx(Rh,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"}),r.jsx("span",{className:"truncate",children:g.print_name||g.filename})]},g.id)):r.jsx("p",{className:"text-sm text-bambu-gray text-center py-4",children:i("fileManager.noArchivesFound")})})]}),r.jsxs("div",{className:"p-4 border-t border-bambu-dark-tertiary flex justify-between",children:[f&&r.jsxs(Le,{variant:"danger",onClick:p,disabled:n,children:[r.jsx(mu,{className:"w-4 h-4 mr-2"}),i("fileManager.unlink")]}),r.jsxs("div",{className:`flex gap-2 ${f?"":"ml-auto"}`,children:[r.jsx(Le,{variant:"secondary",onClick:e,children:i("common.cancel")}),r.jsx(Le,{onClick:m,disabled:!l||n,children:n?r.jsx(lt,{className:"w-4 h-4 animate-spin"}):i("fileManager.link")})]})]})]})})}function jde({folder:t,selectedFolderId:e,onSelect:a,onDelete:n,onLink:i,onRename:s,depth:o=0,wrapNames:l=!1,defaultExpanded:c=!0,hasPermission:d,t:u}){const[m,p]=y.useState(c),[f,g]=y.useState(!1),v=t.children.length>0,b=t.project_id||t.archive_id,x=t.is_external;return r.jsxs("div",{children:[r.jsxs("div",{className:`group flex items-center gap-1 px-2 py-1.5 rounded cursor-pointer transition-colors ${e===t.id?"bg-bambu-green/20 text-bambu-green":"hover:bg-bambu-dark text-white"}`,style:{paddingLeft:`${8+o*12}px`},onClick:()=>a(t.id),children:[v?r.jsx("button",{onClick:S=>{S.stopPropagation(),p(!m)},className:"p-0.5 hover:bg-bambu-dark-tertiary rounded",children:r.jsx(Vn,{className:`w-3.5 h-3.5 transition-transform ${m?"rotate-90":""}`})}):r.jsx("div",{className:"w-4.5"}),x?r.jsx(ow,{className:"w-4 h-4 text-purple-400 flex-shrink-0"}):r.jsx(Fl,{className:"w-4 h-4 text-bambu-green flex-shrink-0"}),r.jsx("span",{className:`text-sm flex-1 min-w-0 ${l?"break-all":"truncate"}`,title:t.name,children:t.name}),b&&r.jsxs("button",{onClick:S=>{S.stopPropagation(),i(t)},className:"flex-shrink-0 flex items-center gap-1 text-xs px-1.5 py-0.5 rounded bg-blue-500/20 text-blue-400 hover:bg-blue-500/30 transition-colors",title:`${t.project_name?`Project: ${t.project_name}`:`Archive: ${t.archive_name}`} (click to change)`,children:[r.jsx(Oh,{className:"w-3 h-3"}),t.project_name?r.jsx(rJ,{className:"w-3 h-3"}):r.jsx(ro,{className:"w-3 h-3"})]}),x&&t.external_readonly&&r.jsx("span",{title:u("fileManager.readOnly"),children:r.jsx(mc,{className:"w-3 h-3 text-amber-400 flex-shrink-0"})}),t.file_count>0&&r.jsx("span",{className:"flex-shrink-0 text-xs text-bambu-gray",children:t.file_count}),!b&&!x&&r.jsx("button",{onClick:S=>{S.stopPropagation(),i(t)},className:"flex-shrink-0 p-1 rounded hover:bg-bambu-dark-tertiary",title:u("fileManager.linkToProjectOrArchive"),children:r.jsx(Oh,{className:"w-3.5 h-3.5 text-bambu-gray hover:text-bambu-green"})}),r.jsx("div",{className:`flex-shrink-0 flex items-center gap-0.5 transition-opacity ${l?"":"opacity-0 group-hover:opacity-100"}`,onClick:S=>S.stopPropagation(),children:r.jsxs("div",{className:"relative",children:[r.jsx("button",{onClick:()=>g(!f),className:"p-1 rounded hover:bg-bambu-dark-tertiary",children:r.jsx(Cm,{className:"w-3.5 h-3.5 text-bambu-gray"})}),f&&r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>g(!1)}),r.jsxs("div",{className:"absolute right-0 top-full mt-1 z-20 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl py-1 min-w-[120px]",children:[r.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${d("library:update_all")?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{d("library:update_all")&&(s(t),g(!1))},disabled:!d("library:update_all"),title:d("library:update_all")?void 0:u("fileManager.noPermissionRenameFolder"),children:[r.jsx(ci,{className:"w-3.5 h-3.5"}),u("common.rename")]}),r.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${d("library:update_all")?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{d("library:update_all")&&(i(t),g(!1))},disabled:!d("library:update_all"),title:d("library:update_all")?void 0:u("fileManager.noPermissionLinkFolder"),children:[r.jsx(Oh,{className:"w-3.5 h-3.5"}),u(b?"fileManager.changeLink":"fileManager.linkTo")]}),r.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${d("library:delete_all")?"text-red-400 hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{d("library:delete_all")&&(n(t.id),g(!1))},disabled:!d("library:delete_all"),title:d("library:delete_all")?void 0:u("fileManager.noPermissionDeleteFolder"),children:[r.jsx(na,{className:"w-3.5 h-3.5"}),u("common.delete")]})]})]})]})})]}),v&&m&&r.jsx("div",{children:t.children.map(S=>r.jsx(jde,{folder:S,selectedFolderId:e,onSelect:a,onDelete:n,onLink:i,onRename:s,depth:o+1,wrapNames:l,defaultExpanded:c,hasPermission:d,t:u},S.id))})]})}function Fw(t){const e=t.toLowerCase();return e.endsWith(".gcode")||e.endsWith(".gcode.3mf")}function gI(t){const e=t.toLowerCase();return e.endsWith(".gcode")||e.endsWith(".gcode.3mf")?!1:e.endsWith(".stl")||e.endsWith(".3mf")||e.endsWith(".step")||e.endsWith(".stp")}function Bst({file:t,isSelected:e,isMobile:a,onSelect:n,onDelete:i,onDownload:s,onAddToQueue:o,onPrint:l,onSlice:c,useSlicerApi:d,onPreview3d:u,onRename:m,onGenerateThumbnail:p,thumbnailVersion:f,hasPermission:g,canModify:v,authEnabled:b,t:x}){const[S,k]=y.useState(!1);return r.jsxs("div",{className:`group relative bg-bambu-dark-secondary rounded-lg border transition-all cursor-pointer overflow-hidden ${e?"border-bambu-green ring-1 ring-bambu-green":"border-bambu-dark-tertiary hover:border-bambu-green/50"}`,onClick:()=>n(t.id),children:[r.jsxs("div",{className:"aspect-square bg-bambu-dark flex items-center justify-center overflow-hidden",children:[t.thumbnail_path?r.jsx("img",{src:`${ne.getLibraryFileThumbnailUrl(t.id)}${f?(ne.getLibraryFileThumbnailUrl(t.id).includes("?")?"&":"?")+`v=${f}`:""}`,alt:t.filename,className:"w-full h-full object-cover"}):r.jsx(Rh,{className:"w-12 h-12 text-bambu-gray/30"}),r.jsx("div",{className:`absolute top-2 right-2 text-xs px-1.5 py-0.5 rounded font-medium ${t.file_type==="3mf"?"bg-bambu-green/90 text-white":t.file_type==="gcode"||t.file_type==="gcode.3mf"?"bg-blue-500/90 text-white":t.file_type==="stl"?"bg-purple-500/90 text-white":"bg-bambu-gray/90 text-white"}`,children:t.file_type.toUpperCase()})]}),r.jsxs("div",{className:"p-3",children:[r.jsx("h3",{className:"text-sm font-medium text-white truncate",title:t.print_name||t.filename,children:t.print_name||t.filename}),r.jsxs("div",{className:"flex items-center gap-3 mt-1 text-xs text-bambu-gray",children:[r.jsx("span",{children:cs(t.file_size)}),t.print_time_seconds&&r.jsxs("span",{className:"flex items-center gap-1",children:[r.jsx(ar,{className:"w-3 h-3"}),ds(t.print_time_seconds)]})]}),t.sliced_for_model&&r.jsxs("div",{className:"mt-1 text-xs text-bambu-gray flex items-center gap-1",children:[r.jsx(xr,{className:"w-3 h-3"}),t.sliced_for_model]}),t.print_count>0&&r.jsx("div",{className:"mt-1 text-xs text-bambu-green",children:x("fileManager.printedCount",{count:t.print_count})}),b&&t.created_by_username&&r.jsxs("div",{className:"mt-1 text-xs text-bambu-gray flex items-center gap-1",children:[r.jsx(Zm,{className:"w-3 h-3"}),t.created_by_username]})]}),r.jsxs("div",{className:`absolute bottom-2 right-2 transition-opacity ${a?"opacity-100":"opacity-0 group-hover:opacity-100"}`,onClick:P=>P.stopPropagation(),children:[r.jsx("button",{onClick:()=>k(!S),className:"p-1.5 rounded bg-bambu-dark-secondary/90 hover:bg-bambu-dark-tertiary",children:r.jsx(Cm,{className:"w-4 h-4 text-bambu-gray"})}),S&&r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>k(!1)}),r.jsxs("div",{className:"absolute right-0 bottom-8 z-20 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl py-1 min-w-[140px]",children:[l&&Fw(t.filename)&&r.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${g("printers:control")?"text-bambu-green hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{g("printers:control")&&(l(t),k(!1))},disabled:!g("printers:control"),title:g("printers:control")?void 0:x("fileManager.noPermissionPrint"),children:[r.jsx(xr,{className:"w-3.5 h-3.5"}),x("common.print")]}),o&&Fw(t.filename)&&r.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${g("queue:create")?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{g("queue:create")&&(o(t.id),k(!1))},disabled:!g("queue:create"),title:g("queue:create")?void 0:x("fileManager.noPermissionAddToQueue"),children:[r.jsx(ar,{className:"w-3.5 h-3.5"}),x("fileManager.schedulePrint")]}),c&&d&&gI(t.filename)&&r.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${g("library:upload")?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{g("library:upload")&&(c(t),k(!1))},disabled:!g("library:upload"),title:g("library:upload")?void 0:x("fileManager.noPermissionSlice"),children:[r.jsx(bd,{className:"w-3.5 h-3.5"}),x("slice.action")]}),u&&(t.file_type==="3mf"||t.file_type==="gcode"||t.file_type==="stl"||t.file_type==="gcode.3mf")&&r.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${g("library:read")?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{g("library:read")&&(u(t),k(!1))},disabled:!g("library:read"),title:g("library:read")?void 0:"You do not have permission to preview files",children:[r.jsx(Ei,{className:"w-3.5 h-3.5"}),"3D Preview"]}),r.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${g("library:read")?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{g("library:read")&&(s(t.id),k(!1))},disabled:!g("library:read"),title:g("library:read")?void 0:x("fileManager.noPermissionDownload"),children:[r.jsx(Ur,{className:"w-3.5 h-3.5"}),x("common.download")]}),m&&r.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${v("library","update",t.created_by_id)?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{v("library","update",t.created_by_id)&&(m(t),k(!1))},disabled:!v("library","update",t.created_by_id),title:v("library","update",t.created_by_id)?void 0:x("fileManager.noPermissionRenameFile"),children:[r.jsx(ci,{className:"w-3.5 h-3.5"}),x("common.rename")]}),p&&t.file_type==="stl"&&r.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${v("library","update",t.created_by_id)?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{v("library","update",t.created_by_id)&&(p(t),k(!1))},disabled:!v("library","update",t.created_by_id),title:v("library","update",t.created_by_id)?void 0:x("fileManager.noPermissionGenerateThumbnail"),children:[r.jsx(gu,{className:"w-3.5 h-3.5"}),x("fileManager.generateThumbnail")]}),r.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${v("library","delete",t.created_by_id)?"text-red-400 hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{v("library","delete",t.created_by_id)&&(i(t.id),k(!1))},disabled:!v("library","delete",t.created_by_id),title:v("library","delete",t.created_by_id)?void 0:x("fileManager.noPermissionDeleteFile"),children:[r.jsx(na,{className:"w-3.5 h-3.5"}),x("common.delete")]})]})]})]}),r.jsx("div",{className:`absolute top-2 left-2 w-5 h-5 rounded border-2 flex items-center justify-center transition-all ${e?"bg-bambu-green border-bambu-green":`border-white/30 bg-black/30 ${a?"opacity-100":"opacity-0 group-hover:opacity-100"}`}`,children:e&&r.jsx("div",{className:"w-2 h-2 bg-white rounded-sm"})})]})}function Ust(){const{t}=wt(),e=ia(),{showToast:a}=da(),{hasPermission:n,hasAnyPermission:i,canModify:s,authEnabled:o}=lr(),[l]=mb(),c=Ii(),d=l.get("folder"),u=d?parseInt(d,10):null,[m,p]=y.useState(u),[f,g]=y.useState("internal"),[v,b]=y.useState([]),[x,S]=y.useState(!1),[k,P]=y.useState(!1),[N,T]=y.useState(!1),[j,D]=y.useState(!1),[C,E]=y.useState(!1),[R,I]=y.useState(null),[O,z]=y.useState(null),[X,ae]=y.useState(null),[Y,ce]=y.useState(null),[de,oe]=y.useState(null),[K,ie]=y.useState(null),[ue,he]=y.useState(null),[ge,q]=y.useState({}),[Q,A]=y.useState(null),[F,B]=y.useState(()=>localStorage.getItem("library-view-mode")||"grid"),[W,H]=y.useState(()=>localStorage.getItem("library-wrap-folders")==="true"),[le,U]=y.useState(()=>localStorage.getItem("library-collapse-folders")==="true"),[G,Z]=y.useState(()=>{const Ae=localStorage.getItem("library-sidebar-width");return Ae?parseInt(Ae,10):256}),[J,re]=y.useState(!1),se=y.useRef(null);y.useEffect(()=>{if(!J)return;document.body.style.userSelect="none",document.body.style.cursor="col-resize";const Ae=ct=>{if(!se.current)return;const Ne=se.current.parentElement?.getBoundingClientRect();if(!Ne)return;const We=ct.clientX-Ne.left,st=Math.min(500,Math.max(200,We));Z(st)},we=()=>{re(!1),document.body.style.userSelect="",document.body.style.cursor="",localStorage.setItem("library-sidebar-width",String(G))};return document.addEventListener("mousemove",Ae),document.addEventListener("mouseup",we),()=>{document.removeEventListener("mousemove",Ae),document.removeEventListener("mouseup",we),document.body.style.userSelect="",document.body.style.cursor=""}},[J,G]);const[fe,me]=y.useState(""),[pe,V]=y.useState("all"),[L,te]=y.useState(""),[be,xe]=y.useState(()=>localStorage.getItem("library-sort-field")||"name"),[ve,De]=y.useState(()=>localStorage.getItem("library-sort-direction")||"asc"),je=Use();y.useEffect(()=>{const Ae=l.get("folder");if(Ae){const we=parseInt(Ae,10);p(we)}},[l]);const{data:Te}=$e({queryKey:["settings"],queryFn:()=>ne.getSettings()}),{data:qe,isLoading:Pe}=$e({queryKey:["library-folders"],queryFn:()=>ne.getLibraryFolders()}),{data:Ie}=$e({queryKey:["library-trash-count"],queryFn:async()=>{try{return(await ne.listLibraryTrash(1,0)).total}catch{return 0}},staleTime:3e4}),{data:Re,isLoading:Ue}=$e({queryKey:["library-files",m,f],queryFn:()=>ne.getLibraryFiles(m,!1,void 0,m===null?f:void 0)}),{data:ze}=$e({queryKey:["library-stats"],queryFn:()=>ne.getLibraryStats()}),{data:it}=$e({queryKey:["users"],queryFn:()=>ne.getUsers()}),Oe=y.useMemo(()=>{if(!Re)return[];const Ae=new Set(Re.map(we=>we.file_type));return Array.from(Ae).sort()},[Re]),tt=y.useMemo(()=>{if(!Re)return[];let Ae=[...Re];if(fe.trim()){const we=fe.toLowerCase();Ae=Ae.filter(ct=>ct.filename.toLowerCase().includes(we)||ct.print_name&&ct.print_name.toLowerCase().includes(we))}if(pe!=="all"&&(Ae=Ae.filter(we=>we.file_type===pe)),L.trim()){const we=L.toLowerCase();Ae=Ae.filter(ct=>ct.created_by_username&&ct.created_by_username.toLowerCase().includes(we))}return Ae.sort((we,ct)=>{let Ne=0;switch(be){case"name":Ne=(we.print_name||we.filename).localeCompare(ct.print_name||ct.filename);break;case"date":Ne=(Ga(we.created_at)?.getTime()??0)-(Ga(ct.created_at)?.getTime()??0);break;case"size":Ne=we.file_size-ct.file_size;break;case"type":Ne=we.file_type.localeCompare(ct.file_type);break;case"prints":Ne=we.print_count-ct.print_count;break}return ve==="asc"?Ne:-Ne}),Ae},[Re,fe,pe,L,be,ve]),Fe=y.useMemo(()=>{if(!ze||!Te)return!1;const Ae=(Te.library_disk_warning_gb||5)*1024*1024*1024;return ze.disk_free_bytesne.createLibraryFolder(Ae),onSuccess:()=>{e.invalidateQueries({queryKey:["library-folders"]}),S(!1),a(t("fileManager.toast.folderCreated"),"success")},onError:Ae=>a(Ae.message,"error")}),Ve=rt({mutationFn:async Ae=>{const we=await ne.createExternalFolder(Ae);return await ne.scanExternalFolder(we.id),we},onSuccess:Ae=>{e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-stats"]}),P(!1),p(Ae.id),a(t("fileManager.toast.externalFolderLinked"),"success")},onError:Ae=>a(Ae.message,"error")}),Me=rt({mutationFn:Ae=>ne.scanExternalFolder(Ae),onSuccess:Ae=>{e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-stats"]}),a(t("fileManager.toast.folderScanned",{added:Ae.added,removed:Ae.removed}),"success")},onError:Ae=>a(Ae.message,"error")}),Be=rt({mutationFn:Ae=>ne.deleteLibraryFolder(Ae),onSuccess:()=>{e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-stats"]}),m===O?.id&&p(null),z(null),a(t("fileManager.toast.folderDeleted"),"success")},onError:Ae=>{z(null),a(Ae.message,"error")}}),Qe=rt({mutationFn:Ae=>ne.deleteLibraryFile(Ae),onSuccess:()=>{e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-stats"]}),e.invalidateQueries({queryKey:["library-trash-count"]}),b(Ae=>Ae.filter(we=>we!==O?.id)),z(null),a(t("fileManager.toast.fileDeleted"),"success")},onError:Ae=>{z(null),a(Ae.message,"error")}}),Ge=rt({mutationFn:Ae=>ne.bulkDeleteLibrary(Ae,[]),onSuccess:(Ae,we)=>{e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-stats"]}),e.invalidateQueries({queryKey:["library-trash-count"]}),a(t("fileManager.toast.filesDeleted",{count:we.length}),"success"),b([]),z(null)},onError:Ae=>{z(null),a(Ae.message,"error")}}),Ee=rt({mutationFn:({fileIds:Ae,folderId:we})=>ne.moveLibraryFiles(Ae,we),onSuccess:()=>{e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-folders"]}),b([]),T(!1),a(t("fileManager.toast.filesMoved"),"success")},onError:Ae=>a(Ae.message,"error")}),at=rt({mutationFn:({id:Ae,data:we})=>ne.updateLibraryFolder(Ae,we),onSuccess:(Ae,we)=>{e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["project-folders"]}),e.invalidateQueries({queryKey:["archive-folders"]}),I(null);const ct=we.data.project_id===0&&we.data.archive_id===0;a(t(ct?"fileManager.toast.folderUnlinked":"fileManager.toast.folderLinked"),"success")},onError:Ae=>a(Ae.message,"error")}),Xe=rt({mutationFn:({id:Ae,filename:we})=>ne.updateLibraryFile(Ae,{filename:we}),onSuccess:()=>{e.invalidateQueries({queryKey:["library-files"]}),he(null),a(t("fileManager.toast.fileRenamed"),"success")},onError:Ae=>{he(null),a(Ae.message,"error")}}),Nt=rt({mutationFn:({id:Ae,name:we})=>ne.updateLibraryFolder(Ae,{name:we}),onSuccess:()=>{e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-files"]}),he(null),a(t("fileManager.toast.folderRenamed"),"success")},onError:Ae=>{he(null),a(Ae.message,"error")}}),Vt=rt({mutationFn:()=>ne.batchGenerateStlThumbnails({all_missing:!0}),onSuccess:Ae=>{if(e.invalidateQueries({queryKey:["library-files"]}),Ae.succeeded>0){const we=Date.now(),ct={};Ae.results.forEach(Ne=>{Ne.success&&(ct[Ne.file_id]=we)}),q(Ne=>({...Ne,...ct}))}Ae.succeeded>0&&Ae.failed===0?a(t("fileManager.toast.thumbnailsGenerated",{count:Ae.succeeded}),"success"):Ae.succeeded>0&&Ae.failed>0?a(t("fileManager.toast.thumbnailsGeneratedPartial",{succeeded:Ae.succeeded,failed:Ae.failed}),"success"):Ae.processed===0?a(t("fileManager.toast.noStlMissingThumbnails"),"info"):a(t("fileManager.toast.failedToGenerateThumbnails",{error:Ae.results[0]?.error||"Unknown error"}),"error")},onError:Ae=>a(Ae.message,"error")}),ht=rt({mutationFn:Ae=>ne.batchGenerateStlThumbnails({file_ids:[Ae]}),onSuccess:Ae=>{if(e.invalidateQueries({queryKey:["library-files"]}),Ae.succeeded>0){const we=Ae.results[0]?.file_id;we&&q(ct=>({...ct,[we]:Date.now()})),a(t("fileManager.toast.thumbnailGenerated"),"success")}else a(t("fileManager.toast.failedToGenerateThumbnail",{error:Ae.results[0]?.error||"Unknown error"}),"error")},onError:Ae=>a(Ae.message,"error")}),It=y.useCallback(Ae=>{const we=Ae.toLowerCase();return we.endsWith(".gcode")||we.includes(".gcode.")},[]),Xt=y.useMemo(()=>Re?Re.filter(Ae=>v.includes(Ae.id)&&It(Ae.filename)):[],[Re,v,It]),oa=y.useCallback(Ae=>{b(we=>we.includes(Ae)?we.filter(ct=>ct!==Ae):[...we,Ae])},[]),la=y.useCallback(()=>{tt.length>0&&b(tt.map(Ae=>Ae.id))},[tt]),ot=y.useCallback(()=>{b([])},[]),vt=()=>{e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-stats"]})},Pt=Ae=>{ne.downloadLibraryFile(Ae).catch(we=>{console.error("Library file download failed:",we)})},ea=()=>{O&&(O.type==="file"?Qe.mutate(O.id):O.type==="folder"?Be.mutate(O.id):O.type==="bulk"&&Ge.mutate(v))},aa=Be.isPending||Qe.isPending||Ge.isPending,Ce=Ae=>{B(Ae),localStorage.setItem("library-view-mode",Ae)},Ke=Pe||Ue,nt=y.useMemo(()=>{if(!m||!qe)return null;const Ae=we=>{for(const ct of we){if(ct.id===m)return ct;const Ne=Ae(ct.children);if(Ne)return Ne}return null};return Ae(qe)},[m,qe]);return r.jsxs("div",{className:"p-4 md:p-8 min-h-[calc(100vh-64px)] lg:h-[calc(100vh-64px)] flex flex-col",children:[r.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4 mb-6",children:[r.jsxs("div",{children:[r.jsxs("h1",{className:"text-2xl font-bold text-white flex items-center gap-3",children:[r.jsx(Fl,{className:"w-7 h-7 text-bambu-green"}),t("fileManager.title")]}),r.jsx("p",{className:"text-bambu-gray mt-1",children:t("fileManager.subtitle")})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsxs("div",{className:"flex items-center bg-bambu-dark rounded-lg p-1",children:[r.jsx("button",{onClick:()=>Ce("grid"),className:`p-1.5 rounded transition-colors ${F==="grid"?"bg-bambu-dark-secondary text-white":"text-bambu-gray hover:text-white"}`,title:t("fileManager.gridView"),children:r.jsx(OS,{className:"w-4 h-4"})}),r.jsx("button",{onClick:()=>Ce("list"),className:`p-1.5 rounded transition-colors ${F==="list"?"bg-bambu-dark-secondary text-white":"text-bambu-gray hover:text-white"}`,title:t("fileManager.listView"),children:r.jsx(BS,{className:"w-4 h-4"})})]}),r.jsxs(Le,{variant:"secondary",onClick:()=>Vt.mutate(),disabled:Vt.isPending||!i("library:update_own","library:update_all"),title:i("library:update_own","library:update_all")?t("fileManager.generateThumbnailsForMissing"):t("fileManager.noPermissionGenerateThumbnail"),children:[Vt.isPending?r.jsx(lt,{className:"w-4 h-4 mr-2 animate-spin"}):r.jsx(gu,{className:"w-4 h-4 mr-2"}),t("fileManager.generateThumbnails")]}),r.jsxs(Le,{variant:"secondary",onClick:()=>P(!0),disabled:!n("library:upload"),title:n("library:upload")?t("fileManager.linkExternalFolder"):t("fileManager.noPermissionCreateFolder"),children:[r.jsx(ow,{className:"w-4 h-4 mr-2"}),t("fileManager.linkExternal")]}),r.jsxs(Le,{variant:"secondary",onClick:()=>S(!0),disabled:!n("library:upload"),title:n("library:upload")?void 0:t("fileManager.noPermissionCreateFolder"),children:[r.jsx(nxe,{className:"w-4 h-4 mr-2"}),t("fileManager.newFolder")]}),n("library:purge")&&r.jsxs(Le,{variant:"secondary",onClick:()=>E(!0),title:t("libraryPurge.headerTooltip"),children:[r.jsx(na,{className:"w-4 h-4 mr-2"}),t("libraryPurge.headerButton")]}),i("library:delete_own","library:delete_all")&&r.jsxs(Ls,{to:"/files/trash",className:"inline-flex items-center px-3 py-1.5 text-sm rounded bg-bambu-dark-secondary text-bambu-gray hover:text-white hover:bg-bambu-dark transition-colors",title:t("libraryTrash.headerTooltip"),children:[r.jsx(na,{className:"w-4 h-4 mr-2"}),t("libraryTrash.headerButton"),typeof Ie=="number"&&Ie>0&&r.jsx("span",{className:"ml-1.5 px-1.5 py-0.5 text-xs rounded-full bg-bambu-green/20 text-bambu-green",children:Ie})]}),r.jsxs(Le,{onClick:()=>D(!0),disabled:!n("library:upload"),title:n("library:upload")?void 0:t("fileManager.noPermissionUpload"),children:[r.jsx(Sn,{className:"w-4 h-4 mr-2"}),t("common.upload")]})]})]}),Fe&&ze&&Te&&r.jsxs("div",{className:"flex items-center gap-3 mb-4 p-3 bg-amber-500/10 border border-amber-500/30 rounded-lg",children:[r.jsx(xa,{className:"w-5 h-5 text-amber-500 flex-shrink-0"}),r.jsxs("div",{className:"flex-1",children:[r.jsx("p",{className:"text-sm text-amber-500 font-medium",children:t("fileManager.lowDiskSpaceWarning")}),r.jsx("p",{className:"text-xs text-amber-500/80",children:t("fileManager.lowDiskSpaceDetails",{free:cs(ze.disk_free_bytes),total:cs(ze.disk_total_bytes),threshold:Te.library_disk_warning_gb})})]})]}),ze&&r.jsxs("div",{className:"flex flex-wrap items-center gap-3 sm:gap-6 mb-6 p-3 bg-bambu-dark-secondary rounded-lg border border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[r.jsx(FT,{className:"w-4 h-4 text-bambu-green"}),r.jsxs("span",{className:"text-bambu-gray",children:[t("fileManager.files"),":"]}),r.jsx("span",{className:"text-white font-medium",children:ze.total_files})]}),r.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[r.jsx(Fl,{className:"w-4 h-4 text-blue-400"}),r.jsxs("span",{className:"text-bambu-gray",children:[t("fileManager.folders"),":"]}),r.jsx("span",{className:"text-white font-medium",children:ze.total_folders})]}),r.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[r.jsx(hb,{className:"w-4 h-4 text-amber-400"}),r.jsxs("span",{className:"text-bambu-gray",children:[t("fileManager.size"),":"]}),r.jsx("span",{className:"text-white font-medium",children:cs(ze.total_size_bytes)})]}),r.jsxs("div",{className:"flex items-center gap-2 text-sm sm:ml-auto",children:[r.jsxs("span",{className:"text-bambu-gray",children:[t("fileManager.free"),":"]}),r.jsx("span",{className:`font-medium ${Fe?"text-amber-500":"text-white"}`,children:cs(ze.disk_free_bytes)})]})]}),r.jsxs("div",{className:"flex-1 flex flex-col lg:flex-row gap-4 lg:gap-6 min-h-0",children:[r.jsx("div",{className:"lg:hidden",children:r.jsxs("select",{value:m!==null?String(m):`__top:${f}`,onChange:Ae=>{const we=Ae.target.value;we.startsWith("__top:")?(p(null),g(we.slice(6))):p(parseInt(we,10))},className:"w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg px-3 py-2.5 text-white focus:outline-none focus:border-bambu-green",children:[r.jsxs("option",{value:"__top:internal",children:["📁 ",t("fileManager.allFiles")]}),qe?.some(Ae=>Ae.is_external)&&r.jsxs("option",{value:"__top:external",children:["🔗 ",t("fileManager.allExternal")]}),qe&&(()=>{const Ae=(we,ct=0)=>{const Ne=[];for(const We of we)Ne.push({id:We.id,name:We.name,fileCount:We.file_count,depth:ct}),We.children.length>0&&Ne.push(...Ae(We.children,ct+1));return Ne};return Ae(qe).map(we=>r.jsxs("option",{value:we.id,children:["│ ".repeat(we.depth),"📂 ",we.name," ",we.fileCount>0?`(${we.fileCount})`:""]},we.id))})()]})}),r.jsxs("div",{ref:se,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:`${G}px`},children:[r.jsx("div",{className:`absolute right-0 top-0 bottom-0 w-1.5 cursor-col-resize z-10 group/resize flex items-center justify-center transition-colors ${J?"bg-bambu-green":"hover:bg-bambu-green/50"}`,onMouseDown:Ae=>{Ae.preventDefault(),re(!0)},onDoubleClick:()=>{Z(256),localStorage.setItem("library-sidebar-width","256")},title:t("fileManager.dragToResizeTooltip"),children:r.jsxs("div",{className:`flex flex-col gap-1 opacity-0 group-hover/resize:opacity-100 transition-opacity ${J?"opacity-100":""}`,children:[r.jsx("div",{className:"w-0.5 h-0.5 rounded-full bg-white/70"}),r.jsx("div",{className:"w-0.5 h-0.5 rounded-full bg-white/70"}),r.jsx("div",{className:"w-0.5 h-0.5 rounded-full bg-white/70"})]})}),r.jsxs("div",{className:"p-3 border-b border-bambu-dark-tertiary flex items-center justify-between",children:[r.jsx("h2",{className:"text-sm font-medium text-white",children:t("fileManager.folders")}),r.jsxs("div",{className:"flex items-center gap-1",children:[r.jsx("button",{onClick:()=>{const Ae=!le;U(Ae),localStorage.setItem("library-collapse-folders",String(Ae))},className:`text-xs px-1.5 py-0.5 rounded transition-colors ${le?"bg-bambu-green/20 text-bambu-green":"text-bambu-gray hover:text-white hover:bg-bambu-dark"}`,title:t(le?"fileManager.expandFoldersByDefault":"fileManager.collapseFoldersByDefault"),children:t("fileManager.collapse")}),r.jsx("button",{onClick:()=>{const Ae=!W;H(Ae),localStorage.setItem("library-wrap-folders",String(Ae))},className:`text-xs px-1.5 py-0.5 rounded transition-colors ${W?"bg-bambu-green/20 text-bambu-green":"text-bambu-gray hover:text-white hover:bg-bambu-dark"}`,title:t(W?"fileManager.disableTextWrapping":"fileManager.enableTextWrapping"),children:t("fileManager.wrap")})]})]}),r.jsxs("div",{className:"flex-1 overflow-y-auto p-2",children:[r.jsxs("div",{className:`flex items-center gap-2 px-2 py-1.5 rounded cursor-pointer transition-colors ${m===null&&f==="internal"?"bg-bambu-green/20 text-bambu-green":"hover:bg-bambu-dark text-white"}`,onClick:()=>{p(null),g("internal")},children:[r.jsx(Rh,{className:"w-4 h-4"}),r.jsx("span",{className:"text-sm",children:t("fileManager.allFiles")})]}),qe?.some(Ae=>Ae.is_external)&&r.jsxs("div",{className:`flex items-center gap-2 px-2 py-1.5 rounded cursor-pointer transition-colors ${m===null&&f==="external"?"bg-bambu-green/20 text-bambu-green":"hover:bg-bambu-dark text-white"}`,onClick:()=>{p(null),g("external")},children:[r.jsx(ow,{className:"w-4 h-4 text-purple-400"}),r.jsx("span",{className:"text-sm",children:t("fileManager.allExternal")})]}),qe?.map(Ae=>r.jsx(jde,{folder:Ae,selectedFolderId:m,onSelect:p,onDelete:we=>z({type:"folder",id:we}),onLink:I,onRename:we=>he({type:"folder",id:we.id,name:we.name}),wrapNames:W,defaultExpanded:!le,hasPermission:n,t},`${Ae.id}-${le?"c":"e"}`))]})]}),r.jsxs("div",{className:"flex-1 flex flex-col min-w-0 min-h-0",children:[nt?.is_external&&r.jsxs("div",{className:"flex items-center gap-3 mb-4 p-3 bg-purple-500/10 border border-purple-500/30 rounded-lg",children:[r.jsx(ow,{className:"w-5 h-5 text-purple-400 flex-shrink-0"}),r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("span",{className:"text-sm font-medium text-purple-300",children:t("fileManager.externalFolder")}),nt.external_readonly&&r.jsxs("span",{className:"text-xs px-1.5 py-0.5 rounded bg-amber-500/20 text-amber-400 flex items-center gap-1",children:[r.jsx(mc,{className:"w-3 h-3"}),t("fileManager.readOnly")]})]}),r.jsx("p",{className:"text-xs text-bambu-gray truncate font-mono",title:nt.external_path||"",children:nt.external_path})]}),r.jsxs(Le,{variant:"secondary",size:"sm",onClick:()=>m&&Me.mutate(m),disabled:Me.isPending,title:t("fileManager.scanFolder"),children:[Me.isPending?r.jsx(lt,{className:"w-4 h-4 animate-spin"}):r.jsx(tr,{className:"w-4 h-4"}),r.jsx("span",{className:"ml-1.5",children:t("fileManager.scanFolder")})]})]}),Re&&Re.length>0&&r.jsxs("div",{className:"flex flex-wrap items-center gap-2 sm:gap-3 mb-4 p-2 sm:p-3 bg-bambu-dark-secondary rounded-lg border border-bambu-dark-tertiary sticky top-0 z-10 lg:static",children:[r.jsxs("div",{className:"relative w-full sm:w-auto sm:flex-1 sm:max-w-xs",children:[r.jsx(br,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),r.jsx("input",{type:"text",placeholder:t("fileManager.searchFiles"),value:fe,onChange:Ae=>me(Ae.target.value),className:"w-full pl-9 pr-3 py-1.5 bg-bambu-dark border border-bambu-dark-tertiary rounded text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green"})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(av,{className:"w-4 h-4 text-bambu-gray hidden sm:block"}),r.jsxs("select",{value:pe,onChange:Ae=>V(Ae.target.value),className:"bg-bambu-dark border border-bambu-dark-tertiary rounded px-2 py-1.5 text-sm text-white focus:outline-none focus:border-bambu-green",children:[r.jsx("option",{value:"all",children:t("fileManager.allTypes")}),Oe.map(Ae=>r.jsx("option",{value:Ae,children:Ae.toUpperCase()},Ae))]})]}),o&&r.jsxs("div",{className:"relative",children:[r.jsx("input",{type:"text",placeholder:t("fileManager.filterByUser",{defaultValue:"Filter by user"}),value:L,onChange:Ae=>te(Ae.target.value),list:"usernames-list",className:`w-32 sm:w-40 px-2 py-1.5 bg-bambu-dark border border-bambu-dark-tertiary rounded text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green ${L?"pr-7":""}`,style:L?{WebkitAppearance:"none",MozAppearance:"textfield"}:void 0}),L&&r.jsx("button",{onClick:()=>te(""),className:"absolute right-2 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white z-10",children:r.jsx(Ht,{className:"w-3 h-3"})}),r.jsx("datalist",{id:"usernames-list",children:it?.map(Ae=>r.jsx("option",{value:Ae.username},Ae.id))})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsxs("select",{value:be,onChange:Ae=>{const we=Ae.target.value;xe(we),localStorage.setItem("library-sort-field",we)},className:"bg-bambu-dark border border-bambu-dark-tertiary rounded px-2 py-1.5 text-sm text-white focus:outline-none focus:border-bambu-green",children:[r.jsx("option",{value:"name",children:t("common.name")}),r.jsx("option",{value:"date",children:t("common.date")}),r.jsx("option",{value:"size",children:t("fileManager.size")}),r.jsx("option",{value:"type",children:t("common.type")}),r.jsx("option",{value:"prints",children:t("fileManager.prints")})]}),r.jsx("button",{onClick:()=>De(Ae=>{const we=Ae==="asc"?"desc":"asc";return localStorage.setItem("library-sort-direction",we),we}),className:"p-1.5 rounded bg-bambu-dark border border-bambu-dark-tertiary hover:border-bambu-green transition-colors",title:t(ve==="asc"?"fileManager.ascending":"fileManager.descending"),children:ve==="asc"?r.jsx(sge,{className:"w-4 h-4 text-white"}):r.jsx(Jfe,{className:"w-4 h-4 text-white"})})]}),(fe||pe!=="all"||L)&&r.jsx("span",{className:"text-sm text-bambu-gray hidden sm:inline",children:t("fileManager.resultsCount",{showing:tt.length,total:Re.length})})]}),tt.length>0&&r.jsxs("div",{className:"flex flex-wrap items-center gap-2 mb-4 p-2 bg-bambu-dark-secondary rounded-lg border border-bambu-dark-tertiary sticky top-[52px] z-10 lg:static",children:[v.length===tt.length&&v.length>0?r.jsxs(Le,{variant:"secondary",size:"sm",onClick:ot,children:[r.jsx(so,{className:"w-4 h-4 sm:mr-1"}),r.jsx("span",{className:"hidden sm:inline",children:t("fileManager.deselectAll")})]}):r.jsxs(Le,{variant:"secondary",size:"sm",onClick:la,children:[r.jsx(xs,{className:"w-4 h-4 sm:mr-1"}),r.jsx("span",{className:"hidden sm:inline",children:t("fileManager.selectAll")})]}),v.length>0&&r.jsxs(r.Fragment,{children:[r.jsx("span",{className:"text-sm text-bambu-gray ml-2",children:t("fileManager.selected",{count:v.length})}),r.jsx("div",{className:"hidden sm:block flex-1"}),r.jsxs("div",{className:"w-full sm:w-auto flex flex-wrap items-center gap-2 mt-2 sm:mt-0",children:[Xt.length===1&&r.jsxs(Le,{variant:"primary",size:"sm",onClick:()=>ce(Xt[0]),disabled:!n("printers:control"),title:n("printers:control")?void 0:t("fileManager.noPermissionPrint"),children:[r.jsx(gs,{className:"w-4 h-4 sm:mr-1"}),r.jsx("span",{className:"hidden sm:inline",children:t("common.print")})]}),Xt.length===1&&r.jsxs(Le,{variant:"secondary",size:"sm",onClick:()=>oe(Xt[0]),disabled:!n("queue:create"),title:n("queue:create")?void 0:t("fileManager.noPermissionAddToQueue"),children:[r.jsx(ar,{className:"w-4 h-4 sm:mr-1"}),r.jsx("span",{className:"hidden sm:inline",children:t("fileManager.schedulePrint")})]}),r.jsxs(Le,{variant:"secondary",size:"sm",onClick:()=>T(!0),disabled:!i("library:update_own","library:update_all"),title:i("library:update_own","library:update_all")?void 0:t("fileManager.noPermissionMoveFiles"),children:[r.jsx(vye,{className:"w-4 h-4 sm:mr-1"}),r.jsx("span",{className:"hidden sm:inline",children:t("common.move")})]}),r.jsxs(Le,{variant:"danger",size:"sm",onClick:()=>{v.length===1?z({type:"file",id:v[0]}):z({type:"bulk",id:0,count:v.length})},disabled:!i("library:delete_own","library:delete_all"),title:i("library:delete_own","library:delete_all")?void 0:t("fileManager.noPermissionDeleteFiles"),children:[r.jsx(na,{className:"w-4 h-4 sm:mr-1"}),r.jsx("span",{className:"hidden sm:inline",children:t("common.delete")})]}),r.jsxs(Le,{variant:"secondary",size:"sm",onClick:ot,children:[r.jsx(Ht,{className:"w-4 h-4 sm:mr-1"}),r.jsx("span",{className:"hidden sm:inline",children:t("common.clear")})]})]})]})]}),Ke?r.jsx("div",{className:"flex-1 flex items-center justify-center",children:r.jsxs("div",{className:"flex flex-col items-center gap-3",children:[r.jsx(lt,{className:"w-8 h-8 animate-spin text-bambu-green"}),r.jsx("p",{className:"text-sm text-bambu-gray",children:t("fileManager.loadingFiles")})]})}):Re?.length===0?r.jsxs("div",{className:"flex-1 flex flex-col items-center justify-center",children:[r.jsx("div",{className:"p-4 bg-bambu-dark rounded-2xl mb-4",children:r.jsx(Rh,{className:"w-12 h-12 text-bambu-gray/50"})}),r.jsx("h3",{className:"text-lg font-medium text-white mb-2",children:t(m!==null?"fileManager.folderIsEmpty":f==="external"?"fileManager.externalIsEmpty":"fileManager.noFilesYet")}),r.jsx("p",{className:"text-bambu-gray text-center max-w-md mb-6",children:t(m!==null?"fileManager.folderEmptyDescription":f==="external"?"fileManager.externalEmptyDescription":"fileManager.noFilesDescription")}),r.jsxs(Le,{onClick:()=>D(!0),disabled:!n("library:upload"),title:n("library:upload")?void 0:t("fileManager.noPermissionUpload"),children:[r.jsx(or,{className:"w-4 h-4 mr-2"}),t("fileManager.uploadFiles")]})]}):tt.length===0?r.jsxs("div",{className:"flex-1 flex flex-col items-center justify-center",children:[r.jsx("div",{className:"p-4 bg-bambu-dark rounded-2xl mb-4",children:r.jsx(br,{className:"w-12 h-12 text-bambu-gray/50"})}),r.jsx("h3",{className:"text-lg font-medium text-white mb-2",children:t("fileManager.noMatchingFiles")}),r.jsx("p",{className:"text-bambu-gray text-center max-w-md mb-6",children:t("fileManager.noMatchingFilesDescription")}),r.jsx(Le,{variant:"secondary",onClick:()=>{me(""),V("all")},children:t("fileManager.clearFilters")})]}):F==="grid"?r.jsx("div",{className:"flex-1 lg:overflow-y-auto",children:r.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 2xl:grid-cols-6 gap-4",children:tt.map(Ae=>r.jsx(Bst,{file:Ae,isSelected:v.includes(Ae.id),isMobile:je,t,onSelect:oa,onDelete:we=>z({type:"file",id:we}),onDownload:Pt,onAddToQueue:we=>{const ct=Re?.find(Ne=>Ne.id===we);ct&&oe(ct)},onPrint:ae,onSlice:ie,useSlicerApi:Te?.use_slicer_api??!1,onPreview3d:we=>{Fw(we.filename)?c(`/gcode-viewer?library_file=${we.id}`):A(we)},onRename:we=>he({type:"file",id:we.id,name:we.filename}),onGenerateThumbnail:we=>ht.mutate(we.id),thumbnailVersion:ge[Ae.id],hasPermission:n,canModify:s,authEnabled:o},Ae.id))})}):r.jsx("div",{className:"flex-1 lg:overflow-y-auto",children:r.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg border border-bambu-dark-tertiary overflow-x-auto",children:[r.jsxs("div",{className:`hidden sm:grid ${o?"grid-cols-[auto_1fr_120px_100px_100px_100px_min-content]":"grid-cols-[auto_1fr_100px_100px_100px_min-content]"} gap-4 px-4 py-2 bg-bambu-dark-secondary border-b border-bambu-dark-tertiary text-xs text-bambu-gray font-medium`,children:[r.jsx("div",{className:"w-6"}),r.jsx("div",{children:t("common.name")}),o&&r.jsx("div",{children:t("fileManager.uploadedBy",{defaultValue:"Uploaded By"})}),r.jsx("div",{children:t("common.type")}),r.jsx("div",{children:t("fileManager.size")}),r.jsx("div",{children:t("fileManager.prints")}),r.jsx("div",{})]}),tt.map(Ae=>r.jsxs("div",{className:`grid ${o?"grid-cols-[auto_1fr_120px_100px_100px_100px_min-content]":"grid-cols-[auto_1fr_100px_100px_100px_min-content]"} 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 ${v.includes(Ae.id)?"bg-bambu-green/10":""}`,onClick:()=>oa(Ae.id),children:[r.jsx("div",{className:`w-5 h-5 rounded border-2 flex items-center justify-center ${v.includes(Ae.id)?"bg-bambu-green border-bambu-green":"border-bambu-gray/50"}`,children:v.includes(Ae.id)&&r.jsx("div",{className:"w-2 h-2 bg-white rounded-sm"})}),r.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[r.jsxs("div",{className:"relative group/thumb",children:[r.jsx("div",{className:"w-10 h-10 rounded bg-bambu-dark flex-shrink-0 overflow-hidden",children:Ae.thumbnail_path?r.jsx("img",{src:`${ne.getLibraryFileThumbnailUrl(Ae.id)}${ge[Ae.id]?(ne.getLibraryFileThumbnailUrl(Ae.id).includes("?")?"&":"?")+`v=${ge[Ae.id]}`:""}`,alt:"",className:"w-full h-full object-cover"}):r.jsx("div",{className:"w-full h-full flex items-center justify-center",children:r.jsx(Rh,{className:"w-5 h-5 text-bambu-gray/50"})})}),Ae.thumbnail_path&&r.jsx("div",{className:"absolute left-0 top-full mt-2 z-50 hidden group-hover/thumb:block",children:r.jsx("div",{className:"w-48 h-48 rounded-lg bg-bambu-dark-secondary border border-bambu-dark-tertiary shadow-xl overflow-hidden",children:r.jsx("img",{src:`${ne.getLibraryFileThumbnailUrl(Ae.id)}${ge[Ae.id]?(ne.getLibraryFileThumbnailUrl(Ae.id).includes("?")?"&":"?")+`v=${ge[Ae.id]}`:""}`,alt:Ae.filename,className:"w-full h-full object-contain"})})})]}),r.jsx("div",{className:"min-w-0",children:r.jsx("div",{className:"text-sm text-white truncate",children:Ae.print_name||Ae.filename})})]}),o&&r.jsx("div",{className:"text-sm text-bambu-gray flex items-center gap-1",children:Ae.created_by_username?r.jsxs(r.Fragment,{children:[r.jsx(Zm,{className:"w-3 h-3"}),r.jsx("span",{className:"truncate",children:Ae.created_by_username})]}):"-"}),r.jsx("div",{children:r.jsx("span",{className:`text-xs px-1.5 py-0.5 rounded font-medium ${Ae.file_type==="3mf"?"bg-bambu-green/20 text-bambu-green":Ae.file_type==="gcode"||Ae.file_type==="gcode.3mf"?"bg-blue-500/20 text-blue-400":Ae.file_type==="stl"?"bg-purple-500/20 text-purple-400":"bg-bambu-gray/20 text-bambu-gray"}`,children:Ae.file_type.toUpperCase()})}),r.jsx("div",{className:"text-sm text-bambu-gray",children:cs(Ae.file_size)}),r.jsx("div",{className:"text-sm text-bambu-gray",children:Ae.print_count>0?`${Ae.print_count}x`:"-"}),r.jsxs("div",{className:"flex items-center gap-1",onClick:we=>we.stopPropagation(),children:[Fw(Ae.filename)&&r.jsxs(r.Fragment,{children:[r.jsx("button",{onClick:()=>n("printers:control")&&ae(Ae),className:`p-1.5 rounded transition-colors ${n("printers:control")?"hover:bg-bambu-dark text-bambu-gray hover:text-bambu-green":"text-bambu-gray/50 cursor-not-allowed"}`,title:n("printers:control")?t("common.print"):t("fileManager.noPermissionPrint"),disabled:!n("printers:control"),children:r.jsx(xr,{className:"w-4 h-4"})}),r.jsx("button",{onClick:()=>{n("queue:create")&&oe(Ae)},className:`p-1.5 rounded transition-colors ${n("queue:create")?"hover:bg-bambu-dark text-bambu-gray hover:text-white":"text-bambu-gray/50 cursor-not-allowed"}`,title:n("queue:create")?t("fileManager.schedulePrint"):t("fileManager.noPermissionAddToQueue"),disabled:!n("queue:create"),children:r.jsx(ar,{className:"w-4 h-4"})})]}),(Te?.use_slicer_api??!1)&&gI(Ae.filename)&&r.jsx("button",{onClick:()=>n("library:upload")&&ie(Ae),className:`p-1.5 rounded transition-colors ${n("library:upload")?"hover:bg-bambu-dark text-bambu-gray hover:text-bambu-green":"text-bambu-gray/50 cursor-not-allowed"}`,title:n("library:upload")?t("slice.action"):t("fileManager.noPermissionSlice"),disabled:!n("library:upload"),children:r.jsx(bd,{className:"w-4 h-4"})}),(Ae.file_type==="3mf"||Ae.file_type==="gcode"||Ae.file_type==="gcode.3mf"||Ae.file_type==="stl")&&r.jsx("button",{onClick:()=>{n("library:read")&&(Fw(Ae.filename)?c(`/gcode-viewer?library_file=${Ae.id}`):A(Ae))},className:`p-1.5 rounded transition-colors ${n("library:read")?"hover:bg-bambu-dark text-bambu-gray hover:text-bambu-green":"text-bambu-gray/50 cursor-not-allowed"}`,title:n("library:read")?"3D Preview":"You do not have permission to preview files",disabled:!n("library:read"),children:r.jsx(Ei,{className:"w-4 h-4"})}),r.jsx("button",{onClick:()=>n("library:read")&&Pt(Ae.id),className:`p-1.5 rounded transition-colors ${n("library:read")?"hover:bg-bambu-dark text-bambu-gray hover:text-white":"text-bambu-gray/50 cursor-not-allowed"}`,title:n("library:read")?t("common.download"):t("fileManager.noPermissionDownload"),disabled:!n("library:read"),children:r.jsx(Ur,{className:"w-4 h-4"})}),r.jsx("button",{onClick:()=>s("library","update",Ae.created_by_id)&&he({type:"file",id:Ae.id,name:Ae.filename}),className:`p-1.5 rounded transition-colors ${s("library","update",Ae.created_by_id)?"hover:bg-bambu-dark text-bambu-gray hover:text-white":"text-bambu-gray/50 cursor-not-allowed"}`,title:s("library","update",Ae.created_by_id)?t("common.rename"):t("fileManager.noPermissionRenameFile"),disabled:!s("library","update",Ae.created_by_id),children:r.jsx(ci,{className:"w-4 h-4"})}),Ae.file_type==="stl"&&r.jsx("button",{onClick:()=>s("library","update",Ae.created_by_id)&&ht.mutate(Ae.id),className:`p-1.5 rounded transition-colors ${s("library","update",Ae.created_by_id)?"hover:bg-bambu-dark text-bambu-gray hover:text-bambu-green":"text-bambu-gray/50 cursor-not-allowed"}`,title:s("library","update",Ae.created_by_id)?t("fileManager.generateThumbnail"):t("fileManager.noPermissionGenerateThumbnail"),disabled:ht.isPending||!s("library","update",Ae.created_by_id),children:r.jsx(gu,{className:"w-4 h-4"})}),r.jsx("button",{onClick:()=>s("library","delete",Ae.created_by_id)&&z({type:"file",id:Ae.id}),className:`p-1.5 rounded transition-colors ${s("library","delete",Ae.created_by_id)?"hover:bg-bambu-dark text-bambu-gray hover:text-red-400":"text-bambu-gray/50 cursor-not-allowed"}`,title:s("library","delete",Ae.created_by_id)?t("common.delete"):t("fileManager.noPermissionDeleteFile"),disabled:!s("library","delete",Ae.created_by_id),children:r.jsx(na,{className:"w-4 h-4"})})]})]},Ae.id))]})})]})]}),x&&r.jsx(Dst,{parentId:m,onClose:()=>S(!1),onSave:Ae=>Ye.mutate(Ae),isLoading:Ye.isPending,t}),k&&r.jsx(Fst,{onClose:()=>P(!1),onSave:Ae=>Ve.mutate(Ae),isLoading:Ve.isPending,t}),N&&qe&&r.jsx(Ist,{folders:qe,selectedFiles:v,currentFolderId:m,onClose:()=>T(!1),onMove:Ae=>Ee.mutate({fileIds:v,folderId:Ae}),isLoading:Ee.isPending,t}),j&&r.jsx(jse,{folderId:m,onClose:()=>D(!1),onUploadComplete:vt}),C&&r.jsx(Est,{onClose:()=>E(!1)}),R&&r.jsx(Ost,{folder:R,onClose:()=>I(null),onLink:Ae=>at.mutate({id:R.id,data:Ae}),isLoading:at.isPending,t}),O&&r.jsx(ka,{title:O.type==="folder"?t("fileManager.deleteFolder"):O.type==="bulk"?t("fileManager.deleteFilesCount",{count:O.count}):t("fileManager.deleteFile"),message:O.type==="folder"?t("fileManager.deleteFolderConfirm"):O.type==="bulk"?t("fileManager.deleteFilesConfirm",{count:O.count}):t("fileManager.deleteFileConfirm"),confirmText:t("common.delete"),variant:"danger",isLoading:aa,loadingText:t("fileManager.deleting"),onConfirm:ea,onCancel:()=>z(null)}),X&&r.jsx(Pc,{mode:"reprint",libraryFileId:X.id,archiveName:X.print_name||X.filename,onClose:()=>ae(null),onSuccess:()=>{ae(null),e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["archives"]})}}),Y&&r.jsx(Pc,{mode:"reprint",libraryFileId:Y.id,archiveName:Y.print_name||Y.filename,onClose:()=>ce(null),onSuccess:()=>{ce(null),b([]),e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["archives"]})}}),de&&r.jsx(Pc,{mode:"add-to-queue",libraryFileId:de.id,archiveName:de.print_name||de.filename,onClose:()=>oe(null),onSuccess:()=>{oe(null),b([]),e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["queue"]}),e.invalidateQueries({queryKey:["archives"]})}}),K&&r.jsx(QA,{source:{kind:"libraryFile",id:K.id,filename:K.filename},onClose:()=>ie(null)}),Q&&r.jsx(jst,{libraryFileId:Q.id,title:Q.print_name||Q.filename,fileType:Q.file_type,onClose:()=>A(null),onSliceWithBambuddy:gI(Q.filename)&&n("library:upload")?()=>{const Ae=Q;A(null),ie(Ae)}:void 0}),ue&&r.jsx(zst,{type:ue.type,currentName:ue.name,onClose:()=>he(null),onSave:Ae=>{ue.type==="file"?Xe.mutate({id:ue.id,filename:Ae}):Nt.mutate({id:ue.id,name:Ae})},isLoading:Xe.isPending||Nt.isPending,t})]})}function Hst(t){const e=Ga(t);if(!e)return"";const a=Math.ceil((e.getTime()-Date.now())/(1e3*60*60*24));return a<=0?"any moment":a===1?"1 day":`${a} days`}function GX(t){const e=Ga(t);return e?e.toLocaleString():t}function qst(){const{t}=wt(),e=Ii(),a=ia(),{showToast:n}=da(),{hasPermission:i,authEnabled:s}=lr(),[o,l]=y.useState(null),[c,d]=y.useState(new Set),u=!s||i("library:purge"),m=$e({queryKey:["library-trash"],queryFn:()=>ne.listLibraryTrash(200,0)}),p=$e({queryKey:["library-trash-settings"],queryFn:()=>ne.getLibraryTrashSettings(),enabled:u}),[f,g]=y.useState(null);y.useEffect(()=>{p.data&&f===null&&g(p.data.retention_days)},[p.data,f]);const v=rt({mutationFn:O=>{const z=p.data;return ne.updateLibraryTrashSettings({retention_days:O,auto_purge_enabled:z?.auto_purge_enabled??!1,auto_purge_days:z?.auto_purge_days??90,auto_purge_include_never_printed:z?.auto_purge_include_never_printed??!0})},onSuccess:O=>{n(t("libraryTrash.toast.retentionSaved",{days:O.retention_days}),"success"),a.invalidateQueries({queryKey:["library-trash-settings"]}),a.invalidateQueries({queryKey:["library-trash"]})},onError:O=>n(O.message||t("libraryTrash.toast.retentionFailed"),"error")}),b=rt({mutationFn:O=>ne.restoreLibraryTrash(O),onSuccess:()=>{n(t("libraryTrash.toast.restored"),"success"),a.invalidateQueries({queryKey:["library-trash"]}),a.invalidateQueries({queryKey:["library-trash-count"]}),a.invalidateQueries({queryKey:["library-files"]}),a.invalidateQueries({queryKey:["library-folders"]})},onError:O=>n(O.message||t("libraryTrash.toast.restoreFailed"),"error")}),x=rt({mutationFn:O=>ne.hardDeleteLibraryTrash(O),onSuccess:()=>{n(t("libraryTrash.toast.purged"),"success"),a.invalidateQueries({queryKey:["library-trash"]}),a.invalidateQueries({queryKey:["library-trash-count"]})},onError:O=>n(O.message||t("libraryTrash.toast.purgeFailed"),"error")}),S=rt({mutationFn:()=>ne.emptyLibraryTrash(),onSuccess:O=>{n(t("libraryTrash.toast.emptied",{count:O.deleted}),"success"),a.invalidateQueries({queryKey:["library-trash"]}),a.invalidateQueries({queryKey:["library-trash-count"]})},onError:O=>n(O.message||t("libraryTrash.toast.emptyFailed"),"error")}),k=rt({mutationFn:O=>Promise.all(O.map(z=>ne.restoreLibraryTrash(z))),onSuccess:(O,z)=>{n(t("libraryTrash.toast.bulkRestored",{count:z.length}),"success"),d(new Set),a.invalidateQueries({queryKey:["library-trash"]}),a.invalidateQueries({queryKey:["library-trash-count"]}),a.invalidateQueries({queryKey:["library-files"]}),a.invalidateQueries({queryKey:["library-folders"]})},onError:O=>n(O.message||t("libraryTrash.toast.restoreFailed"),"error")}),P=rt({mutationFn:O=>Promise.all(O.map(z=>ne.hardDeleteLibraryTrash(z))),onSuccess:(O,z)=>{n(t("libraryTrash.toast.bulkPurged",{count:z.length}),"success"),d(new Set),a.invalidateQueries({queryKey:["library-trash"]}),a.invalidateQueries({queryKey:["library-trash-count"]})},onError:O=>n(O.message||t("libraryTrash.toast.purgeFailed"),"error")}),N=y.useMemo(()=>m.data?.items??[],[m.data?.items]),T=m.data?.retention_days??30,j=y.useMemo(()=>N.reduce((O,z)=>O+z.file_size,0),[N]),D=N.length>0&&N.every(O=>c.has(O.id)),C=c.size>0&&!D,E=O=>{d(z=>{const X=new Set(z);return X.has(O)?X.delete(O):X.add(O),X})},R=()=>{d(O=>O.size===N.length?new Set:new Set(N.map(z=>z.id)))},I=()=>{o&&(o.type==="delete"?x.mutate(o.id):o.type==="bulkDelete"?P.mutate(Array.from(c)):S.mutate(),l(null))};return r.jsxs("div",{className:"p-6 max-w-screen-2xl mx-auto",children:[r.jsx("div",{className:"flex items-center gap-3 mb-4",children:r.jsxs(Ls,{to:"/files",className:"inline-flex items-center gap-1 text-sm text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-200",children:[r.jsx(ev,{className:"w-4 h-4"})," ",t("libraryTrash.backToFiles")]})}),r.jsxs("div",{className:"flex items-start justify-between mb-6 gap-4 flex-wrap",children:[r.jsxs("div",{children:[r.jsx("h1",{className:"text-2xl font-bold text-gray-900 dark:text-gray-100",children:t("libraryTrash.title")}),r.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-400 mt-1",children:u?t("libraryTrash.subtitleAdmin",{days:T}):t("libraryTrash.subtitleUser",{days:T})})]}),N.length>0&&r.jsxs(Le,{variant:"secondary",onClick:()=>l({type:"empty"}),className:"text-red-600 dark:text-red-400",children:[r.jsx(na,{className:"w-4 h-4 mr-1"}),t("libraryTrash.emptyTrash")]})]}),u&&p.data&&r.jsxs("div",{className:"mb-4 border border-gray-200 dark:border-gray-700 rounded-lg p-3 flex items-center gap-3 bg-gray-50 dark:bg-gray-800/40",children:[r.jsx("label",{htmlFor:"retention-days",className:"text-sm font-medium text-gray-700 dark:text-gray-300",children:t("libraryTrash.retentionLabel")}),r.jsx("input",{id:"retention-days",type:"number",min:1,max:365,value:f??p.data.retention_days,onChange:O=>g(Math.max(1,Math.min(365,parseInt(O.target.value||"0",10)||0))),className:"w-20 rounded border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-sm px-2 py-1 text-gray-900 dark:text-gray-100"}),r.jsx("span",{className:"text-sm text-gray-600 dark:text-gray-400",children:t("libraryTrash.days")}),r.jsxs(Le,{variant:"secondary",onClick:()=>f!=null&&v.mutate(f),disabled:v.isPending||f==null||f===p.data.retention_days,className:"ml-auto",children:[r.jsx(ms,{className:"w-4 h-4 mr-1"}),t("common.save")]})]}),m.isLoading?r.jsxs("div",{className:"flex items-center gap-2 text-gray-500 dark:text-gray-400",children:[r.jsx(lt,{className:"w-4 h-4 animate-spin"})," ",t("libraryTrash.loading")]}):N.length===0?r.jsx("div",{className:"border border-dashed border-gray-300 dark:border-gray-700 rounded-lg p-12 text-center",children:r.jsx("p",{className:"text-gray-500 dark:text-gray-400",children:t("libraryTrash.empty")})}):r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"flex items-center justify-between mb-2",children:[r.jsx("div",{className:"text-xs text-gray-500 dark:text-gray-400",children:t("libraryTrash.summary",{count:N.length,size:cs(j)})}),c.size>0&&r.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[r.jsx("span",{className:"text-gray-600 dark:text-gray-400",children:t("libraryTrash.selectionCount",{count:c.size})}),r.jsxs(Le,{variant:"secondary",onClick:()=>k.mutate(Array.from(c)),disabled:k.isPending,children:[r.jsx(bs,{className:"w-4 h-4 mr-1"}),t("libraryTrash.bulkRestore")]}),r.jsxs(Le,{variant:"secondary",onClick:()=>l({type:"bulkDelete",count:c.size}),disabled:P.isPending,className:"text-red-600 dark:text-red-400",children:[r.jsx(na,{className:"w-4 h-4 mr-1"}),t("libraryTrash.bulkPurge")]})]})]}),r.jsx("div",{className:"border border-gray-200 dark:border-gray-700 rounded-lg overflow-x-auto",children:r.jsxs("table",{className:"w-full text-sm",children:[r.jsx("thead",{className:"bg-gray-50 dark:bg-gray-800 text-left text-gray-600 dark:text-gray-300",children:r.jsxs("tr",{children:[r.jsx("th",{className:"px-3 py-2 w-10",children:r.jsx("input",{type:"checkbox",checked:D,ref:O=>{O&&(O.indeterminate=C)},onChange:R,"aria-label":t("libraryTrash.selectAll"),className:"rounded border-gray-300 cursor-pointer"})}),r.jsx("th",{className:"px-3 py-2 font-medium",children:t("libraryTrash.col.filename")}),r.jsx("th",{className:"px-3 py-2 font-medium",children:t("libraryTrash.col.folder")}),r.jsx("th",{className:"px-3 py-2 font-medium text-right",children:t("libraryTrash.col.size")}),r.jsx("th",{className:"px-3 py-2 font-medium whitespace-nowrap",children:t("libraryTrash.col.deleted")}),r.jsx("th",{className:"px-3 py-2 font-medium whitespace-nowrap",children:t("libraryTrash.col.autoPurge")}),u&&r.jsx("th",{className:"px-3 py-2 font-medium",children:t("libraryTrash.col.owner")}),r.jsx("th",{className:"px-3 py-2 font-medium text-right",children:t("libraryTrash.col.actions")})]})}),r.jsx("tbody",{className:"divide-y divide-gray-100 dark:divide-gray-800",children:N.map(O=>r.jsxs("tr",{className:"hover:bg-gray-50 dark:hover:bg-gray-800/50",children:[r.jsx("td",{className:"px-3 py-2",children:r.jsx("input",{type:"checkbox",checked:c.has(O.id),onChange:()=>E(O.id),"aria-label":t("libraryTrash.selectOne",{filename:O.filename}),className:"rounded border-gray-300 cursor-pointer"})}),r.jsx("td",{className:"px-3 py-2 text-gray-900 dark:text-gray-100 truncate max-w-md",title:O.filename,children:O.filename}),r.jsx("td",{className:"px-3 py-2 text-gray-600 dark:text-gray-400",children:O.folder_name??"—"}),r.jsx("td",{className:"px-3 py-2 text-right text-gray-600 dark:text-gray-400 tabular-nums whitespace-nowrap",children:cs(O.file_size)}),r.jsx("td",{className:"px-3 py-2 text-gray-600 dark:text-gray-400 whitespace-nowrap",children:GX(O.deleted_at)}),r.jsx("td",{className:"px-3 py-2 text-gray-600 dark:text-gray-400 whitespace-nowrap",children:r.jsx("span",{title:GX(O.auto_purge_at),children:t("libraryTrash.autoPurgeIn",{when:Hst(O.auto_purge_at)})})}),u&&r.jsx("td",{className:"px-3 py-2 text-gray-600 dark:text-gray-400",children:O.created_by_username??"—"}),r.jsxs("td",{className:"px-3 py-2 text-right whitespace-nowrap",children:[r.jsxs("button",{onClick:()=>b.mutate(O.id),disabled:b.isPending,className:"inline-flex items-center gap-1 px-2 py-1 text-xs text-blue-600 hover:text-blue-800 dark:text-blue-400 dark:hover:text-blue-300",children:[r.jsx(bs,{className:"w-3.5 h-3.5"}),t("libraryTrash.restore")]}),r.jsxs("button",{onClick:()=>l({type:"delete",id:O.id,filename:O.filename}),disabled:x.isPending,className:"inline-flex items-center gap-1 px-2 py-1 text-xs text-red-600 hover:text-red-800 dark:text-red-400 dark:hover:text-red-300 ml-2",children:[r.jsx(na,{className:"w-3.5 h-3.5"}),t("libraryTrash.purgeNow")]})]})]},O.id))})]})})]}),o&&r.jsx(ka,{onCancel:()=>l(null),onConfirm:I,title:o.type==="delete"?t("libraryTrash.confirm.purgeTitle"):o.type==="bulkDelete"?t("libraryTrash.confirm.bulkPurgeTitle"):t("libraryTrash.confirm.emptyTitle"),message:o.type==="delete"?t("libraryTrash.confirm.purgeBody",{filename:o.filename}):o.type==="bulkDelete"?t("libraryTrash.confirm.bulkPurgeBody",{count:o.count}):t("libraryTrash.confirm.emptyBody",{count:N.length}),confirmText:t("libraryTrash.confirm.cta"),variant:"danger"}),m.isError&&r.jsxs("div",{className:"mt-4 text-sm text-red-600 dark:text-red-400",children:[m.error?.message??t("libraryTrash.loadError"),r.jsx(Le,{variant:"secondary",onClick:()=>e("/files"),className:"ml-3",children:t("libraryTrash.backToFiles")})]})]})}function Vst(t,e){const a=`token=${encodeURIComponent(e)}`;let n=0;return t.querySelectorAll('img[src*="/api/v1/"], video[src*="/api/v1/"]').forEach(i=>{const s=i.getAttribute("src")||"";if(s.includes(a))return;const o=s.replace(/([?&])token=[^&]*(&|$)/,(c,d,u)=>u==="&"?d:""),l=o.includes("?")?"&":"?";i.src=`${o}${l}${a}`,n+=1}),n}function Mde(){const{authEnabled:t,user:e,loading:a}=lr(),n=ia(),i=y.useRef(!1),{data:s}=$e({queryKey:["camera-stream-token",e?.id??null],queryFn:()=>ne.getCameraStreamToken(),enabled:!a&&(!t||e!==null),staleTime:3e3*1e3,refetchInterval:3e3*1e3});y.useEffect(()=>{const o=s?.token??null;return D8(o),o&&Vst(document,o),()=>D8(null)},[s?.token]),y.useEffect(()=>{if(!t)return;const o=l=>{const c=l.target;if(!(c instanceof HTMLImageElement||c instanceof HTMLVideoElement))return;const d=c.src||"",u=yJ();!u||!d.includes(`token=${encodeURIComponent(u)}`)||i.current||(i.current=!0,n.invalidateQueries({queryKey:["camera-stream-token"]}),setTimeout(()=>{i.current=!1},5e3))};return document.addEventListener("error",o,!0),()=>document.removeEventListener("error",o,!0)},[t,n])}const kP=5,Gst=2e3,$st=3e4,Wst=5e3;function Kst(){const{t}=wt(),e=ia(),{showToast:a}=da(),{hasPermission:n,authEnabled:i,user:s}=lr(),{printerId:o}=FS(),l=parseInt(o||"0",10),[c]=mb(),d=parseInt(c.get("fps")||"15",10),u=Math.min(Math.max(isNaN(d)?15:d,1),30);Mde();const{data:m}=$e({queryKey:["camera-stream-token",s?.id??null],queryFn:()=>ne.getCameraStreamToken(),enabled:i?!!s:!0,staleTime:3e3*1e3}),p=m?.token??yJ(),[f,g]=y.useState("stream"),[v,b]=y.useState(!1),[x,S]=y.useState(!1),[k,P]=y.useState(!1),[N,T]=y.useState(!0),[j,D]=y.useState(Date.now()),[C,E]=y.useState(!1),[R,I]=y.useState(!1),[O,z]=y.useState(0),[X,ae]=y.useState(!1),[Y,ce]=y.useState(0),[de,oe]=y.useState(1),[K,ie]=y.useState({x:0,y:0}),[ue,he]=y.useState(!1),[ge,q]=y.useState({x:0,y:0}),[Q,A]=y.useState(null),[F,B]=y.useState(null),W=y.useRef(null),H=y.useRef(null),le=y.useRef(null),U=y.useRef(null),G=y.useRef(null),{data:Z}=$e({queryKey:["printer",l],queryFn:()=>ne.getPrinter(l),enabled:l>0}),{data:J}=$e({queryKey:["printerStatus",l],queryFn:()=>ne.getPrinterStatus(l),refetchInterval:3e4,enabled:l>0}),re=rt({mutationFn:Be=>ne.setChamberLight(l,Be),onMutate:async Be=>{await e.cancelQueries({queryKey:["printerStatus",l]});const Qe=e.getQueryData(["printerStatus",l]);return e.setQueryData(["printerStatus",l],Ge=>({...Ge,chamber_light:Be})),{previousStatus:Qe}},onSuccess:(Be,Qe)=>{a(`Chamber light ${Qe?"on":"off"}`)},onError:(Be,Qe,Ge)=>{Ge?.previousStatus&&e.setQueryData(["printerStatus",l],Ge.previousStatus),a(Be.message||t("printers.toast.failedToControlChamberLight"),"error")}}),se=(J?.state==="RUNNING"||J?.state==="PAUSE")&&(J?.printable_objects_count??0)>=2;y.useEffect(()=>(Z&&(document.title=`${Z.name} - Camera`),()=>{document.title="Bambuddy"}),[Z]);const fe=y.useRef(!1);y.useEffect(()=>{const Be=`/api/v1/printers/${l}/camera/stop`;fe.current=!1;const Qe=()=>{if(l>0&&!fe.current){fe.current=!0;const at={},Xe=ep();Xe&&(at.Authorization=`Bearer ${Xe}`),fetch(Be,{method:"POST",keepalive:!0,headers:at}).catch(()=>{})}},Ge=()=>{Qe()};window.addEventListener("beforeunload",Ge);const Ee=W.current;return()=>{window.removeEventListener("beforeunload",Ge),Ee&&(Ee.src=""),Qe()}},[l]),y.useEffect(()=>{if(N&&!C){const Qe=setTimeout(()=>{T(!1)},f==="stream"?3e3:2e4);return()=>clearTimeout(Qe)}},[f,N,j,C]),y.useEffect(()=>{const Be=()=>{const Qe=!!document.fullscreenElement;I(Qe),oe(1),ie({x:0,y:0}),f==="stream"&&!C&&(W.current&&(W.current.src=""),setTimeout(()=>{T(!0),D(Date.now())},200))};return document.addEventListener("fullscreenchange",Be),()=>document.removeEventListener("fullscreenchange",Be)},[f,C]),y.useEffect(()=>{let Be;const Qe=()=>{clearTimeout(Be),Be=setTimeout(()=>{localStorage.setItem("cameraWindowState",JSON.stringify({width:window.outerWidth,height:window.outerHeight,left:window.screenX,top:window.screenY}))},500)};return window.addEventListener("resize",Qe),()=>{clearTimeout(Be),window.removeEventListener("resize",Qe)}},[]),y.useEffect(()=>()=>{le.current&&clearTimeout(le.current),U.current&&clearInterval(U.current),G.current&&clearInterval(G.current)},[]);const me=y.useCallback(()=>{if(O>=kP){ae(!1),P(!0);return}const Be=Math.min(Gst*Math.pow(2,O),$st);ae(!0),ce(Math.ceil(Be/1e3)),U.current=setInterval(()=>{ce(Qe=>Qe<=1?(U.current&&clearInterval(U.current),0):Qe-1)},1e3),le.current=setTimeout(()=>{z(Qe=>Qe+1),ae(!1),T(!0),P(!1),W.current&&(W.current.src=""),D(Date.now())},Be)},[O]);y.useEffect(()=>{if(f!=="stream"||N||X||C){G.current&&(clearInterval(G.current),G.current=null);return}return G.current=setInterval(async()=>{try{const Be=await ne.getCameraStatus(l);(Be.stalled||!Be.active&&!k)&&(console.log(`Stream issue detected: stalled=${Be.stalled}, active=${Be.active}, reconnecting...`),G.current&&(clearInterval(G.current),G.current=null),T(!1),me())}catch{}},Wst),()=>{G.current&&(clearInterval(G.current),G.current=null)}},[f,N,k,X,C,l,me]);const pe=()=>{T(!1),f==="stream"&&O{if(T(!1),P(!1),z(0),ae(!1),le.current&&clearTimeout(le.current),U.current&&clearInterval(U.current),W.current&&!localStorage.getItem("cameraWindowState")){const Be=W.current,Qe=Be.naturalWidth,Ge=Be.naturalHeight;if(Qe>0&&Ge>0){const Xe=window.outerWidth-window.innerWidth,Nt=window.outerHeight-window.innerHeight,Vt=Qe+16+Xe,ht=Ge+45+16+Nt;try{window.resizeTo(Vt,ht)}catch{}}}},L=()=>{if(l>0){const Be={},Qe=ep();Qe&&(Be.Authorization=`Bearer ${Qe}`),fetch(`/api/v1/printers/${l}/camera/stop`,{method:"POST",headers:Be}).catch(()=>{})}},te=Be=>{f===Be||C||(E(!0),T(!0),P(!1),z(0),ae(!1),oe(1),ie({x:0,y:0}),le.current&&clearTimeout(le.current),U.current&&clearInterval(U.current),W.current&&(W.current.src=""),f==="stream"&&L(),setTimeout(()=>{g(Be),D(Date.now()),E(!1)},100))},be=()=>{C||(E(!0),T(!0),P(!1),z(0),ae(!1),le.current&&clearTimeout(le.current),U.current&&clearInterval(U.current),W.current&&(W.current.src=""),f==="stream"&&L(),setTimeout(()=>{D(Date.now()),E(!1)},100))},xe=()=>{H.current&&(document.fullscreenElement?document.exitFullscreen():H.current.requestFullscreen())},ve=()=>{oe(Be=>Math.min(Be+.5,4))},De=()=>{oe(Be=>{const Qe=Math.max(Be-.5,1);return Qe===1&&ie({x:0,y:0}),Qe})},je=Be=>{Be.preventDefault(),Be.deltaY<0?ve():De()},Te=Be=>{de>1&&(Be.preventDefault(),he(!0),q({x:Be.clientX-K.x,y:Be.clientY-K.y}))},qe=y.useCallback(()=>{if(!H.current)return{x:300,y:200};const Be=H.current.getBoundingClientRect(),Qe=Be.width*(de-1)/2,Ge=Be.height*(de-1)/2;return{x:Math.max(50,Qe),y:Math.max(50,Ge)}},[de]),Pe=Be=>{if(ue&&de>1){const Qe=Be.clientX-ge.x,Ge=Be.clientY-ge.y,Ee=qe();ie({x:Math.max(-Ee.x,Math.min(Ee.x,Qe)),y:Math.max(-Ee.y,Math.min(Ee.y,Ge))})}},Ie=()=>{he(!1)},Re=Be=>{if(Be.length<2)return 0;const Qe=Be[0].clientX-Be[1].clientX,Ge=Be[0].clientY-Be[1].clientY;return Math.sqrt(Qe*Qe+Ge*Ge)},Ue=Be=>Be.length<2?{x:Be[0].clientX,y:Be[0].clientY}:{x:(Be[0].clientX+Be[1].clientX)/2,y:(Be[0].clientY+Be[1].clientY)/2},ze=Be=>{Be.touches.length===2?(Be.preventDefault(),A(Re(Be.touches)),B(Ue(Be.touches))):Be.touches.length===1&&de>1&&(Be.preventDefault(),he(!0),q({x:Be.touches[0].clientX-K.x,y:Be.touches[0].clientY-K.y}))},it=Be=>{if(Be.touches.length===2&&Q!==null){Be.preventDefault();const Qe=Re(Be.touches),Ge=Qe/Q;oe(at=>{const Xe=Math.max(1,Math.min(4,at*Ge));return Xe===1&&ie({x:0,y:0}),Xe}),A(Qe);const Ee=Ue(Be.touches);if(F){const at=qe();ie(Xe=>({x:Math.max(-at.x,Math.min(at.x,Xe.x+(Ee.x-F.x))),y:Math.max(-at.y,Math.min(at.y,Xe.y+(Ee.y-F.y)))}))}B(Ee)}else if(Be.touches.length===1&&ue&&de>1){Be.preventDefault();const Qe=Be.touches[0].clientX-ge.x,Ge=Be.touches[0].clientY-ge.y,Ee=qe();ie({x:Math.max(-Ee.x,Math.min(Ee.x,Qe)),y:Math.max(-Ee.y,Math.min(Ee.y,Ge))})}},Oe=Be=>{Be.touches.length<2&&(A(null),B(null)),Be.touches.length===0&&he(!1)},tt=()=>{oe(1),ie({x:0,y:0})},Fe=i&&!p,Ye=Be=>p?`${Be}&token=${encodeURIComponent(p)}`:zn(Be),Ve=C||Fe?"":Ye(f==="stream"?`/api/v1/printers/${l}/camera/stream?fps=${u}&t=${j}`:`/api/v1/printers/${l}/camera/snapshot?t=${j}`),Me=N||C||X;return l?r.jsxs("div",{ref:H,className:"min-h-screen bg-black flex flex-col",children:[r.jsxs("div",{className:"flex items-center justify-between px-4 py-2 bg-bambu-dark-secondary border-b border-bambu-dark-tertiary",children:[r.jsxs("h1",{className:"text-sm font-medium text-white flex items-center gap-2",children:[r.jsx(wy,{className:"w-4 h-4"}),Z?.name||`Printer ${l}`]}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsxs("div",{className:"flex bg-bambu-dark rounded p-0.5",children:[r.jsx("button",{onClick:()=>te("stream"),disabled:Me,className:`px-3 py-1 text-xs rounded transition-colors ${f==="stream"?"bg-bambu-green text-white":"text-bambu-gray hover:text-white disabled:opacity-50"}`,children:t("camera.live")}),r.jsx("button",{onClick:()=>te("snapshot"),disabled:Me,className:`px-3 py-1 text-xs rounded transition-colors ${f==="snapshot"?"bg-bambu-green text-white":"text-bambu-gray hover:text-white disabled:opacity-50"}`,children:t("camera.snapshot")})]}),r.jsx("button",{onClick:()=>re.mutate(!J?.chamber_light),disabled:!J?.connected||re.isPending||!n("printers:control"),className:`p-1.5 rounded disabled:opacity-50 ${J?.chamber_light?"bg-yellow-500/20 hover:bg-yellow-500/30":"hover:bg-bambu-dark-tertiary"}`,title:n("printers:control")?t("camera.chamberLight"):t("printers.permission.noControl"),children:r.jsx(CO,{on:J?.chamber_light??!1,className:"w-4 h-4"})}),r.jsx("button",{onClick:()=>b(!0),disabled:!se||!n("printers:control"),className:`p-1.5 rounded disabled:opacity-50 ${se&&n("printers:control")?"hover:bg-bambu-dark-tertiary":""}`,title:n("printers:control")?t(se?"printers.skipObjects.tooltip":"printers.skipObjects.onlyWhilePrinting"):t("printers.permission.noControl"),children:r.jsx(JT,{className:"w-4 h-4 text-bambu-gray"})}),r.jsx("button",{onClick:be,disabled:Me,className:"p-1.5 hover:bg-bambu-dark-tertiary rounded disabled:opacity-50",title:t(f==="stream"?"camera.restartStream":"camera.refreshSnapshot"),children:r.jsx(tr,{className:`w-4 h-4 text-bambu-gray ${Me?"animate-spin":""}`})}),r.jsx("button",{onClick:()=>S(!0),className:"p-1.5 hover:bg-bambu-dark-tertiary rounded",title:t("camera.diagnose.button"),children:r.jsx(Ll,{className:"w-4 h-4 text-bambu-gray"})}),r.jsx("button",{onClick:xe,className:"p-1.5 hover:bg-bambu-dark-tertiary rounded",title:t(R?"camera.exitFullscreen":"camera.fullscreen"),children:R?r.jsx(cJ,{className:"w-4 h-4 text-bambu-gray"}):r.jsx(cye,{className:"w-4 h-4 text-bambu-gray"})})]})]}),r.jsx("div",{className:"flex-1 flex items-center justify-center p-2 overflow-hidden",onWheel:je,onMouseMove:Pe,onMouseUp:Ie,onMouseLeave:Ie,onTouchStart:ze,onTouchMove:it,onTouchEnd:Oe,style:{touchAction:"none"},children:r.jsxs("div",{className:"relative w-full h-full flex items-center justify-center",children:[(N||C)&&!X&&r.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/50 z-10",children:r.jsxs("div",{className:"text-center",children:[r.jsx(tr,{className:"w-8 h-8 text-bambu-gray animate-spin mx-auto mb-2"}),r.jsx("p",{className:"text-sm text-bambu-gray",children:t(f==="stream"?"camera.connectingToCamera":"camera.capturingSnapshot")})]})}),X&&r.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/80 z-10",children:r.jsxs("div",{className:"text-center p-4",children:[r.jsx(xu,{className:"w-10 h-10 text-orange-400 mx-auto mb-3"}),r.jsx("p",{className:"text-white mb-2",children:t("camera.connectionLost")}),r.jsx("p",{className:"text-sm text-bambu-gray mb-3",children:t("camera.reconnecting",{countdown:Y,attempt:Math.min(O+1,kP),max:kP})}),r.jsx("button",{onClick:be,className:"px-4 py-2 bg-bambu-green text-white text-sm rounded hover:bg-bambu-green/80 transition-colors",children:t("camera.reconnectNow")})]})}),k&&!X&&r.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black z-10",children:r.jsxs("div",{className:"text-center p-4",children:[r.jsx(xa,{className:"w-12 h-12 text-orange-400 mx-auto mb-3"}),r.jsx("p",{className:"text-white mb-2",children:t("camera.cameraUnavailable")}),r.jsx("p",{className:"text-xs text-bambu-gray mb-4 max-w-md",children:t("camera.cameraUnavailableDesc")}),r.jsxs("div",{className:"flex gap-2 justify-center",children:[r.jsx("button",{onClick:be,className:"px-4 py-2 bg-bambu-green text-white rounded hover:bg-bambu-green/80 transition-colors",children:t("camera.retry")}),r.jsx("button",{onClick:()=>S(!0),className:"px-4 py-2 bg-bambu-dark border border-bambu-dark-tertiary text-bambu-gray hover:text-white rounded transition-colors",children:t("camera.diagnose.button")})]})]})}),r.jsx("img",{ref:W,src:Ve,alt:t("camera.cameraStream"),className:"max-w-full max-h-full object-contain select-none",style:{transform:`scale(${de}) translate(${K.x/de}px, ${K.y/de}px) rotate(${Z?.camera_rotation||0}deg)`,...Z?.camera_rotation===90||Z?.camera_rotation===270?{maxWidth:"100vh",maxHeight:"100vw"}:{},cursor:de>1?ue?"grabbing":"grab":"default"},onError:Ve?pe:void 0,onLoad:Ve?V:void 0,onMouseDown:Te,draggable:!1},j),r.jsxs("div",{className:"absolute bottom-4 left-4 flex items-center gap-1.5 bg-black/60 rounded-lg px-2 py-1.5",children:[r.jsx("button",{onClick:De,disabled:de<=1,className:"p-1.5 hover:bg-white/10 rounded disabled:opacity-30",title:t("camera.zoomOut"),children:r.jsx(GI,{className:"w-4 h-4 text-white"})}),r.jsxs("button",{onClick:tt,className:"px-2 py-1 text-sm text-white hover:bg-white/10 rounded min-w-[48px]",title:t("camera.resetZoom"),children:[Math.round(de*100),"%"]}),r.jsx("button",{onClick:ve,disabled:de>=4,className:"p-1.5 hover:bg-white/10 rounded disabled:opacity-30",title:t("camera.zoomIn"),children:r.jsx(VI,{className:"w-4 h-4 text-white"})})]})]})}),r.jsx(PO,{printerId:l,isOpen:v,onClose:()=>b(!1)}),x&&r.jsx(ate,{printerId:l,printerName:Z?.name||null,onClose:()=>S(!1)})]}):r.jsx("div",{className:"min-h-screen bg-black flex items-center justify-center",children:r.jsx("p",{className:"text-white",children:t("camera.invalidPrinterId")})})}function Yst(t,e,a){if(!t)return"";if(!e)return t;const n=e.match(/plate_(\d+)\.gcode/);return n&&parseInt(n[1],10)>1?`${t} — ${a("printers.plateNumber","Plate {{number}}",{number:n[1]})}`:t}function Qst(t){const e=t.get("show")?.split(",")||["progress","layers","eta","filename","status"],a=parseInt(t.get("fps")||"15",10),n=Math.min(Math.max(isNaN(a)?15:a,1),30),i=t.get("camera"),s=i!=="false"&&i!=="0";return{size:t.get("size")||"medium",fps:n,showCamera:s,showProgress:e.includes("progress"),showLayers:e.includes("layers"),showEta:e.includes("eta"),showFilename:e.includes("filename"),showStatus:e.includes("status"),showPrinter:e.includes("printer")}}function Xst(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 Zst(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 Jst(){const{printerId:t}=FS(),[e]=mb(),{t:a}=wt(),n=ia(),i=parseInt(t||"0",10),[s,o]=y.useState(Date.now()),l=y.useMemo(()=>Qst(e),[e]),c=Zst(l.size),{data:d}=$e({queryKey:["printer",i],queryFn:()=>ne.getPrinter(i),enabled:i>0}),{data:u}=$e({queryKey:["printerStatus",i],queryFn:()=>ne.getPrinterStatus(i),enabled:i>0,refetchInterval:2e3}),{data:m}=$e({queryKey:["settings"],queryFn:ne.getSettings}),p=m?.time_format||"system";y.useEffect(()=>{if(!i)return;let x=null,S=!1;return(async()=>{let k;try{k=(await ne.getWebSocketToken()).token}catch{}if(S)return;const P=window.location.protocol==="https:"?"wss:":"ws:",N=k?`?token=${encodeURIComponent(k)}`:"",T=`${P}//${window.location.host}/api/v1/ws${N}`;x=new WebSocket(T),x.onmessage=j=>{try{const D=JSON.parse(j.data);D.type==="printer_status"&&D.printer_id===i&&n.setQueryData(["printerStatus",i],D.status)}catch{}},x.onerror=()=>{}})(),()=>{S=!0,x&&x.close()}},[i,n]),y.useEffect(()=>(document.title=d?`${d.name} - ${a("streamOverlay.title")}`:a("streamOverlay.title"),()=>{document.title="Bambuddy"}),[d,a]);const f=()=>{setTimeout(()=>{o(Date.now())},3e3)};if(!i)return r.jsx("div",{className:"min-h-screen bg-black flex items-center justify-center",children:r.jsx("p",{className:"text-white",children:a("streamOverlay.invalidPrinterId")})});if(!u)return r.jsx("div",{className:"min-h-screen bg-black flex items-center justify-center",children:r.jsx("p",{className:"text-gray-400",children:a("common.loading")})});const g=u.state==="RUNNING"||u.state==="PAUSE",v=u.progress||0,b=zn(`/api/v1/printers/${i}/camera/stream?fps=${l.fps}&t=${s}`);return r.jsxs("div",{className:"min-h-screen bg-black relative overflow-hidden",children:[l.showCamera&&r.jsx("img",{src:b,alt:a("streamOverlay.cameraStream"),className:"absolute inset-0 w-full h-full object-contain",style:d?.camera_rotation?{transform:`rotate(${d.camera_rotation}deg)`}:void 0,onError:f},s),r.jsx("a",{href:"https://github.com/maziggy/bambuddy",target:"_blank",rel:"noopener noreferrer",className:"absolute top-4 right-4 z-10",children:r.jsx("img",{src:"/img/bambuddy_logo_dark_transparent.png",alt:"Bambuddy",className:`${c.logoHeight} object-contain drop-shadow-lg hover:scale-105 transition-transform`})}),r.jsx("div",{className:"absolute bottom-0 left-0 right-0 z-10 bg-gradient-to-t from-black/80 via-black/60 to-transparent",children:r.jsxs("div",{className:`${c.container}`,children:[l.showPrinter&&d&&r.jsxs("div",{className:`flex items-center ${c.gap} mb-2`,children:[r.jsx(xr,{className:`${c.icon} text-white/70`}),r.jsx("span",{className:`${c.text} text-white font-medium`,children:d.name})]}),l.showFilename&&u.current_print&&r.jsx("div",{className:`${c.textLarge} text-white font-semibold mb-2 truncate drop-shadow-md`,children:Yst(u.current_print.replace(/\.gcode\.3mf$|\.3mf$|\.gcode$/i,""),u.gcode_file,a)}),l.showStatus&&r.jsx("div",{className:`${c.text} text-white/70 mb-2`,children:Xst(u,a)}),l.showProgress&&g&&r.jsxs("div",{className:"mb-3",children:[r.jsxs("div",{className:`flex items-center justify-between mb-1 ${c.text}`,children:[r.jsx("span",{className:"text-white/70",children:a("streamOverlay.progress")}),r.jsxs("span",{className:"text-white font-bold",children:[Math.round(v),"%"]})]}),r.jsx("div",{className:`w-full bg-white/20 rounded-full ${c.progressHeight}`,children:r.jsx("div",{className:`bg-bambu-green ${c.progressHeight} rounded-full transition-all duration-500`,style:{width:`${v}%`}})})]}),g&&(l.showLayers||l.showEta)&&r.jsxs("div",{className:`flex items-center ${c.gap} flex-wrap`,children:[l.showLayers&&u.layer_num!=null&&u.total_layers!=null&&u.total_layers>0&&r.jsxs("div",{className:`flex items-center ${c.gap} text-white/70`,children:[r.jsx(tn,{className:c.icon}),r.jsxs("span",{className:c.text,children:[r.jsx("span",{className:"text-white",children:u.layer_num}),r.jsx("span",{className:"mx-1",children:"/"}),r.jsx("span",{children:u.total_layers})]})]}),l.showEta&&u.remaining_time!=null&&u.remaining_time>0&&r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:`flex items-center ${c.gap} text-white/70`,children:[r.jsx(ru,{className:c.icon}),r.jsx("span",{className:`${c.text} text-white`,children:ds(u.remaining_time*60)})]}),r.jsxs("div",{className:`flex items-center ${c.gap} text-white/70`,children:[r.jsx(ar,{className:c.icon}),r.jsxs("span",{className:`${c.text} text-white`,children:[a("streamOverlay.eta")," ",YI(u.remaining_time,p,a)]})]})]})]}),!g&&r.jsx("div",{className:`${c.text} text-white/70 py-2`,children:u.connected?a("streamOverlay.printerIdle"):a("streamOverlay.printerOffline")})]})})]})}function eot(){const{t}=wt(),{id:e}=FS(),{mode:a}=gb(),{data:n,isLoading:i,error:s}=$e({queryKey:["external-link",e],queryFn:()=>ne.getExternalLink(Number(e)),enabled:!!e});return i?r.jsx("div",{className:"flex items-center justify-center h-full",children:r.jsx(lt,{className:"w-8 h-8 text-bambu-green animate-spin"})}):s||!n?r.jsxs("div",{className:"flex flex-col items-center justify-center h-full gap-4 text-bambu-gray",children:[r.jsx(xa,{className:"w-12 h-12"}),r.jsx("p",{children:t("common.linkNotFound")})]}):r.jsx("iframe",{src:n.url,className:"h-full w-full border-0",style:{colorScheme:a},title:n.name,sandbox:"allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox"})}function $X(){const{id:t}=FS(),e=Ii(),a=ia(),{t:n}=wt(),{showToast:i}=da(),s=!!t,[o,l]=y.useState(""),[c,d]=y.useState(""),[u,m]=y.useState([]),[p,f]=y.useState(""),[g,v]=y.useState(!1),{data:b,isLoading:x}=$e({queryKey:["group",t],queryFn:()=>ne.getGroup(Number(t)),enabled:s}),{data:S,isLoading:k}=$e({queryKey:["permissions"],queryFn:()=>ne.getPermissions()});s&&b&&!g&&(l(b.name),d(b.description||""),m(b.permissions),v(!0));const P=rt({mutationFn:Y=>ne.createGroup(Y),onSuccess:()=>{a.invalidateQueries({queryKey:["groups"]}),a.invalidateQueries({queryKey:["group"]}),i(n("groups.toast.created")),e("/settings?tab=users")},onError:Y=>{i(Y.message,"error")}}),N=rt({mutationFn:Y=>ne.updateGroup(Number(t),Y),onSuccess:Y=>{a.invalidateQueries({queryKey:["groups"]}),Y&&a.setQueryData(["group",t],Y),i(n("groups.toast.updated")),e("/settings?tab=users")},onError:Y=>{i(Y.message,"error")}}),T=P.isPending||N.isPending,j=()=>{if(!o.trim()){i(n("groups.toast.enterGroupName"),"error");return}s?N.mutate({name:o!==b?.name?o:void 0,description:c,permissions:u}):P.mutate({name:o,description:c||void 0,permissions:u})},D=Y=>{m(ce=>ce.includes(Y)?ce.filter(de=>de!==Y):[...ce,Y])},C=(Y,ce)=>{const de=Y.permissions.map(oe=>oe.value);m(oe=>{const K=oe.filter(ie=>!de.includes(ie));return ce?[...K,...de]:K})},E=Y=>Y.permissions.every(ce=>u.includes(ce.value)),R=Y=>{const ce=Y.permissions.filter(de=>u.includes(de.value)).length;return ce>0&&ce{S&&m(S.all_permissions)},O=()=>{m([])},z=p.toLowerCase(),X=y.useMemo(()=>S?z?S.categories.map(Y=>({...Y,permissions:Y.permissions.filter(ce=>ce.label.toLowerCase().includes(z))})).filter(Y=>Y.permissions.length>0):S.categories:[],[S,z]),ae=S?.all_permissions.length??0;return x||k?r.jsx("div",{className:"flex items-center justify-center py-16",children:r.jsx(lt,{className:"w-8 h-8 text-bambu-green animate-spin"})}):r.jsxs("div",{className:"space-y-6 max-w-5xl mx-auto",children:[r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("button",{onClick:()=>e("/settings?tab=users"),className:"p-2 rounded-lg hover:bg-bambu-dark-tertiary text-bambu-gray hover:text-white transition-colors",children:r.jsx(ev,{className:"w-5 h-5"})}),r.jsx("h1",{className:"text-xl font-bold text-white",children:n(s?"groups.editor.title":"groups.editor.createTitle")})]}),s&&b?.is_system&&r.jsxs("div",{className:"flex items-center gap-3 px-4 py-3 rounded-lg bg-yellow-500/10 border border-yellow-500/20 text-yellow-400 text-sm",children:[r.jsx(xa,{className:"w-4 h-4 shrink-0"}),n("groups.form.systemGroupWarning")]}),r.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:n("groups.form.groupName")}),r.jsx("input",{type:"text",value:o,onChange:Y=>l(Y.target.value),disabled:s&&b?.is_system,className:"w-full px-4 py-3 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors disabled:opacity-50",placeholder:n("groups.form.groupNamePlaceholder")})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:n("groups.form.description")}),r.jsx("input",{type:"text",value:c,onChange:Y=>d(Y.target.value),className:"w-full px-4 py-3 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors",placeholder:n("groups.form.descriptionPlaceholder")})]})]}),r.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-3",children:[r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsxs("span",{className:"text-sm text-bambu-gray",children:[n("groups.editor.permissionsSelected",{count:u.length})," / ",ae]}),r.jsx(Le,{size:"sm",variant:"ghost",onClick:I,children:n("groups.editor.selectAll")}),r.jsx(Le,{size:"sm",variant:"ghost",onClick:O,children:n("groups.editor.clearAll")})]}),r.jsxs("div",{className:"relative",children:[r.jsx(br,{className:"w-4 h-4 absolute left-3 top-1/2 -translate-y-1/2 text-bambu-gray"}),r.jsx("input",{type:"text",value:p,onChange:Y=>f(Y.target.value),placeholder:n("groups.editor.search"),className:"pl-9 pr-4 py-2 text-sm bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors w-64"})]})]}),X.length===0?r.jsx("div",{className:"text-center py-12 text-bambu-gray",children:n("groups.editor.noResults")}):r.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:X.map(Y=>{const ce=S.categories.find(ue=>ue.name===Y.name),de=ce.permissions.filter(ue=>u.includes(ue.value)).length,oe=ce.permissions.length,K=E(ce),ie=R(ce);return r.jsxs(Tt,{children:[r.jsxs("div",{className:"sticky top-0 z-10 flex items-center justify-between px-4 py-3 bg-bambu-dark-secondary border-b border-bambu-dark-tertiary rounded-t-xl",children:[r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsxs("button",{type:"button",onClick:()=>C(ce,!K),className:`w-5 h-5 rounded border flex items-center justify-center transition-colors shrink-0 ${K?"bg-bambu-green border-bambu-green":ie?"bg-bambu-green/50 border-bambu-green":"border-bambu-gray hover:border-white"}`,children:[K&&r.jsx(_r,{className:"w-3 h-3 text-white"}),ie&&!K&&r.jsx(hN,{className:"w-3 h-3 text-white"})]}),r.jsx(kl,{className:"w-4 h-4 text-bambu-gray shrink-0"}),r.jsx("span",{className:"text-white font-medium text-sm",children:Y.name})]}),r.jsxs("span",{className:"text-xs text-bambu-gray tabular-nums",children:[de,"/",oe]})]}),r.jsx("div",{className:"p-3 space-y-1",children:Y.permissions.map(ue=>r.jsxs("label",{className:"flex items-center gap-3 px-2 py-1.5 rounded hover:bg-bambu-dark-secondary cursor-pointer",children:[r.jsx("input",{type:"checkbox",checked:u.includes(ue.value),onChange:()=>D(ue.value),className:"w-4 h-4 rounded border-bambu-gray text-bambu-green focus:ring-bambu-green focus:ring-offset-0 bg-bambu-dark-secondary"}),r.jsx("span",{className:"text-sm text-bambu-gray",children:ue.label})]},ue.value))})]},Y.name)})}),r.jsx("div",{className:"h-16"}),r.jsxs("div",{className:"fixed bottom-0 left-0 right-0 z-20 px-6 py-3 bg-bambu-dark-secondary border-t border-bambu-dark-tertiary flex items-center justify-center gap-3",children:[r.jsx(Le,{variant:"secondary",onClick:()=>e("/settings?tab=users"),children:n("common.cancel")}),r.jsx(Le,{onClick:j,disabled:T||!o.trim(),children:T?r.jsxs(r.Fragment,{children:[r.jsx(lt,{className:"w-4 h-4 animate-spin"}),n("common.saving")]}):r.jsxs(r.Fragment,{children:[r.jsx(ms,{className:"w-4 h-4"}),n("common.save")]})})]})]})}const tot=1.65,WX=["#1DB954","#3B82F6","#F59E0B","#EF4444","#8B5CF6"];function Lw(t,e,a){return`${t}||${e??""}||${a??""}`}function Km(t,e){const a=new Date(t);return a.setDate(a.getDate()+Math.round(e)),a}function ES(t){return t.toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})}function Rw(t){return t.toLocaleDateString(void 0,{month:"short",day:"numeric"})}function aot(t){if(t.length<2)return null;const e=[...t].sort((c,d)=>new Date(c.created_at).getTime()-new Date(d.created_at).getTime()),a=Date.now(),n=Math.LN2/30,i=[];for(let c=1;cc+d.weight,0);if(s===0)return null;const o=i.reduce((c,d)=>c+d.rate*d.weight,0)/s,l=i.reduce((c,d)=>c+d.weight*(d.rate-o)**2,0)/s;return{rate:o,stdDev:Math.sqrt(l)}}function rot(t){const e=t.reduce((s,o)=>s+Math.max(0,o.weight_used-(o.weight_used_baseline??0)),0);if(e===0)return null;const a=Date.now(),n=t.reduce((s,o)=>{const l=new Date(o.created_at).getTime();return lne.getAllUsageHistory(5e3),staleTime:6e4,enabled:o}),{data:j=[]}=$e({queryKey:["shopping-list"],queryFn:ne.getShoppingList,staleTime:3e4,enabled:o}),D=P?.forecast_global_lead_time_days??0,C=y.useMemo(()=>{const ce=new Map;for(const de of N)ce.set(Lw(de.material,de.subtype,de.brand),de);return ce},[N]),E=y.useMemo(()=>{const ce=new Map;for(const de of T){const oe=ce.get(de.spool_id)??[];oe.push(de),ce.set(de.spool_id,oe)}return ce},[T]),R=y.useMemo(()=>{const ce=new Map;for(const de of t){if(de.archived_at)continue;const oe=Lw(de.material,de.subtype,de.brand),K=ce.get(oe)??{key:oe,material:de.material,subtype:de.subtype,brand:de.brand,spools:[]};K.spools.push(de),ce.set(oe,K)}return[...ce.values()]},[t]),I=y.useMemo(()=>{const ce=new Date;return ce.setHours(0,0,0,0),R.map(de=>{const oe=C.get(de.key)??null,K=oe?.lead_time_days??0,ie=Math.max(D,K),ue=oe?.safety_margin_value??14,he=oe?.safety_margin_unit??"days",ge=de.spools.reduce((L,te)=>L+Math.max(0,te.label_weight-te.weight_used),0),q=de.spools.reduce((L,te)=>L+te.label_weight,0),Q=de.spools.reduce((L,te)=>L+Math.max(0,te.weight_used-(te.weight_used_baseline??0)),0),A=[];for(const L of de.spools)A.push(...E.get(L.id)??[]);let F=null,B=null,W="none";const H=aot(A);if(H!==null)F=H.rate,B=H.stdDev,W="history";else{const L=rot(de.spools);L!==null&&(F=L,W="delta")}const le=B??(F!==null?F*.2:0),U=tot*le*Math.sqrt(ie),G=he==="g"?ue:F!==null?F*ue:ue*5,Z=U+G,J=F!==null?F*ie+Z:0,re=F&&F>0?Math.floor(ge/F):null,se=re!==null?Km(ce,re):null,fe=F&&F>0?Math.floor((ge-J)/F):null,me=fe!==null?Km(ce,Math.max(0,fe)):null,pe=re!==null&&ie>0&&re<=ie,V=!pe&&fe!==null&&fe<=0;return{group:de,settings:oe,totalRemainingG:ge,totalLabelG:q,totalSpools:de.spools.length,totalUsedG:Q,dailyRateG:F,dailyRateStdDev:B,rateTier:W,effectiveLeadTimeDays:ie,safetyStockG:Z,reorderPointG:J,daysRemaining:re,daysUntilROP:fe,projectedEmptyDate:se,reorderTriggerDate:me,reorderAlert:V,stockBreakAlert:pe}})},[R,C,E,D]),O=y.useMemo(()=>{const ce=[...I];return ce.sort((de,oe)=>{let K=0,ie=0;switch(u){case"material":K=[de.group.material,de.group.subtype??"",de.group.brand??""].join(" ").toLowerCase(),ie=[oe.group.material,oe.group.subtype??"",oe.group.brand??""].join(" ").toLowerCase();break;case"used":K=de.totalUsedG,ie=oe.totalUsedG;break;case"days_left":K=de.daysRemaining??999999,ie=oe.daysRemaining??999999;break;case"stock":K=de.totalRemainingG,ie=oe.totalRemainingG;break}const ue=Kie?1:0;return p==="asc"?ue:-ue}),ce},[I,u,p]),z=y.useMemo(()=>I.filter(ce=>!ce.settings?.alerts_snoozed&&(ce.stockBreakAlert||ce.reorderAlert)),[I]),X=y.useMemo(()=>[...I].filter(ce=>ce.dailyRateG!==null).sort((ce,de)=>de.totalUsedG-ce.totalUsedG).slice(0,5),[I]);if(!o)return r.jsxs("div",{className:"flex flex-col items-center justify-center py-16 text-bambu-gray gap-3",children:[r.jsx(mc,{className:"w-8 h-8 opacity-40"}),r.jsx("p",{className:"text-sm",children:n("forecast.noReadAccess")})]});function ae(ce){u===ce?f(de=>de==="asc"?"desc":"asc"):(m(ce),f(ce==="days_left"?"asc":"desc"))}const Y=j.length>0?j.length:null;return r.jsxs("div",{className:"space-y-5",children:[r.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[z.length>0&&r.jsxs("button",{onClick:()=>d(ce=>!ce),className:`flex items-center gap-2 px-3 py-1.5 rounded-lg border text-sm font-medium transition-colors ${z.some(ce=>ce.stockBreakAlert)?"bg-red-500/15 border-red-500/30 text-red-300 hover:bg-red-500/25":"bg-yellow-500/15 border-yellow-500/30 text-yellow-300 hover:bg-yellow-500/25"}`,children:[r.jsx(xa,{className:"w-4 h-4"}),n("forecast.alertCount",{count:z.length}),c?r.jsx(el,{className:"w-3.5 h-3.5"}):r.jsx(za,{className:"w-3.5 h-3.5"})]}),l&&r.jsx(cot,{value:D,onSave:ce=>{ne.updateSettings({forecast_global_lead_time_days:ce}).then(()=>{e.invalidateQueries({queryKey:["settings"]}),a(n("forecast.globalLeadTimeSaved"),"success")})}}),r.jsxs("button",{onClick:()=>x(ce=>!ce),className:"relative flex items-center gap-2 px-3 py-1.5 rounded-lg border border-bambu-dark-tertiary text-bambu-gray hover:bg-bambu-dark-tertiary text-sm transition-colors ml-auto",children:[r.jsx(fb,{className:"w-4 h-4"}),r.jsx("span",{className:"hidden sm:inline",children:n("forecast.shoppingList")}),Y&&r.jsx("span",{className:"absolute -top-1.5 -right-1.5 w-4 h-4 rounded-full bg-bambu-green text-white text-[10px] font-bold flex items-center justify-center",children:Y})]})]}),c&&z.length>0&&r.jsx("div",{className:"space-y-2",children:z.map(ce=>r.jsx(sot,{forecast:ce,onCart:()=>v(ce)},ce.group.key))}),b&&r.jsx(pot,{items:j,forecasts:I,globalLeadTime:D,canWrite:l,onClose:()=>x(!1),onRemove:ce=>{ne.removeFromShoppingList(ce).then(()=>e.invalidateQueries({queryKey:["shopping-list"]})).catch(()=>a(n("forecast.failedSaveSettings"),"error"))},onClear:()=>{ne.clearShoppingList().then(()=>e.invalidateQueries({queryKey:["shopping-list"]})).catch(()=>a(n("forecast.failedSaveSettings"),"error"))}}),X.length>0&&r.jsx(lot,{forecasts:X,days:S,onDaysChange:k}),I.length===0?r.jsxs("div",{className:"flex flex-col items-center justify-center py-16 text-bambu-gray",children:[r.jsx(GS,{className:"w-10 h-10 mb-3 opacity-40"}),r.jsx("p",{className:"text-sm",children:n("forecast.noSpools")})]}):r.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg overflow-hidden border border-bambu-dark-tertiary",children:[r.jsx("div",{className:"overflow-x-auto",children:r.jsxs("table",{className:"w-full",children:[r.jsx("thead",{children:r.jsxs("tr",{className:"border-b border-bambu-dark-tertiary bg-bambu-dark-tertiary/30",children:[r.jsx("th",{className:"w-8 px-4 py-3"}),r.jsx(_P,{col:"material",active:u,dir:p,onSort:ae,children:n("forecast.sku")}),r.jsx(_P,{col:"stock",active:u,dir:p,onSort:ae,children:n("forecast.stock")}),r.jsx(_P,{col:"used",active:u,dir:p,onSort:ae,children:n("forecast.dailyRate")}),r.jsx(_P,{col:"days_left",active:u,dir:p,onSort:ae,children:n("forecast.daysLeft")}),r.jsx("th",{className:"px-4 py-3 text-left text-xs font-medium text-bambu-gray uppercase tracking-wide",children:n("forecast.emptyBy")}),r.jsx("th",{className:"px-4 py-3 text-left text-xs font-medium text-bambu-gray uppercase tracking-wide",children:n("forecast.reorderBy")}),r.jsx("th",{className:"w-24 px-4 py-3"})]})}),r.jsx("tbody",{className:"divide-y divide-bambu-dark-tertiary",children:O.map(ce=>r.jsx(dot,{forecast:ce,globalLeadTime:D,canWrite:l,onSaved:()=>e.invalidateQueries({queryKey:["sku-settings"]}),onCart:()=>v(ce),showToast:a},ce.group.key))})]})}),r.jsxs("div",{className:"flex flex-wrap items-center gap-4 px-4 py-3 text-xs text-bambu-gray border-t border-bambu-dark-tertiary bg-bambu-dark-tertiary/20",children:[r.jsxs("span",{className:"flex items-center gap-1.5",children:[r.jsx("span",{className:"w-2 h-2 rounded-full bg-bambu-green inline-block"}),n("forecast.trendLegend")]}),r.jsxs("span",{className:"flex items-center gap-1.5",children:[r.jsx("span",{className:"w-2 h-2 rounded-full bg-blue-400 inline-block"}),n("forecast.estimatedLegend")]}),r.jsxs("span",{className:"flex items-center gap-1.5",children:[r.jsx("span",{className:"w-2 h-2 rounded-full bg-bambu-gray/40 inline-block"}),n("forecast.noDataLegend")]})]})]}),g&&r.jsx(fot,{forecast:g,onClose:()=>v(null),onAdd:ce=>{ne.addToShoppingList(ce).then(()=>{e.invalidateQueries({queryKey:["shopping-list"]}),a(n("forecast.addedToCart"),"success"),v(null),x(!0)}).catch(()=>a(n("forecast.failedAddItem"),"error"))}})]})}function _P({col:t,active:e,dir:a,onSort:n,children:i}){const s=e===t;return r.jsx("th",{className:"px-4 py-3 text-left text-xs font-medium text-bambu-gray uppercase tracking-wide cursor-pointer select-none hover:text-white transition-colors",onClick:()=>n(t),children:r.jsxs("span",{className:"inline-flex items-center",children:[i,s?a==="asc"?r.jsx(Qm,{className:"w-3 h-3 ml-1 text-bambu-green"}):r.jsx(Xh,{className:"w-3 h-3 ml-1 text-bambu-green"}):r.jsx(ET,{className:"w-3 h-3 ml-1 opacity-40"})]})})}function sot({forecast:t,onCart:e}){const{t:a}=wt(),n=[t.group.brand,t.group.material,t.group.subtype].filter(Boolean).join(" "),i=t.stockBreakAlert;return r.jsxs("div",{className:`flex items-center gap-3 px-4 py-3 rounded-lg border text-sm ${i?"bg-red-500/10 border-red-500/30 text-red-300":"bg-yellow-500/10 border-yellow-500/30 text-yellow-300"}`,children:[r.jsx(xa,{className:"w-4 h-4 flex-shrink-0"}),r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsx("span",{className:"font-medium",children:n}),i?r.jsxs("span",{className:"ml-2 text-xs opacity-80",children:[a("forecast.stockBreakRisk")," — ",a("forecast.stockBreakDetail",{days:t.daysRemaining,lt:t.effectiveLeadTimeDays})]}):r.jsxs("span",{className:"ml-2 text-xs opacity-80",children:[a("forecast.reorderNow")," — ",a("forecast.reorderTriggerPassed",{date:t.reorderTriggerDate?ES(t.reorderTriggerDate):"—"})]})]}),r.jsxs("button",{onClick:e,className:"flex items-center gap-1.5 px-2.5 py-1 rounded border border-current text-xs opacity-70 hover:opacity-100 transition-opacity",children:[r.jsx(fb,{className:"w-3 h-3"})," ",a("forecast.order")]})]})}const oot=[{label:"1W",value:7},{label:"1M",value:30},{label:"6M",value:180}];function lot({forecasts:t,days:e,onDaysChange:a}){const{t:n}=wt(),i=Array.from({length:e+1},(u,m)=>m),s=t.map((u,m)=>({key:u.group.key,label:[u.group.brand,u.group.material,u.group.subtype].filter(Boolean).join(" "),color:WX[m%WX.length],rop:u.reorderPointG,points:not(u,e)})),o=i.map(u=>{const m={day:u,label:Rw(Km(new Date,u))};for(const p of s){const f=p.points.find(g=>g.day===u);m[p.key]=f?.stock??0}return m}),l=(()=>{for(let u=e;u>=0;u--)if(s.some(m=>o[u]?.[m.key]>0))return u;return e})(),c=o.slice(0,l+1),d=s.filter(u=>u.rop>0);return r.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg overflow-hidden border border-bambu-dark-tertiary p-4",children:[r.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[r.jsx(GS,{className:"w-4 h-4 text-bambu-green"}),r.jsx("h3",{className:"text-sm font-semibold text-white",children:n("forecast.chartTitle")}),r.jsx("span",{className:"text-xs text-bambu-gray ml-1 hidden sm:inline",children:n("forecast.dashedLinesROP")}),r.jsx("div",{className:"ml-auto flex items-center bg-bambu-dark-tertiary rounded-lg p-0.5",children:oot.map(u=>r.jsx("button",{onClick:()=>a(u.value),className:`px-2.5 py-1 text-xs font-medium rounded-md transition-colors ${e===u.value?"bg-bambu-dark-secondary text-white shadow":"text-bambu-gray hover:text-white"}`,children:u.label},u.value))})]}),r.jsx(ou,{width:"100%",height:220,children:r.jsxs(jB,{data:c,margin:{top:4,right:8,bottom:0,left:0},children:[r.jsx("defs",{children:s.map(u=>r.jsxs("linearGradient",{id:`grad-${u.key}`,x1:"0",y1:"0",x2:"0",y2:"1",children:[r.jsx("stop",{offset:"5%",stopColor:u.color,stopOpacity:.25}),r.jsx("stop",{offset:"95%",stopColor:u.color,stopOpacity:.02})]},u.key))}),r.jsx(Em,{strokeDasharray:"3 3",stroke:"#374151",strokeOpacity:.5}),r.jsx(Dm,{dataKey:"label",tick:{fill:"#6B7280",fontSize:10},interval:Math.max(0,Math.ceil(l/8)-1),axisLine:!1,tickLine:!1}),r.jsx(Fm,{tick:{fill:"#6B7280",fontSize:10},axisLine:!1,tickLine:!1,tickFormatter:u=>u>=1e3?`${(u/1e3).toFixed(1)}kg`:`${u}g`,width:48}),r.jsx(cu,{contentStyle:{background:"#1a1a2e",border:"1px solid #374151",borderRadius:8,fontSize:12},labelStyle:{color:"#9CA3AF"},itemStyle:{color:"#E5E7EB"},formatter:(u,m)=>{if(typeof u!="number")return"";const p=s.find(f=>f.key===String(m));return`${u}g — ${p?.label??m}`}}),r.jsx(e4,{formatter:u=>{const m=s.find(p=>p.key===u);return r.jsx("span",{style:{color:"#9CA3AF",fontSize:11},children:m?.label??u})}}),s.map(u=>r.jsx(KA,{type:"monotone",dataKey:u.key,stroke:u.color,strokeWidth:2,fill:`url(#grad-${u.key})`,dot:!1,activeDot:{r:3}},u.key)),d.map(u=>r.jsx(du,{y:u.rop,stroke:u.color,strokeDasharray:"4 3",strokeOpacity:.6},`rop-${u.key}`))]})})]})}function cot({value:t,onSave:e}){const{t:a}=wt(),[n,i]=y.useState(!1),[s,o]=y.useState(String(t));function l(){const c=parseInt(s,10);isNaN(c)||c<0||(e(c),i(!1))}return r.jsxs("div",{className:"flex items-center gap-2 px-3 py-1.5 bg-bambu-dark-tertiary/40 rounded-lg border border-bambu-dark-tertiary text-xs text-bambu-gray",children:[r.jsx(yi,{className:"w-3.5 h-3.5 flex-shrink-0","aria-label":a("forecast.globalLeadTimeHint")}),r.jsxs("span",{className:"hidden sm:inline",children:[a("forecast.globalLeadTime"),":"]}),n?r.jsxs("form",{className:"flex items-center gap-1.5",onSubmit:c=>{c.preventDefault(),l()},children:[r.jsx("input",{type:"number",min:0,max:365,value:s,onChange:c=>o(c.target.value),className:"w-14 px-1.5 py-0.5 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-sm text-white focus:outline-none focus:border-bambu-green",autoFocus:!0}),r.jsx("span",{className:"text-bambu-gray",children:"d"}),r.jsx("button",{type:"submit",className:"px-2 py-0.5 bg-bambu-green text-white text-xs rounded hover:bg-bambu-green/80",children:a("forecast.save")}),r.jsx("button",{type:"button",onClick:()=>i(!1),className:"text-xs text-bambu-gray hover:text-white",children:"✕"})]}):r.jsxs("div",{className:"flex items-center gap-1.5",children:[r.jsxs("span",{className:"font-semibold text-white",children:[t,"d"]}),r.jsx("button",{onClick:()=>{o(String(t)),i(!0)},className:"p-0.5 text-bambu-gray hover:text-white rounded transition-colors",children:r.jsx(vc,{className:"w-3 h-3"})})]})]})}function dot({forecast:t,globalLeadTime:e,canWrite:a,onSaved:n,onCart:i,showToast:s}){const{t:o}=wt(),[l,c]=y.useState(!1),[d,u]=y.useState(!1),[m,p]=y.useState(!1),[f,g]=y.useState(String(t.settings?.lead_time_days??0)),[v,b]=y.useState(String(t.settings?.safety_margin_value??14)),[x,S]=y.useState(t.settings?.safety_margin_unit??"days");y.useEffect(()=>{d||g(String(t.settings?.lead_time_days??0))},[t.settings?.lead_time_days,d]),y.useEffect(()=>{m||(b(String(t.settings?.safety_margin_value??14)),S(t.settings?.safety_margin_unit??"days"))},[t.settings?.safety_margin_value,t.settings?.safety_margin_unit,m]);const k=rt({mutationFn:ne.upsertSkuSettings,onSuccess:()=>{n(),s(o("forecast.settingsSaved"),"success")},onError:()=>s(o("forecast.failedSaveSettings"),"error")}),P=t.settings?.alerts_snoozed??!1,N=[t.group.brand,t.group.material,t.group.subtype].filter(Boolean).join(" "),T=t.group.spools[0]?.rgba?al(t.group.spools[0].rgba):{backgroundColor:"#4B5563"},j=t.totalLabelG>0?Math.round(t.totalRemainingG/t.totalLabelG*100):0,D=P||t.daysRemaining===null?"text-bambu-gray":t.stockBreakAlert?"text-red-400":t.reorderAlert||t.daysRemaining<30?"text-yellow-400":"text-green-400";function C(O,z,X,ae=P){k.mutate({material:t.group.material,subtype:t.group.subtype,brand:t.group.brand,lead_time_days:O,safety_margin_value:z,safety_margin_unit:X,alerts_snoozed:ae})}function E(O){O.stopPropagation(),C(t.settings?.lead_time_days??0,t.settings?.safety_margin_value??14,t.settings?.safety_margin_unit??"days",!P)}const R=t.rateTier==="history"?r.jsxs("span",{className:"inline-flex items-center gap-1 text-xs px-1.5 py-0.5 rounded bg-bambu-green/15 text-bambu-green",children:[r.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-bambu-green"}),o("forecast.trend")]}):t.rateTier==="delta"?r.jsxs("span",{className:"inline-flex items-center gap-1 text-xs px-1.5 py-0.5 rounded bg-blue-400/15 text-blue-400",children:[r.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-blue-400"}),o("forecast.estimated")]}):r.jsxs("span",{className:"inline-flex items-center gap-1 text-xs px-1.5 py-0.5 rounded bg-bambu-dark-tertiary text-bambu-gray/60",children:[r.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-bambu-gray/40"}),o("forecast.noData")]}),I=P?"":t.stockBreakAlert?"bg-red-500/5":t.reorderAlert?"bg-yellow-500/5":"";return r.jsxs(r.Fragment,{children:[r.jsxs("tr",{className:`cursor-pointer hover:bg-bambu-dark-tertiary/40 transition-colors ${I} ${P?"opacity-50":""}`,onClick:()=>c(O=>!O),children:[r.jsx("td",{className:"px-4 py-3",children:r.jsx("span",{className:"block w-3 h-3 rounded-full border border-black/20",style:T})}),r.jsxs("td",{className:"px-4 py-3",children:[r.jsx("div",{className:"text-sm font-medium text-white",children:N}),r.jsx("div",{className:"text-xs text-bambu-gray",children:o("forecast.spoolCount",{count:t.totalSpools})})]}),r.jsxs("td",{className:"px-4 py-3 min-w-[120px]",children:[r.jsx("div",{className:"h-1.5 bg-bambu-dark-tertiary rounded-full overflow-hidden mb-1 w-24",children:r.jsx("div",{className:`h-full rounded-full ${j>50?"bg-bambu-green":j>20?"bg-yellow-500":"bg-red-500"}`,style:{width:`${Math.min(j,100)}%`}})}),r.jsxs("span",{className:"text-xs text-bambu-gray",children:[Math.round(t.totalRemainingG),"g"]})]}),r.jsxs("td",{className:"px-4 py-3",children:[r.jsx("div",{className:"text-sm text-white",children:t.dailyRateG!==null?`${t.dailyRateG.toFixed(1)}g/d`:"—"}),r.jsx("div",{className:"mt-0.5",children:R})]}),r.jsx("td",{className:"px-4 py-3",children:r.jsx("span",{className:`text-sm font-semibold ${D}`,children:t.daysRemaining!==null?`${t.daysRemaining}d`:r.jsx("span",{className:"text-bambu-gray font-normal",children:"—"})})}),r.jsx("td",{className:"px-4 py-3",children:r.jsx("span",{className:"text-sm text-bambu-gray",children:t.projectedEmptyDate?ES(t.projectedEmptyDate):"—"})}),r.jsx("td",{className:"px-4 py-3",children:r.jsx("span",{className:`text-sm font-medium ${!P&&t.reorderAlert?"text-yellow-400":"text-bambu-gray"}`,children:t.reorderTriggerDate?ES(t.reorderTriggerDate):"—"})}),r.jsx("td",{className:"px-4 py-3",onClick:O=>O.stopPropagation(),children:r.jsxs("div",{className:"flex items-center justify-end gap-1",children:[a&&r.jsx("button",{onClick:i,className:"p-1.5 text-bambu-gray hover:text-bambu-green rounded transition-colors",title:o("forecast.addToCart"),children:r.jsx(fb,{className:"w-4 h-4"})}),!P&&(t.stockBreakAlert?r.jsx(xa,{className:"w-4 h-4 text-red-400","aria-label":o("forecast.stockBreakRisk")}):t.reorderAlert?r.jsx(xa,{className:"w-4 h-4 text-yellow-400","aria-label":o("forecast.reorderNow")}):t.daysRemaining!==null?r.jsx(_r,{className:"w-4 h-4 text-bambu-green/50"}):null),a&&r.jsx("button",{onClick:E,className:`p-1 rounded transition-colors ${P?"text-bambu-gray/70 hover:text-white":"text-bambu-dark-tertiary hover:text-bambu-gray"}`,title:o(P?"forecast.alertsEnabled":"forecast.alertsSnoozed"),children:r.jsx(aJ,{className:"w-3.5 h-3.5"})}),r.jsx("button",{onClick:O=>{O.stopPropagation(),c(z=>!z)},className:"p-1.5 text-bambu-gray hover:text-white rounded transition-colors",children:l?r.jsx(el,{className:"w-4 h-4"}):r.jsx(za,{className:"w-4 h-4"})})]})})]}),l&&r.jsx("tr",{className:"bg-bambu-dark-tertiary/10",children:r.jsx("td",{colSpan:8,className:"px-6 py-4",children:r.jsxs("div",{className:"space-y-4",children:[r.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[r.jsx(LL,{label:o("forecast.effectiveLeadTime"),value:`${t.effectiveLeadTimeDays}d`,hint:o("forecast.effectiveLeadTimeHint",{global:e,sku:t.settings?.lead_time_days??0})}),r.jsx(LL,{label:o("forecast.safetyMarginLabel"),value:`${Math.round(t.safetyStockG)}g`,hint:o("forecast.safetyMarginHint")}),r.jsx(LL,{label:o("forecast.reorderPoint"),value:`${Math.round(t.reorderPointG)}g`,hint:o("forecast.reorderPointHint")})]}),a&&r.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[r.jsx(uot,{label:o("forecast.skuLeadTimeOverride"),hint:o("forecast.skuLeadTimeHint"),unit:o("forecast.leadTime"),editing:d,value:t.settings?.lead_time_days??0,inputValue:f,onInputChange:g,onEdit:()=>{g(String(t.settings?.lead_time_days??0)),u(!0)},onSave:()=>{const O=parseInt(f,10);!isNaN(O)&&O>=0&&(C(O,t.settings?.safety_margin_value??14,x),u(!1))},onCancel:()=>u(!1),isPending:k.isPending,saveLabel:o("forecast.save"),cancelLabel:o("forecast.cancel")}),r.jsx(mot,{value:t.settings?.safety_margin_value??14,unit:x,editing:m,inputValue:v,dailyRateG:t.dailyRateG,onInputChange:b,onUnitChange:O=>S(O),onEdit:()=>{b(String(t.settings?.safety_margin_value??14)),S(t.settings?.safety_margin_unit??"days"),p(!0)},onSave:()=>{const O=parseInt(v,10);!isNaN(O)&&O>=0&&(C(t.settings?.lead_time_days??0,O,x),p(!1))},onCancel:()=>p(!1),isPending:k.isPending,saveLabel:o("forecast.save"),cancelLabel:o("forecast.cancel"),safetyMarginLabel:o("forecast.safetyMarginLabel")})]}),t.group.spools.length>1&&r.jsxs("div",{className:"border-t border-bambu-dark-tertiary pt-3",children:[r.jsx("p",{className:"text-xs text-bambu-gray mb-2",children:o("forecast.individualSpools")}),r.jsx("div",{className:"bg-bambu-dark-secondary rounded-lg overflow-hidden border border-bambu-dark-tertiary",children:r.jsxs("table",{className:"w-full",children:[r.jsx("thead",{children:r.jsxs("tr",{className:"border-b border-bambu-dark-tertiary bg-bambu-dark-tertiary/30",children:[r.jsx("th",{className:"px-4 py-2 text-left text-xs font-medium text-bambu-gray uppercase tracking-wide",children:"#"}),r.jsx("th",{className:"px-4 py-2 text-left text-xs font-medium text-bambu-gray uppercase tracking-wide",children:o("inventory.remaining")}),r.jsx("th",{className:"px-4 py-2 text-left text-xs font-medium text-bambu-gray uppercase tracking-wide",children:o("inventory.used")}),r.jsx("th",{className:"px-4 py-2 text-left text-xs font-medium text-bambu-gray uppercase tracking-wide",children:o("forecast.labelWeight")})]})}),r.jsx("tbody",{className:"divide-y divide-bambu-dark-tertiary",children:t.group.spools.map(O=>{const z=Math.max(0,O.label_weight-O.weight_used),X=O.label_weight>0?z/O.label_weight*100:0;return r.jsxs("tr",{className:"hover:bg-bambu-dark-tertiary/30 transition-colors",children:[r.jsx("td",{className:"px-4 py-2",children:r.jsxs("span",{className:"text-xs font-mono text-bambu-gray/70",children:["#",O.id]})}),r.jsx("td",{className:"px-4 py-2",children:r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("div",{className:"w-24 h-1.5 bg-bambu-dark-tertiary rounded-full overflow-hidden flex-shrink-0",children:r.jsx("div",{className:`h-full rounded-full ${X>50?"bg-bambu-green":X>20?"bg-yellow-500":"bg-red-500"}`,style:{width:`${Math.min(X,100)}%`}})}),r.jsxs("span",{className:"text-sm text-white",children:[Math.round(z),"g"]})]})}),r.jsx("td",{className:"px-4 py-2",children:r.jsxs("span",{className:"text-sm text-bambu-gray",children:[Math.round(Math.max(0,O.weight_used-(O.weight_used_baseline??0))),"g"]})}),r.jsx("td",{className:"px-4 py-2",children:r.jsxs("span",{className:"text-sm text-bambu-gray",children:[O.label_weight,"g"]})})]},O.id)})})]})})]})]})})})]})}function LL({label:t,value:e,hint:a}){return r.jsxs("div",{className:"bg-bambu-dark-tertiary/40 rounded-lg p-3",title:a,children:[r.jsx("div",{className:"text-xs text-bambu-gray mb-1",children:t}),r.jsx("div",{className:"text-lg font-semibold text-white",children:e})]})}function uot({label:t,hint:e,unit:a,editing:n,value:i,inputValue:s,onInputChange:o,onEdit:l,onSave:c,onCancel:d,isPending:u,saveLabel:m="Save",cancelLabel:p="Cancel"}){return r.jsxs("div",{className:"bg-bambu-dark-tertiary/40 rounded-lg p-3 space-y-1",children:[r.jsxs("div",{className:"flex items-center gap-1.5",children:[r.jsx("span",{className:"text-xs font-medium text-white",children:t}),r.jsx("span",{title:e,children:r.jsx(yi,{className:"w-3 h-3 text-bambu-gray/50"})})]}),n?r.jsxs("form",{className:"flex items-center gap-2",onSubmit:f=>{f.preventDefault(),c()},children:[r.jsx("input",{type:"number",min:0,max:365,value:s,onChange:f=>o(f.target.value),className:"w-20 px-2 py-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-sm text-white focus:outline-none focus:border-bambu-green",autoFocus:!0,disabled:u}),r.jsx("span",{className:"text-xs text-bambu-gray",children:a}),r.jsx("button",{type:"submit",disabled:u,className:"px-2 py-1 bg-bambu-green text-white text-xs rounded hover:bg-bambu-green/80 disabled:opacity-50",children:m}),r.jsx("button",{type:"button",onClick:d,disabled:u,className:"px-2 py-1 text-xs text-bambu-gray hover:text-white",children:p})]}):r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("span",{className:"text-lg font-semibold text-white",children:i}),r.jsx("span",{className:"text-xs text-bambu-gray",children:a}),r.jsx("button",{onClick:l,className:"p-1 text-bambu-gray hover:text-white rounded transition-colors",children:r.jsx(vc,{className:"w-3 h-3"})})]})]})}function mot({value:t,unit:e,editing:a,inputValue:n,dailyRateG:i,onInputChange:s,onUnitChange:o,onEdit:l,onSave:c,onCancel:d,isPending:u,saveLabel:m="Save",cancelLabel:p="Cancel",safetyMarginLabel:f="Safety Margin"}){const{t:g}=wt(),v=e==="g"?t:i!==null?Math.round(i*t):null,b=e==="days"?g("forecast.safetyMarginHintDays",{approx:v!==null?g("forecast.safetyMarginHintDaysApprox",{g:v}):""}):g("forecast.safetyMarginHintG",{approx:i!==null?g("forecast.safetyMarginHintGApprox",{days:Math.round(t/i)}):""});return r.jsxs("div",{className:"bg-bambu-dark-tertiary/40 rounded-lg p-3 space-y-1",children:[r.jsxs("div",{className:"flex items-center gap-1.5",children:[r.jsx("span",{className:"text-xs font-medium text-white",children:f}),r.jsx("span",{title:b,children:r.jsx(yi,{className:"w-3 h-3 text-bambu-gray/50"})})]}),a?r.jsxs("form",{className:"flex items-center gap-2 flex-wrap",onSubmit:x=>{x.preventDefault(),c()},children:[r.jsx("input",{type:"number",min:0,max:e==="g"?1e4:365,value:n,onChange:x=>s(x.target.value),className:"w-20 px-2 py-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-sm text-white focus:outline-none focus:border-bambu-green",autoFocus:!0,disabled:u}),r.jsxs("div",{className:"flex bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded overflow-hidden text-xs",children:[r.jsx("button",{type:"button",onClick:()=>o("days"),className:`px-2 py-1 transition-colors ${e==="days"?"bg-bambu-green text-white":"text-bambu-gray hover:text-white"}`,children:"days"}),r.jsx("button",{type:"button",onClick:()=>o("g"),className:`px-2 py-1 transition-colors ${e==="g"?"bg-bambu-green text-white":"text-bambu-gray hover:text-white"}`,children:"g"})]}),r.jsx("button",{type:"submit",disabled:u,className:"px-2 py-1 bg-bambu-green text-white text-xs rounded hover:bg-bambu-green/80 disabled:opacity-50",children:m}),r.jsx("button",{type:"button",onClick:d,disabled:u,className:"px-2 py-1 text-xs text-bambu-gray hover:text-white",children:p})]}):r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("span",{className:"text-lg font-semibold text-white",children:t}),r.jsx("span",{className:"text-xs text-bambu-gray",children:e}),v!==null&&e==="days"&&r.jsxs("span",{className:"text-xs text-bambu-gray/60",children:["≈ ",v,"g"]}),e==="g"&&i!==null&&r.jsxs("span",{className:"text-xs text-bambu-gray/60",children:["≈ ",Math.round(t/i),"d"]}),r.jsx("button",{onClick:l,className:"p-1 text-bambu-gray hover:text-white rounded transition-colors",children:r.jsx(vc,{className:"w-3 h-3"})})]})]})}function pot({items:t,forecasts:e,globalLeadTime:a,canWrite:n,onClose:i,onRemove:s,onClear:o}){const{t:l}=wt(),c=ia(),[d,u]=y.useState("list"),m=rt({mutationFn:async({id:b,status:x,item:S,avgSpoolG:k})=>{if(await ne.updateShoppingListStatus(b,x),x==="received"&&S){const P=k??1e3,N={material:S.material,subtype:S.subtype,brand:S.brand,label_weight:P,core_weight:0,core_weight_catalog_id:null,color_name:null,rgba:null,extra_colors:null,effect_type:null,nozzle_temp_min:null,nozzle_temp_max:null,note:S.note??null,tag_uid:null,tray_uuid:null,data_origin:"manual",tag_type:null,cost_per_kg:null,last_scale_weight:null,last_weighed_at:null,weight_used:0,slicer_filament:null,slicer_filament_name:null,added_full:null,last_used:null,encode_time:null,category:"Stock",low_stock_threshold_pct:null};await ne.bulkCreateSpools(N,S.quantity_spools),await ne.removeFromShoppingList(b)}},onSuccess:()=>{c.invalidateQueries({queryKey:["shopping-list"]}),c.invalidateQueries({queryKey:["spools"]})}}),p=y.useMemo(()=>{const b=new Map;for(const x of e)b.set(x.group.key,x);return b},[e]),f=y.useMemo(()=>t.map(b=>({item:b,forecast:p.get(Lw(b.material,b.subtype,b.brand))??null})),[t,p]),g=y.useMemo(()=>f.filter(({forecast:b})=>!b||b.dailyRateG===null?!1:b.stockBreakAlert||b.daysRemaining!==null&&b.daysRemaining<=b.effectiveLeadTimeDays),[f]);function v(){const b=[l("forecast.qty"),l("forecast.material"),"Brand","Subtype",`${l("forecast.weight")} (g)`,`${l("forecast.leadTime")} (d)`,l("forecast.expectedRestock"),l("forecast.status"),l("forecast.note")],x=t.map(T=>{const j=p.get(Lw(T.material,T.subtype,T.brand))??null,D=j&&j.totalSpools>0?j.totalLabelG/j.totalSpools:1e3,C=Math.round(T.quantity_spools*D),E=j?.effectiveLeadTimeDays??a??0,R=E>0?ES(Km(new Date,E)):"";return[T.quantity_spools,T.material,T.brand??"",T.subtype??"",C,E||"",R,T.status,T.note??""].map(I=>`"${String(I).replace(/"/g,'""')}"`).join(",")}),S=[b.join(","),...x].join(`
`),k=new Blob([S],{type:"text/csv"}),P=URL.createObjectURL(k),N=document.createElement("a");N.href=P,N.download=`shopping-list-${new Date().toISOString().slice(0,10)}.csv`,N.click(),setTimeout(()=>URL.revokeObjectURL(P),100)}return r.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg overflow-hidden border border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"flex items-center justify-between px-4 py-3 border-b border-bambu-dark-tertiary bg-bambu-dark-tertiary/30",children:[r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx(fb,{className:"w-4 h-4 text-bambu-green"}),r.jsx("h3",{className:"text-sm font-semibold text-white",children:l("forecast.shoppingList")}),r.jsx("span",{className:"text-xs text-bambu-gray",children:l("forecast.shoppingListItems",{count:t.length})}),t.length>0&&r.jsxs("div",{className:"flex bg-bambu-dark-tertiary rounded-md p-0.5 ml-1",children:[r.jsxs("button",{onClick:()=>u("list"),className:`flex items-center gap-1.5 px-2 py-0.5 text-xs font-medium rounded transition-colors ${d==="list"?"bg-bambu-dark-secondary text-white shadow":"text-bambu-gray hover:text-white"}`,children:[r.jsx(en,{className:"w-3 h-3"}),l("forecast.listView")]}),r.jsxs("button",{onClick:()=>u("logistics"),className:`flex items-center gap-1.5 px-2 py-0.5 text-xs font-medium rounded transition-colors ${d==="logistics"?"bg-bambu-dark-secondary text-white shadow":"text-bambu-gray hover:text-white"}`,children:[r.jsx(Fge,{className:"w-3 h-3"}),l("forecast.logisticsView"),g.length>0&&r.jsx("span",{className:"w-3.5 h-3.5 rounded-full bg-red-500 text-white text-[9px] font-bold flex items-center justify-center",children:g.length})]})]})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[t.length>0&&r.jsxs(r.Fragment,{children:[r.jsxs("button",{onClick:v,className:"flex items-center gap-1.5 text-xs text-bambu-gray hover:text-white transition-colors px-2 py-1 rounded border border-bambu-dark-tertiary hover:bg-bambu-dark-tertiary",children:[r.jsx(Ur,{className:"w-3 h-3"}),l("forecast.downloadCsv")]}),n&&r.jsx("button",{onClick:o,className:"text-xs text-red-400 hover:text-red-300 transition-colors px-2 py-1 rounded border border-red-500/20 hover:bg-red-500/10",children:l("forecast.clearAll")})]}),r.jsx("button",{onClick:i,className:"p-1 text-bambu-gray hover:text-white transition-colors",children:r.jsx(Ht,{className:"w-4 h-4"})})]})]}),t.length===0?r.jsxs("div",{className:"flex flex-col items-center py-8 text-bambu-gray",children:[r.jsx(en,{className:"w-8 h-8 mb-2 opacity-30"}),r.jsx("p",{className:"text-sm",children:l("forecast.shoppingListEmpty")})]}):d==="list"?r.jsx("div",{className:"overflow-x-auto",children:r.jsxs("table",{className:"w-full",children:[r.jsx("thead",{children:r.jsxs("tr",{className:"border-b border-bambu-dark-tertiary bg-bambu-dark-tertiary/20",children:[r.jsx("th",{className:"px-4 py-2 text-left text-xs font-medium text-bambu-gray uppercase tracking-wide",children:l("forecast.qty")}),r.jsx("th",{className:"px-4 py-2 text-left text-xs font-medium text-bambu-gray uppercase tracking-wide",children:l("forecast.material")}),r.jsx("th",{className:"px-4 py-2 text-left text-xs font-medium text-bambu-gray uppercase tracking-wide",children:l("forecast.weight")}),r.jsx("th",{className:"px-4 py-2 text-left text-xs font-medium text-bambu-gray uppercase tracking-wide",children:l("forecast.leadTime")}),r.jsx("th",{className:"px-4 py-2 text-left text-xs font-medium text-bambu-gray uppercase tracking-wide",children:l("forecast.expectedRestock")}),r.jsx("th",{className:"px-4 py-2 text-left text-xs font-medium text-bambu-gray uppercase tracking-wide",children:l("forecast.status")}),r.jsx("th",{className:"px-4 py-2 text-left text-xs font-medium text-bambu-gray uppercase tracking-wide",children:l("forecast.note")}),r.jsx("th",{className:"px-4 py-2 text-right text-xs font-medium text-bambu-gray uppercase tracking-wide",children:l("forecast.actions")})]})}),r.jsx("tbody",{className:"divide-y divide-bambu-dark-tertiary",children:t.map(b=>{const x=[b.brand,b.material,b.subtype].filter(Boolean).join(" "),S=g.some(R=>R.item.id===b.id),k=p.get(Lw(b.material,b.subtype,b.brand))??null,P=k&&k.totalSpools>0?k.totalLabelG/k.totalSpools:1e3,N=Math.round(b.quantity_spools*P),T=k?.effectiveLeadTimeDays??a??0,j=T>0?Km(new Date,T):null,D=b.status==="purchased"||b.status==="received",C=b.status==="received",E=m.isPending;return r.jsxs("tr",{className:`hover:bg-bambu-dark-tertiary/30 transition-colors ${S&&!D?"bg-red-500/5":""}`,children:[r.jsx("td",{className:"px-4 py-2.5",children:r.jsxs("span",{className:"text-sm font-semibold text-bambu-green",children:[b.quantity_spools,"×"]})}),r.jsx("td",{className:"px-4 py-2.5",children:r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("span",{className:"text-sm text-white",children:x}),S&&!D&&r.jsx(xa,{className:"w-3.5 h-3.5 text-red-400 flex-shrink-0","aria-label":l("forecast.stockBreakBefore")})]})}),r.jsx("td",{className:"px-4 py-2.5",children:r.jsx("span",{className:"text-sm text-white",children:N>=1e3?`${(N/1e3).toFixed(1)}kg`:`${N}g`})}),r.jsx("td",{className:"px-4 py-2.5",children:r.jsx("span",{className:"text-sm text-bambu-gray",children:T>0?`${T}d`:"—"})}),r.jsx("td",{className:"px-4 py-2.5",children:r.jsx("span",{className:"text-sm text-bambu-gray",children:j?ES(j):"—"})}),r.jsx("td",{className:"px-4 py-2.5",children:r.jsx("span",{className:`inline-flex items-center px-2 py-0.5 rounded text-xs font-medium ${C?"bg-bambu-green/20 text-bambu-green":D?"bg-blue-400/20 text-blue-400":"bg-bambu-dark-tertiary text-bambu-gray"}`,children:l(C?"forecast.received":D?"forecast.purchased":"forecast.pending")})}),r.jsx("td",{className:"px-4 py-2.5",children:r.jsx("span",{className:"text-xs text-bambu-gray",children:b.note||"—"})}),r.jsx("td",{className:"px-4 py-2.5",children:r.jsx("div",{className:"flex items-center justify-end gap-1",children:n&&r.jsxs(r.Fragment,{children:[r.jsx("button",{onClick:()=>m.mutate({id:b.id,status:D?"pending":"purchased"}),disabled:E||C,title:l(D?"forecast.resetToPending":"forecast.markPurchased"),className:`p-1 rounded transition-colors disabled:opacity-30 ${D?"text-blue-400 hover:text-bambu-gray":"text-bambu-gray hover:text-blue-400"}`,children:D?r.jsx(bs,{className:"w-3.5 h-3.5"}):r.jsx(wbe,{className:"w-3.5 h-3.5"})}),r.jsx("button",{onClick:()=>m.mutate({id:b.id,status:"received",item:b,avgSpoolG:P}),disabled:E||!D||C,title:l("forecast.markReceived"),className:"p-1 rounded transition-colors text-bambu-gray hover:text-bambu-green disabled:opacity-30",children:r.jsx(Cye,{className:"w-3.5 h-3.5"})}),r.jsx("button",{onClick:()=>s(b.id),className:"p-1 text-bambu-gray hover:text-red-400 transition-colors",title:l("forecast.remove"),children:r.jsx(na,{className:"w-3.5 h-3.5"})})]})})})]},b.id)})})]})}):r.jsx("div",{className:"divide-y divide-bambu-dark-tertiary",children:f.filter(({item:b})=>b.status!=="received").map(({item:b,forecast:x})=>r.jsx(hot,{item:b,forecast:x,globalLeadTime:a,canWrite:n,onRemove:()=>s(b.id)},b.id))})]})}function hot({item:t,forecast:e,globalLeadTime:a,canWrite:n,onRemove:i}){const{t:s}=wt(),o=[t.brand,t.material,t.subtype].filter(Boolean).join(" "),l=y.useMemo(()=>{if(!e||e.dailyRateG===null||e.dailyRateG<=0)return null;const u=e.dailyRateG,m=e.effectiveLeadTimeDays,p=e.totalSpools>0?e.totalLabelG/e.totalSpools:1e3,f=t.quantity_spools*p,g=Math.max(0,e.totalRemainingG-u*m),v=g+f,b=Math.ceil(v/u),x=Math.min(m+b+5,365),S=[];for(let k=0;k<=x;k++){const P=Rw(Km(new Date,k));if(k===m)S.push({day:k,label:P,stock:Math.round(g),rop:Math.round(e.reorderPointG),safetyStock:Math.round(e.safetyStockG)}),S.push({day:k,label:P,stock:Math.round(v),rop:Math.round(e.reorderPointG),safetyStock:Math.round(e.safetyStockG),arrival:!0});else{const N=k{if(!e||e.dailyRateG===null||e.dailyRateG<=0)return null;const u=Math.floor(e.totalRemainingG/e.dailyRateG);return uu>=1e3?`${(u/1e3).toFixed(1)}kg`:`${u}g`,width:44}),r.jsx(cu,{contentStyle:{background:"#1a1a2e",border:"1px solid #374151",borderRadius:8,fontSize:11},labelStyle:{color:"#9CA3AF"},formatter:(u,m)=>typeof u!="number"?"":m==="stock"?`${u}g — ${s("forecast.stock")}`:m==="rop"?`${u}g — ${s("forecast.reorderPoint")}`:m==="safetyStock"?`${u}g — ${s("forecast.safetyMarginLabel")}`:`${u}`}),r.jsx(KA,{type:"linear",dataKey:"stock",stroke:"#1DB954",strokeWidth:2,fill:`url(#cart-post-${t.id})`,dot:!1,activeDot:{r:3}}),e.reorderPointG>0&&r.jsx(du,{y:e.reorderPointG,stroke:"#F59E0B",strokeDasharray:"5 3",strokeOpacity:.8,label:{value:"ROP",position:"insideTopRight",fill:"#F59E0B",fontSize:9}}),e.safetyStockG>0&&r.jsx(du,{y:e.safetyStockG,stroke:"#6B7280",strokeDasharray:"3 3",strokeOpacity:.6,label:{value:"SS",position:"insideTopRight",fill:"#6B7280",fontSize:9}}),r.jsx(du,{x:Rw(Km(new Date,l.lt)),stroke:"#3B82F6",strokeWidth:1.5,strokeDasharray:"4 3",strokeOpacity:.9,label:{value:`+${l.arrivalG>=1e3?`${(l.arrivalG/1e3).toFixed(1)}kg`:`${Math.round(l.arrivalG)}g`} arrives (d${l.lt})`,position:"insideTopLeft",fill:"#3B82F6",fontSize:9}}),c!==null&&r.jsx(du,{x:Rw(Km(new Date,c)),stroke:"#EF4444",strokeWidth:1.5,strokeOpacity:.9,label:{value:"OUT",position:"insideTopLeft",fill:"#EF4444",fontSize:9}})]})}),r.jsxs("div",{className:"flex flex-wrap items-center gap-3 mt-2 text-[10px] text-bambu-gray",children:[r.jsxs("span",{className:"flex items-center gap-1",children:[r.jsx("span",{className:"inline-block w-4 border-t-2 border-yellow-400 border-dashed"})," ",s("forecast.ropLabel")]}),r.jsxs("span",{className:"flex items-center gap-1",children:[r.jsx("span",{className:"inline-block w-4 border-t border-bambu-gray border-dashed"})," ",s("forecast.safetyStockLegend")]}),r.jsxs("span",{className:"flex items-center gap-1",children:[r.jsx("span",{className:"inline-block w-4 border-t-2 border-blue-400 border-dashed"})," ",s("forecast.stockArrivalLegend")]}),d&&r.jsxs("span",{className:"flex items-center gap-1 text-red-400",children:[r.jsx("span",{className:"inline-block w-4 border-t-2 border-red-400"})," ",s("forecast.stockoutLegend")]})]})]}):null]})}function fot({forecast:t,onClose:e,onAdd:a}){const{t:n}=wt(),i=[t.group.brand,t.group.material,t.group.subtype].filter(Boolean).join(" "),[s,o]=y.useState("qty"),[l,c]=y.useState("1"),[d,u]=y.useState("30"),[m,p]=y.useState(""),f=y.useMemo(()=>{if(!t.dailyRateG||t.dailyRateG<=0)return null;const b=t.dailyRateG*Number(d),x=t.group.spools.length>0?t.group.spools.reduce((S,k)=>S+k.label_weight,0)/t.group.spools.length:1e3;return Math.ceil(b/x)},[t,d]),g=s==="qty"?parseInt(l,10)||1:f??1;function v(b){b.preventDefault(),a({material:t.group.material,subtype:t.group.subtype,brand:t.group.brand,quantity_spools:g,note:m||null})}return r.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm p-4",children:r.jsxs("div",{className:"bg-bambu-dark-secondary rounded-2xl border border-bambu-dark-tertiary w-full max-w-sm shadow-2xl",children:[r.jsxs("div",{className:"flex items-center justify-between px-5 pt-5 pb-4 border-b border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(fb,{className:"w-5 h-5 text-bambu-green"}),r.jsx("h2",{className:"text-base font-semibold text-white",children:n("forecast.addToCartTitle")})]}),r.jsx("button",{onClick:e,className:"p-1 text-bambu-gray hover:text-white transition-colors",children:r.jsx(Ht,{className:"w-5 h-5"})})]}),r.jsxs("form",{onSubmit:v,className:"p-5 space-y-4",children:[r.jsx("div",{className:"text-sm text-bambu-gray",children:i}),r.jsxs("div",{className:"flex bg-bambu-dark-tertiary rounded-lg p-0.5",children:[r.jsx("button",{type:"button",onClick:()=>o("qty"),className:`flex-1 py-1.5 text-xs font-medium rounded-md transition-colors ${s==="qty"?"bg-bambu-dark-secondary text-white shadow":"text-bambu-gray hover:text-white"}`,children:n("forecast.byQuantity")}),r.jsx("button",{type:"button",onClick:()=>o("duration"),className:`flex-1 py-1.5 text-xs font-medium rounded-md transition-colors ${s==="duration"?"bg-bambu-dark-secondary text-white shadow":"text-bambu-gray hover:text-white"}`,children:n("forecast.byDuration")})]}),s==="qty"?r.jsxs("div",{className:"space-y-1.5",children:[r.jsx("label",{className:"text-xs text-bambu-gray",children:n("forecast.numberOfSpools")}),r.jsx("input",{type:"number",min:1,max:99,value:l,onChange:b=>c(b.target.value),className:"w-full px-3 py-2 bg-bambu-dark-tertiary border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:outline-none focus:border-bambu-green",autoFocus:!0})]}):r.jsxs("div",{className:"space-y-2",children:[r.jsxs("div",{className:"space-y-1.5",children:[r.jsx("label",{className:"text-xs text-bambu-gray",children:n("forecast.lastHowManyDays")}),r.jsx("input",{type:"number",min:1,max:365,value:d,onChange:b=>u(b.target.value),className:"w-full px-3 py-2 bg-bambu-dark-tertiary border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:outline-none focus:border-bambu-green",autoFocus:!0})]}),t.dailyRateG!==null?r.jsxs("div",{className:"flex items-center gap-2 px-3 py-2 bg-bambu-dark-tertiary/50 rounded-lg",children:[r.jsx("span",{className:"text-xs text-bambu-gray",children:"≈"}),r.jsx("span",{className:"text-sm font-semibold text-bambu-green",children:n("forecast.spoolCount",{count:f??0})}),r.jsxs("span",{className:"text-xs text-bambu-gray",children:["at ",t.dailyRateG.toFixed(1),"g/day"]})]}):r.jsx("div",{className:"text-xs text-yellow-400 px-1",children:n("forecast.noUsageQty")})]}),r.jsxs("div",{className:"space-y-1.5",children:[r.jsx("label",{className:"text-xs text-bambu-gray",children:n("forecast.noteOptional")}),r.jsx("input",{type:"text",maxLength:200,value:m,onChange:b=>p(b.target.value),placeholder:n("forecast.notePlaceholder"),className:"w-full px-3 py-2 bg-bambu-dark-tertiary border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/40 focus:outline-none focus:border-bambu-green"})]}),r.jsxs("div",{className:"flex items-center gap-3 pt-1",children:[r.jsx("button",{type:"submit",className:"flex-1 py-2 bg-bambu-green text-white text-sm font-medium rounded-lg hover:bg-bambu-green/80 transition-colors",children:n("forecast.addNSpools",{count:g})}),r.jsx("button",{type:"button",onClick:e,className:"px-4 py-2 text-sm text-bambu-gray hover:text-white border border-bambu-dark-tertiary rounded-lg transition-colors",children:n("forecast.cancel")})]})]})]})})}const bI={material:"",subtype:"",brand:"",color_name:"",rgba:"808080FF",extra_colors:"",effect_type:"",label_weight:1e3,core_weight:250,core_weight_catalog_id:null,weight_used:0,slicer_filament:"",note:"",cost_per_kg:null,category:"",low_stock_threshold_pct:null,storage_location:"",spoolman_filament_id:null},got=new Set(["material","subtype","brand","rgba","color_name","label_weight"]);function Ede(t,e=!1,a=!1){const n={};return e||a?(!t.material&&!t.spoolman_filament_id&&(n.material="Material is required"),{isValid:Object.keys(n).length===0,errors:n}):(t.slicer_filament||(n.slicer_filament="Slicer preset is required"),t.material||(n.material="Material is required"),t.brand||(n.brand="Brand is required"),t.subtype||(n.subtype="Subtype is required"),{isValid:Object.keys(n).length===0,errors:n})}function Dde({formData:t,updateField:e,cloudAuthenticated:a,loadingCloudPresets:n,presetInputValue:i,setPresetInputValue:s,selectedPresetOption:o,filamentOptions:l,availableBrands:c,availableMaterials:d,quickAdd:u,quantity:m,onQuantityChange:p,errors:f}){const{t:g}=wt(),[v,b]=y.useState(!1),[x,S]=y.useState(!1),[k,P]=y.useState(!1),[N,T]=y.useState(!1),[j,D]=y.useState(""),[C,E]=y.useState(""),[R,I]=y.useState(""),[O,z]=y.useState(String(t.label_weight)),[X,ae]=y.useState(!1),Y=y.useRef(null),ce=y.useRef(null),de=y.useRef(null),oe=y.useRef(null);y.useEffect(()=>{const q=Q=>{Y.current&&!Y.current.contains(Q.target)&&b(!1),oe.current&&!oe.current.contains(Q.target)&&T(!1),ce.current&&!ce.current.contains(Q.target)&&S(!1),de.current&&!de.current.contains(Q.target)&&P(!1)};return document.addEventListener("mousedown",q),()=>document.removeEventListener("mousedown",q)},[]);const K=y.useMemo(()=>{if(!i)return l;const q=i.toLowerCase();return l.filter(Q=>Q.displayName.toLowerCase().includes(q)||Q.code.toLowerCase().includes(q))},[l,i]),ie=y.useMemo(()=>{if(!j)return c;const q=j.toLowerCase();return c.filter(A=>A.toLowerCase().includes(q)).sort((A,F)=>{const B=A.toLowerCase()===q,W=F.toLowerCase()===q;return B&&!W?-1:!B&&W?1:A.localeCompare(F)})},[c,j]),ue=y.useMemo(()=>{if(!C)return gw;const q=C.toLowerCase();return gw.filter(Q=>Q.toLowerCase().includes(q))},[C]),he=y.useMemo(()=>{if(!R)return d;const q=R.toLowerCase();return d.filter(A=>A.toLowerCase().includes(q)).sort((A,F)=>{const B=A.toLowerCase()===q,W=F.toLowerCase()===q;return B&&!W?-1:!B&&W?1:A.localeCompare(F)})},[R,d]);y.useEffect(()=>{X||z(String(t.label_weight))},[t.label_weight,X]);const ge=q=>{e("slicer_filament",q.code),s(q.displayName),b(!1);const Q=lf(q.name);Q.material&&e("material",Q.material),Q.brand&&e("brand",Q.brand),Q.variant&&e("subtype",Q.variant)};return r.jsxs("div",{className:"space-y-4",children:[!u&&r.jsx("div",{className:"flex items-center gap-2 text-xs text-bambu-gray",children:n?r.jsxs(r.Fragment,{children:[r.jsx(lt,{className:"w-3 h-3 animate-spin"})," ",g("inventory.loadingPresets")]}):a?r.jsxs(r.Fragment,{children:[r.jsx(Im,{className:"w-3 h-3 text-bambu-green"})," ",g("inventory.cloudConnected")]}):r.jsxs(r.Fragment,{children:[r.jsx(s3,{className:"w-3 h-3"})," ",g("inventory.cloudNotConnected")]})}),!u&&r.jsxs("div",{children:[r.jsxs("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:[g("inventory.slicerPreset")," *"]}),r.jsxs("div",{className:"relative",ref:Y,children:[r.jsx(br,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50 pointer-events-none"}),r.jsx("input",{type:"text",className:"w-full pl-9 pr-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green",placeholder:g("inventory.searchPresets"),value:i,onChange:q=>{s(q.target.value),b(!0)},onFocus:()=>{b(!0),s("")}}),v&&r.jsx("div",{className:"absolute z-50 w-full mt-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-lg max-h-64 overflow-y-auto",children:K.length===0?r.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:g("inventory.noPresetsFound")}):K.map(q=>r.jsx("button",{type:"button",className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary truncate ${o?.code===q.code?"bg-bambu-green/10 text-bambu-green":"text-white"}`,onClick:()=>ge(q),children:q.displayName},`${q.code}::${q.name}`))})]}),o&&r.jsxs("div",{className:"mt-1 text-xs text-bambu-gray",children:[g("inventory.selectedPreset"),": ",r.jsx("span",{className:"font-mono text-bambu-green",children:o.code})]}),f?.slicer_filament&&r.jsx("p",{className:"mt-1 text-xs text-red-400",children:f.slicer_filament})]}),r.jsxs("div",{children:[r.jsxs("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:[g("inventory.material")," *"]}),r.jsxs("div",{className:"relative",ref:oe,children:[r.jsx("input",{type:"text",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green",placeholder:g("inventory.selectMaterial"),value:N?R:t.material,onChange:q=>{I(q.target.value),T(!0)},onFocus:()=>{T(!0),I("")}}),r.jsx(za,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50 pointer-events-none"}),N&&r.jsxs("div",{className:"absolute z-50 w-full mt-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-lg max-h-48 overflow-y-auto",children:[he.length===0?r.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:g("inventory.noResults")}):he.map(q=>r.jsx("button",{type:"button",className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary ${t.material===q?"bg-bambu-green/10 text-bambu-green":"text-white"}`,onClick:()=>{e("material",q),T(!1),I("")},children:q},q)),R&&!he.includes(R)&&r.jsx("button",{type:"button",className:"w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary text-bambu-green border-t border-bambu-dark-tertiary",onClick:()=>{e("material",R),T(!1),I("")},children:g("inventory.useCustomMaterial",{material:R})})]})]}),f?.material&&r.jsx("p",{className:"mt-1 text-xs text-red-400",children:f.material})]}),r.jsxs("div",{children:[r.jsxs("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:[g("inventory.brand"),!u&&" *"]}),r.jsxs("div",{className:"relative",ref:ce,children:[r.jsx("input",{type:"text",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green",placeholder:g("inventory.searchBrand"),value:x?j:t.brand,onChange:q=>{D(q.target.value),S(!0)},onFocus:()=>{S(!0),D("")}}),r.jsx(za,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50 pointer-events-none"}),x&&r.jsxs("div",{className:"absolute z-50 w-full mt-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-lg max-h-48 overflow-y-auto",children:[ie.length===0?r.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:g("inventory.noResults")}):ie.map(q=>r.jsx("button",{type:"button",className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary ${t.brand===q?"bg-bambu-green/10 text-bambu-green":"text-white"}`,onClick:()=>{e("brand",q),S(!1),D("")},children:q},q)),j&&!ie.includes(j)&&r.jsx("button",{type:"button",className:"w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary text-bambu-green border-t border-bambu-dark-tertiary",onClick:()=>{e("brand",j),S(!1),D("")},children:g("inventory.useCustomBrand",{brand:j})})]})]}),f?.brand&&r.jsx("p",{className:"mt-1 text-xs text-red-400",children:f.brand})]}),r.jsxs("div",{children:[r.jsxs("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:[g("inventory.subtype"),!u&&" *"]}),r.jsxs("div",{className:"relative",ref:de,children:[r.jsx("input",{type:"text",value:k?C:t.subtype,onChange:q=>{E(q.target.value),P(!0)},onFocus:()=>{P(!0),E("")},placeholder:"Basic, Matte, Silk...",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green"}),r.jsx(za,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50 pointer-events-none"}),k&&r.jsxs("div",{className:"absolute z-50 w-full mt-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-lg max-h-48 overflow-y-auto",children:[ue.length===0?r.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:g("inventory.noResults")}):ue.map(q=>r.jsx("button",{type:"button",className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary ${t.subtype===q?"bg-bambu-green/10 text-bambu-green":"text-white"}`,onClick:()=>{e("subtype",q),P(!1),E("")},children:q},q)),C&&!gw.some(q=>q.toLowerCase()===C.toLowerCase().trim())&&r.jsx("button",{type:"button",className:"w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary text-bambu-green border-t border-bambu-dark-tertiary",onClick:()=>{e("subtype",C),P(!1),E("")},children:g("inventory.useCustomBrand",{brand:C})})]})]}),f?.subtype&&r.jsx("p",{className:"mt-1 text-xs text-red-400",children:f.subtype})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:g("inventory.labelWeight")}),r.jsxs("div",{className:"relative",children:[r.jsx("input",{type:"number",className:"w-full px-3 py-2 pr-7 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:outline-none focus:border-bambu-green",value:O,min:0,onFocus:()=>ae(!0),onChange:q=>z(q.target.value),onBlur:()=>{ae(!1);const q=O.trim(),Q=Number(q);if(!q||!Number.isFinite(Q)||Q<0){z(String(t.label_weight));return}const A=Math.round(Q);e("label_weight",A),z(String(A))}}),r.jsx("span",{className:"absolute right-2 top-1/2 -translate-y-1/2 text-xs text-bambu-gray",children:"g"})]})]}),u&&r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:g("inventory.quantity")}),r.jsx("input",{type:"number",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:outline-none focus:border-bambu-green",value:m,min:1,max:100,onChange:q=>{const Q=Math.max(1,Math.min(100,parseInt(q.target.value)||1));p(Q)}})]})]})}function bot(t){const e=t.split(/[\s,]+/).map(i=>i.trim().replace(/^#/,"")).filter(Boolean),a=[],n=[];for(const i of e)(i.length===6||i.length===8)&&/^[0-9a-fA-F]+$/.test(i)?a.push(i.toLowerCase()):n.push(i);return{value:a.join(","),invalid:n}}function Fde({formData:t,updateField:e,recentColors:a,onColorUsed:n,catalogColors:i}){const{t:s}=wt(),[o,l]=y.useState(!1),[c,d]=y.useState(""),u=(t.rgba.replace("#","")+"FF").substring(0,8).toUpperCase(),m=u.substring(0,6),f=u.substring(6,8)==="00",[g,v]=y.useState(f?u:m);y.useEffect(()=>{v(f?u:m)},[m,u,f]);const b=z=>{const X=(z.replace("#","")+"FF").substring(0,8).toUpperCase();return u===X},x=z=>al(z),S=(z,X,ae,Y)=>{const ce=z.replace("#","").toUpperCase(),de=ce.length===8?ce:ce+"FF";if(e("rgba",de),e("color_name",X),ae!==void 0){const oe=ae??"";D(oe),E([]),R.current=oe,e("extra_colors",oe)}Y!==void 0&&e("effect_type",Y??""),n({name:X,hex:z})},k=y.useMemo(()=>{if(i.length===0)return[];const z=t.brand?.trim(),X=t.material?.toLowerCase().trim(),ae=t.subtype?.toLowerCase().trim();if(!z&&!X)return[];const Y=z?z.toLowerCase().split(/[\s\-_]+/).filter(oe=>oe.length>=2):[],ce=oe=>{if(Y.length===0)return!0;const K=oe.toLowerCase();return Y.some(ie=>K.includes(ie))};if(z&&!X){const oe=i.filter(K=>ce(K.manufacturer));if(oe.length>0)return oe.map(K=>({name:K.color_name,hex:K.hex_color.replace("#","").substring(0,6),manufacturer:K.manufacturer,material:typeof K.material=="string"?K.material:void 0,extra_colors:K.extra_colors??null,effect_type:K.effect_type??null}))}const de=X&&ae?`${X} ${ae}`:"";if(de){const oe=i.filter(ie=>ce(ie.manufacturer)&&ie.material?.toLowerCase()===de);if(oe.length>0)return oe.map(ie=>({name:ie.color_name,hex:ie.hex_color.replace("#","").substring(0,6),manufacturer:ie.manufacturer,material:typeof ie.material=="string"?ie.material:void 0,extra_colors:ie.extra_colors??null,effect_type:ie.effect_type??null}));const K=de.replace(/\+$/,"");if(K!==de){const ie=i.filter(ue=>ce(ue.manufacturer)&&ue.material?.toLowerCase()===K);if(ie.length>0)return ie.map(ue=>({name:ue.color_name,hex:ue.hex_color.replace("#","").substring(0,6),manufacturer:ue.manufacturer,material:typeof ue.material=="string"?ue.material:void 0}))}}if(X){const oe=i.filter(K=>ce(K.manufacturer)&&(!K.material||K.material.toLowerCase().startsWith(X)));if(oe.length>0)return oe.map(K=>({name:K.color_name,hex:K.hex_color.replace("#","").substring(0,6),manufacturer:K.manufacturer,material:typeof K.material=="string"?K.material:void 0,extra_colors:K.extra_colors??null,effect_type:K.effect_type??null}))}return[]},[i,t.brand,t.material,t.subtype]),P=y.useMemo(()=>{if(!c)return k;if(k.length===0)return[];const z=c.toLowerCase();return k.filter(ae=>ae.name.toLowerCase().includes(z)||(ae.manufacturer?.toLowerCase().includes(z)??!1)||(ae.material?.toLowerCase().includes(z)??!1))},[c,k]),N=k.length>0,T=y.useMemo(()=>c?rY.filter(z=>z.name.toLowerCase().includes(c.toLowerCase())):o?rY:wse,[c,o]),[j,D]=y.useState(t.extra_colors),[C,E]=y.useState([]),R=y.useRef(t.extra_colors);y.useEffect(()=>{t.extra_colors!==R.current&&(D(t.extra_colors),E([]),R.current=t.extra_colors)},[t.extra_colors]);const I=y.useMemo(()=>yj({rgba:t.rgba,extraColors:t.extra_colors,effectType:t.effect_type,subtype:t.subtype,effectSize:"bar"}),[t.rgba,t.extra_colors,t.effect_type,t.subtype]),O=z=>{if(D(z),!z.trim()){E([]),R.current="",e("extra_colors","");return}const{value:X,invalid:ae}=bot(z);E(ae),R.current=X,e("extra_colors",X)};return r.jsxs("div",{className:"space-y-3",children:[r.jsx("div",{className:"h-10 rounded-lg border border-bambu-dark-tertiary",style:I,"data-testid":"color-preview-banner"}),a.length>0&&r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-bambu-gray shrink-0",children:[r.jsx(ar,{className:"w-3 h-3"}),r.jsx("span",{children:s("inventory.recentColors")})]}),r.jsx("div",{className:"flex flex-wrap gap-1.5",children:a.map(z=>r.jsx("button",{type:"button",onClick:()=>S(z.hex,z.name),className:`w-6 h-6 rounded border-2 transition-all hover:scale-110 ${b(z.hex)?"border-bambu-green ring-1 ring-bambu-green/30 scale-110":"border-bambu-dark-tertiary"}`,style:x(z.hex),title:z.name},z.hex))})]}),r.jsxs("div",{className:"relative",children:[r.jsx(br,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50 pointer-events-none"}),r.jsx("input",{type:"text",className:"w-full pl-9 pr-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green",placeholder:s("inventory.searchColors"),value:c,onChange:z=>d(z.target.value)})]}),N?r.jsxs("div",{className:"space-y-1.5",children:[r.jsx("span",{className:"text-xs text-bambu-gray",children:c?s("inventory.searchResults"):`${t.brand}${t.material?` ${t.material}`:""}`}),r.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[P.map(z=>r.jsx("button",{type:"button",onClick:()=>S(z.hex,z.name,z.extra_colors,z.effect_type),className:`w-6 h-6 rounded border-2 transition-all hover:scale-110 hover:z-20 relative group ${b(z.hex)?"border-bambu-green ring-1 ring-bambu-green/30 scale-110":"border-bambu-dark-tertiary"}`,style:x(z.hex),title:z.manufacturer&&z.material?`${z.name} (${z.manufacturer} — ${z.material})`:z.manufacturer?`${z.name} (${z.manufacturer})`:z.name,children:r.jsx("span",{className:"absolute -bottom-7 left-1/2 -translate-x-1/2 px-2 py-0.5 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-xs whitespace-nowrap opacity-0 group-hover:opacity-100 transition-opacity pointer-events-none z-20 shadow-lg text-white",children:z.manufacturer&&z.material?`${z.name} (${z.manufacturer} — ${z.material})`:z.manufacturer?`${z.name} (${z.manufacturer})`:z.name})},`${z.hex}-${z.name}-${z.manufacturer??""}`)),P.length===0&&r.jsx("p",{className:"text-sm text-bambu-gray py-1",children:s("inventory.noColorsFound")})]})]}):r.jsxs("div",{className:"space-y-1.5",children:[r.jsxs("div",{className:"flex items-center justify-between text-xs text-bambu-gray",children:[r.jsx("span",{children:s(c?"inventory.searchResults":o?"inventory.allColors":"inventory.commonColors")}),!c&&r.jsx("button",{type:"button",onClick:()=>l(!o),className:"flex items-center gap-1 hover:text-white transition-colors",children:o?r.jsxs(r.Fragment,{children:[s("inventory.showLess")," ",r.jsx(el,{className:"w-3 h-3"})]}):r.jsxs(r.Fragment,{children:[s("inventory.showAll")," ",r.jsx(za,{className:"w-3 h-3"})]})})]}),r.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[T.map(z=>r.jsx("button",{type:"button",onClick:()=>S(z.hex,z.name),className:`w-6 h-6 rounded border-2 transition-all hover:scale-110 hover:z-20 relative group ${b(z.hex)?"border-bambu-green ring-1 ring-bambu-green/30 scale-110":"border-bambu-dark-tertiary"}`,style:x(z.hex),title:z.name,children:r.jsx("span",{className:"absolute -bottom-7 left-1/2 -translate-x-1/2 px-2 py-0.5 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-xs whitespace-nowrap opacity-0 group-hover:opacity-100 transition-opacity pointer-events-none z-20 shadow-lg text-white",children:z.name})},z.hex)),T.length===0&&r.jsx("p",{className:"text-sm text-bambu-gray py-1",children:s("inventory.noColorsFound")})]})]}),r.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:s("inventory.colorName")}),r.jsx("input",{type:"text",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green",placeholder:s("inventory.colorNamePlaceholder"),value:t.color_name,onChange:z=>e("color_name",z.target.value)})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:s("inventory.hexColor")}),r.jsxs("div",{className:"flex gap-2",children:[r.jsxs("div",{className:"relative flex-1",children:[r.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-bambu-gray",children:"#"}),r.jsx("input",{type:"text",className:"w-full pl-7 pr-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm font-mono uppercase focus:outline-none focus:border-bambu-green",placeholder:"RRGGBB",value:g.toUpperCase(),onChange:z=>{const X=z.target.value.replace("#","").replace(/[^0-9A-Fa-f]/g,"").toUpperCase(),ae=X.length>8?X.substring(0,8):X;v(ae),ae.length===6?e("rgba",ae+"FF"):ae.length===8&&e("rgba",ae)},onBlur:()=>{if(g.length===7){const z=g+"0";v(z),e("rgba",z)}else if(g.length>0&&g.length<6){const z=g.padEnd(6,"0");v(z),e("rgba",z+"FF")}}})]}),r.jsx("input",{type:"color",className:"w-11 h-[38px] rounded-lg cursor-pointer border border-bambu-dark-tertiary shrink-0 bg-transparent",value:`#${m}`,onChange:z=>{const X=z.target.value.replace("#","").toUpperCase();e("rgba",X+"FF")},title:s("inventory.pickColor")})]})]})]}),r.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3 pt-2 border-t border-bambu-dark-tertiary/50",children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:s("inventory.extraColorsLabel")}),r.jsx("input",{type:"text",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm font-mono placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green",placeholder:s("inventory.extraColorsPlaceholder"),value:j,onChange:z=>O(z.target.value),"data-testid":"extra-colors-input"}),C.length>0&&r.jsx("p",{className:"text-xs text-red-400 mt-1",children:s("inventory.extraColorsInvalid",{tokens:C.join(", ")})}),!C.length&&r.jsx("p",{className:"text-xs text-bambu-gray/70 mt-1",children:s("inventory.extraColorsHint")})]}),r.jsxs("div",{children:[r.jsxs("label",{className:"block text-sm font-medium text-bambu-gray mb-1 flex items-center gap-1.5",children:[r.jsx(Ug,{className:"w-3.5 h-3.5"}),s("inventory.colorEffectLabel")]}),r.jsxs("div",{className:"flex gap-2 items-stretch",children:[r.jsx("select",{className:"flex-1 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:outline-none focus:border-bambu-green",value:t.effect_type,onChange:z=>e("effect_type",z.target.value),"data-testid":"effect-type-select",children:hI.map(z=>r.jsx("option",{value:z.value,children:s(z.labelKey)},z.value||"none"))}),r.jsx(N5,{rgba:t.rgba,extraColors:t.extra_colors,effectType:t.effect_type,subtype:t.subtype,effectSize:"preview",className:"w-10 h-10",shape:"square"})]})]})]})]})}function xot({catalog:t,value:e,onChange:a,catalogId:n,onCatalogIdChange:i}){const{t:s}=wt(),[o,l]=y.useState(!1),[c,d]=y.useState(""),u=y.useRef(null),m=y.useRef(null);y.useEffect(()=>{const v=b=>{u.current&&!u.current.contains(b.target)&&l(!1)};return document.addEventListener("mousedown",v),()=>document.removeEventListener("mousedown",v)},[]),y.useEffect(()=>{if(t.length===0)return;const v=t.filter(b=>b.weight===e);if(n){const b=t.find(x=>x.id===n);if(b&&b.weight===e)return}v.length===1?i(v[0].id):v.length===0&&n!==null&&i(null)},[e,t,n,i]);const p=y.useMemo(()=>{if(!c)return t;const v=c.toLowerCase();return t.filter(b=>b.name.toLowerCase().includes(v)||b.weight.toString().includes(v))},[t,c]),f=y.useMemo(()=>t.filter(v=>v.weight===e),[t,e]),g=y.useMemo(()=>{if(o)return c;if(n){const v=t.find(b=>b.id===n);if(v)return v.name}return f.length>0?f[0].name:""},[o,c,n,t,f]);return r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:r.jsxs("span",{className:"flex items-center gap-2",children:[r.jsx(uJ,{className:"w-3.5 h-3.5 text-bambu-gray"}),s("inventory.coreWeight")]})}),r.jsxs("div",{className:"flex gap-2 items-center",children:[r.jsxs("div",{className:"flex-1 min-w-0 relative",ref:u,children:[r.jsx("input",{ref:m,type:"text",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green",placeholder:s("inventory.searchSpoolWeight"),value:g,onFocus:()=>{l(!0),d("")},onChange:v=>{d(v.target.value),l(!0)}}),o&&r.jsx("div",{className:"absolute z-50 w-full mt-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-lg max-h-64 overflow-y-auto",children:p.length===0?r.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:s("inventory.noResults")}):p.map(v=>r.jsxs("button",{type:"button",className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex justify-between items-center ${(n?v.id===n:v.weight===e)?"bg-bambu-green/10 text-bambu-green":"text-white"}`,onClick:()=>{i(v.id),a(v.weight),l(!1),d("")},children:[r.jsx("span",{className:"truncate",children:v.name}),r.jsxs("span",{className:"font-mono text-xs text-bambu-gray ml-2 shrink-0",children:[v.weight,"g"]})]},v.id))})]}),r.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[r.jsx("input",{type:"number",className:"w-16 px-2 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm text-center font-mono focus:outline-none focus:border-bambu-green",value:e,min:0,max:2e3,onChange:v=>{const b=parseInt(v.target.value);!isNaN(b)&&b>=0&&a(b)}}),r.jsx("span",{className:"text-bambu-gray text-sm",children:"g"})]})]})]})}function Lde({formData:t,updateField:e,spoolCatalog:a,currencySymbol:n,availableCategories:i,globalLowStockThreshold:s,spoolmanMode:o=!1}){const{t:l}=wt(),{showToast:c}=da(),[d,u]=y.useState(""),[m,p]=y.useState(!1),[f,g]=y.useState(""),[v,b]=y.useState(!1),x=Math.max(0,t.label_weight-t.weight_used),S=t.core_weight+x;return y.useEffect(()=>{m||u(String(S))},[m,S]),y.useEffect(()=>{v||g(String(x))},[v,x]),r.jsxs("div",{className:"space-y-4",children:[o?r.jsx("p",{className:"text-xs text-bambu-gray px-1",children:l("inventory.spoolWeightManagedBySpoolman")}):r.jsx(xot,{catalog:a,value:t.core_weight,onChange:k=>e("core_weight",k),catalogId:t.core_weight_catalog_id,onCatalogIdChange:k=>e("core_weight_catalog_id",k)}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:l("inventory.currentWeight")}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsxs("div",{className:"relative flex-1",children:[r.jsx("input",{type:"number",value:f,min:0,max:t.label_weight,onFocus:()=>b(!0),onChange:k=>{g(k.target.value)},onBlur:()=>{b(!1);const k=f.trim(),P=Number(k);if(!k||!Number.isFinite(P)||P<0||P>t.label_weight){g(String(x));return}const N=Math.round(P);e("weight_used",Math.max(0,t.label_weight-N)),g(String(N))},className:"w-full px-3 py-2 pr-7 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:outline-none focus:border-bambu-green"}),r.jsx("span",{className:"absolute right-2 top-1/2 -translate-y-1/2 text-xs text-bambu-gray",children:"g"})]}),r.jsxs("span",{className:"text-xs text-bambu-gray shrink-0",children:["/ ",t.label_weight,"g"]})]})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:l("inventory.measuredWeight")}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsxs("div",{className:"relative flex-1",children:[r.jsx("input",{type:"number",value:d,min:0,onFocus:()=>p(!0),onChange:k=>{u(k.target.value)},onBlur:()=>{p(!1);const k=d.trim(),P=Number(k),N=t.core_weight,T=t.core_weight+t.label_weight;if(!k||!Number.isFinite(P)||PT){c(l("inventory.measuredWeightError",{min:N,max:T}),"error"),u(String(S));return}const j=Math.round(P),D=Math.max(0,Math.min(t.label_weight,j-t.core_weight));e("weight_used",Math.max(0,t.label_weight-D)),u(String(j))},className:"w-full px-3 py-2 pr-7 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:outline-none focus:border-bambu-green"}),r.jsx("span",{className:"absolute right-2 top-1/2 -translate-y-1/2 text-xs text-bambu-gray",children:"g"})]}),r.jsxs("span",{className:"text-xs text-bambu-gray shrink-0",children:["/ ",t.core_weight+t.label_weight,"g"]})]})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:l("inventory.costPerKg","Cost per kg")}),r.jsx("div",{className:"flex items-center gap-2",children:r.jsxs("div",{className:"relative flex-1",children:[r.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-bambu-gray text-sm pointer-events-none",children:n}),r.jsx("input",{type:"number",value:t.cost_per_kg??"",min:0,step:.01,placeholder:"0.00",onChange:k=>{const P=k.target.value===""?null:parseFloat(k.target.value);e("cost_per_kg",P)},style:{paddingLeft:`${Math.max(2,n.length*.6+1)}rem`},className:"w-full py-2 pr-3 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:outline-none focus:border-bambu-green"})]})})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",htmlFor:"spool-category",children:l("inventory.category")}),r.jsx("input",{id:"spool-category",type:"text",list:"spool-category-options",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green",placeholder:l("inventory.categoryPlaceholder"),value:t.category,maxLength:50,onChange:k=>e("category",k.target.value)}),i.length>0&&r.jsx("datalist",{id:"spool-category-options",children:i.map(k=>r.jsx("option",{value:k},k))})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",htmlFor:"spool-low-stock-threshold",children:l("inventory.lowStockThresholdOverride")}),r.jsx("div",{className:"flex items-center gap-2",children:r.jsxs("div",{className:"relative flex-1",children:[r.jsx("input",{id:"spool-low-stock-threshold",type:"number",className:"w-full px-3 py-2 pr-8 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green",placeholder:String(s),value:t.low_stock_threshold_pct??"",min:1,max:99,step:1,onChange:k=>{const P=k.target.value;if(P===""){e("low_stock_threshold_pct",null);return}const N=Number(P);Number.isFinite(N)&&e("low_stock_threshold_pct",Math.min(99,Math.max(1,Math.round(N))))}}),r.jsx("span",{className:"absolute right-3 top-1/2 -translate-y-1/2 text-xs text-bambu-gray pointer-events-none",children:"%"})]})}),r.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:l("inventory.lowStockThresholdOverrideHelp",{global:s})})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:l("inventory.note")}),r.jsx("textarea",{className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green resize-none min-h-[80px]",placeholder:l("inventory.notePlaceholder"),value:t.note,onChange:k=>e("note",k.target.value)})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:l("inventory.storageLocation")}),r.jsx("input",{type:"text",maxLength:255,className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green",placeholder:l("inventory.storageLocationPlaceholder"),value:t.storage_location,onChange:k=>e("storage_location",k.target.value)})]})]})}function yot({filaments:t,isLoading:e,selectedId:a,onSelect:n}){const{t:i}=wt(),[s,o]=y.useState(!1),[l,c]=y.useState(""),d=y.useRef(null),u=y.useRef(null),m=y.useMemo(()=>t.find(b=>b.id===a)??null,[t,a]);y.useEffect(()=>{const b=x=>{d.current&&!d.current.contains(x.target)&&(o(!1),c(""))};return document.addEventListener("mousedown",b),()=>document.removeEventListener("mousedown",b)},[]);const p=y.useMemo(()=>{const b=l.toLowerCase().trim();return b?t.filter(x=>x.name.toLowerCase().includes(b)||(x.material?.toLowerCase().includes(b)??!1)||(x.vendor?.name.toLowerCase().includes(b)??!1)||(x.color_name?.toLowerCase().includes(b)??!1)):t},[t,l]);y.useEffect(()=>{s&&u.current?.focus()},[s]);const f=()=>{o(!0),c("")},g=b=>{n(b),o(!1),c("")},v=b=>b?`#${b.replace("#","")}`:"#808080";return r.jsxs("div",{ref:d,className:"relative",children:[r.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:i("inventory.pickFromSpoolmanCatalog")}),r.jsxs("button",{type:"button",onClick:f,className:"w-full flex items-center gap-2 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-left focus:outline-none focus:border-bambu-green hover:border-bambu-gray transition-colors",children:[e?r.jsx(lt,{className:"w-4 h-4 text-bambu-gray animate-spin shrink-0"}):m?r.jsxs(r.Fragment,{children:[r.jsx("span",{className:"w-4 h-4 rounded-full shrink-0 border border-white/20",style:{backgroundColor:v(m.color_hex)},"aria-label":i("inventory.spoolmanFilamentColorSwatch")}),r.jsxs("span",{className:"text-white text-sm truncate flex-1",children:[m.vendor?.name?`${m.vendor.name} — `:"",m.name]})]}):r.jsxs(r.Fragment,{children:[r.jsx(en,{className:"w-4 h-4 text-bambu-gray shrink-0"}),r.jsx("span",{className:"text-bambu-gray text-sm flex-1",children:i("inventory.spoolmanFilamentCatalog")})]}),r.jsx(za,{className:"w-4 h-4 text-bambu-gray shrink-0 ml-auto"})]}),s&&r.jsxs("div",{className:"absolute z-50 w-full mt-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl",children:[r.jsx("div",{className:"p-2 border-b border-bambu-dark-tertiary",children:r.jsx("input",{ref:u,type:"text",value:l,onChange:b=>c(b.target.value),placeholder:i("inventory.pickFromSpoolmanCatalog"),className:"w-full px-2 py-1.5 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-sm placeholder-bambu-gray focus:outline-none focus:border-bambu-green"})}),r.jsx("ul",{className:"max-h-56 overflow-y-auto py-1",children:e?r.jsxs("li",{className:"flex items-center justify-center gap-2 py-4 text-bambu-gray text-sm",children:[r.jsx(lt,{className:"w-4 h-4 animate-spin"}),r.jsx("span",{children:i("common.loading","Loading…")})]}):p.length===0?r.jsx("li",{className:"py-4 text-center text-bambu-gray text-sm",children:i("inventory.noSpoolmanFilaments")}):p.map(b=>r.jsx("li",{children:r.jsxs("button",{type:"button",onClick:()=>g(b),className:`w-full flex items-center gap-2 px-3 py-2 text-left hover:bg-bambu-dark-tertiary transition-colors ${b.id===a?"bg-bambu-dark-tertiary":""}`,children:[r.jsx("span",{className:"w-4 h-4 rounded-full shrink-0 border border-white/20",style:{backgroundColor:v(b.color_hex)},"aria-label":i("inventory.spoolmanFilamentColorSwatch")}),r.jsxs("span",{className:"flex-1 min-w-0",children:[r.jsxs("span",{className:"block text-white text-sm truncate",children:[b.vendor?.name?`${b.vendor.name} — `:"",b.name]}),r.jsxs("span",{className:"block text-bambu-gray text-xs truncate",children:[[b.material,b.color_name].filter(Boolean).join(" · "),b.weight?` · ${b.weight}g`:""]})]})]})},b.id))})]})]})}function Rde({formData:t,printersWithCalibrations:e,selectedProfiles:a,setSelectedProfiles:n,expandedPrinters:i,setExpandedPrinters:s}){const{t:o}=wt(),l=p=>{s(f=>{const g=new Set(f);return g.has(p)?g.delete(p):g.add(p),g})},c=(p,f,g)=>{const v=`${p}:${f}:${g??"null"}`,b=`${p}:${g??"null"}`;n(x=>{const S=new Set(x);if(S.has(v))S.delete(v);else{for(const k of Array.from(S)){const P=k.split(":");`${P[0]}:${P[2]}`===b&&S.delete(k)}S.add(v)}return S})},d=()=>{const p=new Set;for(const{printer:f,calibrations:g}of e){if(!f.connected)continue;const v=g.filter(x=>PF(x,t)),b=new Map;for(const x of v){const S=`${x.extruder_id??"null"}`;b.has(S)||b.set(S,[]),b.get(S).push(x)}for(const[x,S]of b)if(S.length>0){const P=[...S].sort((N,T)=>T.k_value-N.k_value)[0];p.add(`${f.id}:${P.cali_idx}:${x}`)}}n(p)};if(!t.material)return r.jsx("div",{className:"p-6 bg-bambu-dark rounded-lg text-center",children:r.jsx("p",{className:"text-bambu-gray",children:o("inventory.selectMaterialFirst")})});if(e.length===0)return r.jsx("div",{className:"p-6 bg-bambu-dark rounded-lg text-center",children:r.jsx("p",{className:"text-bambu-gray",children:o("inventory.noPrintersConfigured")})});const u=e.reduce((p,{printer:f,calibrations:g})=>f.connected?p+g.filter(v=>PF(v,t)).length:p,0),m=(p,f)=>{const g=`${p.id}:${f.cali_idx}:${f.extruder_id??"null"}`,v=a.has(g);return r.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:[r.jsx("input",{type:"checkbox",checked:v,onChange:()=>c(String(p.id),f.cali_idx,f.extruder_id),className:"w-4 h-4 rounded border-bambu-dark-tertiary text-bambu-green focus:ring-bambu-green"}),r.jsx("div",{className:"flex-1 min-w-0",children:r.jsx("span",{className:`text-sm font-medium ${v?"text-bambu-green":"text-white"}`,children:f.name||f.filament_id})}),r.jsx("div",{className:"flex items-center gap-2 shrink-0",children:r.jsxs("span",{className:"text-xs font-mono px-2 py-0.5 rounded bg-bambu-dark text-bambu-gray",children:["K=",f.k_value.toFixed(3)]})})]},`${f.cali_idx}-${f.extruder_id}`)};return r.jsxs("div",{className:"space-y-4",children:[r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("p",{className:"text-xs text-bambu-gray",children:[o("inventory.matchingFilter"),": ",t.brand||o("inventory.anyBrand")," / ",t.material," / ",t.subtype||o("inventory.anyVariant")]}),u>0&&r.jsxs("button",{type:"button",onClick:d,className:"flex items-center gap-1.5 px-2 py-1 text-xs bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-bambu-gray hover:text-white hover:border-bambu-green transition-colors",children:[r.jsx(Ug,{className:"w-3.5 h-3.5"}),o("inventory.autoSelect")," (",u,")"]})]}),r.jsx("div",{className:"space-y-3",children:e.map(({printer:p,calibrations:f})=>{const g=i.has(String(p.id)),v=f.filter(P=>PF(P,t)),b=v.length,x=v.some(P=>P.extruder_id!==void 0&&P.extruder_id!==null&&P.extruder_id>0),S=v.filter(P=>P.extruder_id===1),k=v.filter(P=>P.extruder_id===0||P.extruder_id===void 0||P.extruder_id===null);return r.jsxs("div",{className:"border border-bambu-dark-tertiary rounded-lg overflow-hidden",children:[r.jsxs("button",{type:"button",onClick:()=>l(String(p.id)),className:"w-full px-4 py-3 flex items-center justify-between bg-bambu-dark-secondary hover:bg-bambu-dark-tertiary transition-colors",children:[r.jsxs("div",{className:"flex items-center gap-3",children:[g?r.jsx(za,{className:"w-4 h-4 text-bambu-gray"}):r.jsx(Vn,{className:"w-4 h-4 text-bambu-gray"}),r.jsx("span",{className:"font-medium text-white",children:p.name}),b>0?r.jsxs("span",{className:"text-xs px-2 py-0.5 rounded-full bg-bambu-green/20 text-bambu-green",children:[b," ",o(b!==1?"inventory.matches":"inventory.match")]}):r.jsx("span",{className:"text-xs px-2 py-0.5 rounded-full bg-bambu-dark-tertiary text-bambu-gray",children:o("inventory.noMatches")})]}),r.jsx("span",{className:`text-xs px-2 py-1 rounded-full ${p.connected?"bg-green-500/20 text-green-500":"bg-bambu-gray/20 text-bambu-gray"}`,children:p.connected?o("inventory.connected"):o("inventory.offline")})]}),g&&r.jsx("div",{className:"px-4 py-3 space-y-3 bg-bambu-dark border-t border-bambu-dark-tertiary",children:p.connected?b===0?r.jsx("p",{className:"text-sm text-bambu-gray italic py-2",children:o("inventory.noKProfilesMatch")}):x?r.jsxs(r.Fragment,{children:[S.length>0&&r.jsxs("div",{className:"space-y-2",children:[r.jsx("p",{className:"text-xs font-medium text-bambu-gray uppercase tracking-wide",children:o("inventory.leftNozzle")}),r.jsx("div",{className:"space-y-2",children:S.map(P=>m(p,P))})]}),k.length>0&&r.jsxs("div",{className:"space-y-2",children:[r.jsx("p",{className:"text-xs font-medium text-bambu-gray uppercase tracking-wide",children:o("inventory.rightNozzle")}),r.jsx("div",{className:"space-y-2",children:k.map(P=>m(p,P))})]})]}):r.jsx("div",{className:"space-y-2",children:v.map(P=>m(p,P))}):r.jsx("p",{className:"text-sm text-bambu-gray italic py-2",children:o("inventory.printerOffline")})})]},p.id)})}),a.size>0&&r.jsx("div",{className:"p-3 bg-bambu-green/10 border border-bambu-green/30 rounded-lg",children:r.jsxs("p",{className:"text-sm text-white",children:[r.jsx("span",{className:"font-semibold",children:a.size})," ",o("inventory.profilesSelected")]})})]})}function vot(t){const e=Ga(t);return e?e.toLocaleDateString("en-GB",{day:"2-digit",month:"2-digit",year:"2-digit"})+" "+e.toLocaleTimeString("en-GB",{hour:"2-digit",minute:"2-digit"}):""}const wot={completed:"text-bambu-green",failed:"text-red-400",aborted:"text-yellow-400"};function Sot({spoolId:t}){const{t:e}=wt(),a=ia(),{showToast:n}=da(),{data:i,isLoading:s}=$e({queryKey:["spool-usage",t],queryFn:()=>ne.getSpoolUsageHistory(t)}),o=rt({mutationFn:()=>ne.clearSpoolUsageHistory(t),onSuccess:()=>{a.invalidateQueries({queryKey:["spool-usage",t]}),n(e("inventory.historyCleared"),"success")}});return s?r.jsx("div",{className:"flex justify-center py-4",children:r.jsx(lt,{className:"w-5 h-5 animate-spin text-bambu-green"})}):!i||i.length===0?r.jsxs("div",{className:"text-center py-4 text-bambu-gray text-sm",children:[r.jsx(ar,{className:"w-5 h-5 mx-auto mb-2 opacity-50"}),e("inventory.noUsageHistory")]}):r.jsxs("div",{className:"space-y-2",children:[r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsx("h4",{className:"text-sm font-medium text-white",children:e("inventory.usageHistory")}),r.jsxs(Le,{variant:"ghost",size:"sm",onClick:()=>o.mutate(),disabled:o.isPending,className:"text-xs text-bambu-gray hover:text-red-400",children:[r.jsx(na,{className:"w-3 h-3 mr-1"}),e("inventory.clearHistory")]})]}),r.jsx("div",{className:"max-h-48 overflow-y-auto space-y-1",children:i.map(l=>r.jsxs("div",{className:"flex items-center justify-between p-2 rounded bg-bambu-dark/50 text-xs",children:[r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsx("span",{className:"text-bambu-gray",children:vot(l.created_at)}),l.print_name&&r.jsx("span",{className:"text-white ml-2 truncate",title:l.print_name,children:l.print_name})]}),r.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0 ml-2",children:[r.jsxs("span",{className:"text-white font-medium",children:[l.weight_used.toFixed(1),"g"]}),r.jsxs("span",{className:"text-bambu-gray",children:["(",l.percent_used,"%)"]}),r.jsx("span",{className:wot[l.status]||"text-bambu-gray",children:l.status})]})]},l.id))})]})}const KX={tag_uid:null,tray_uuid:null,tag_type:null,data_origin:null};function kot({isOpen:t,onClose:e,spool:a,mode:n,printersWithCalibrations:i=[],currencySymbol:s,onSpoolsCreated:o,spoolmanMode:l=!1,spoolsQueryKey:c=["inventory-spools"]}){const{t:d}=wt(),u=ia(),{showToast:m}=da(),p=n==="edit",f=n==="copy",[g,v]=y.useState(bI),[b,x]=y.useState({}),[S,k]=y.useState("filament"),[P,N]=y.useState(!1),[T,j]=y.useState(!1),[D,C]=y.useState(!1),[E,R]=y.useState(1),[I,O]=y.useState(!1),[z,X]=y.useState(!1),[ae,Y]=y.useState([]),[ce,de]=y.useState(""),[oe,K]=y.useState([]),[ie,ue]=y.useState([]),[he,ge]=y.useState([]),[q,Q]=y.useState([]),[A,F]=y.useState([]),[B,W]=y.useState([]),[H,le]=y.useState(new Set),[U,G]=y.useState(new Set),Z=i.length>0?i:B,J=H.size,{data:re=[],isLoading:se,error:fe}=$e({queryKey:["spoolman-inventory-filaments"],queryFn:()=>ne.getSpoolmanInventoryFilaments(),enabled:l&&t,staleTime:6e4,retry:!1});y.useEffect(()=>{F(Pse())},[]),y.useEffect(()=>{let Ee=!1;return t&&((async()=>{X(!0);try{const[Xe,Nt]=await Promise.allSettled([(async()=>(await ne.getCloudStatus()).is_authenticated?{connected:!0,presets:await ne.getFilamentPresets()}:{connected:!1,presets:[]})(),(async()=>(await ne.orcaCloudStatus()).connected?{connected:!0,presets:(await ne.orcaCloudListProfiles()).filament}:{connected:!1,presets:[]})()]);if(Ee)return;const Vt=Xe.status==="fulfilled"&&Xe.value.connected,ht=Nt.status==="fulfilled"&&Nt.value.connected,It=Xe.status==="fulfilled"?Xe.value.presets:[],Xt=Nt.status==="fulfilled"?Nt.value.presets:[];O(Vt||ht),Y([...It,...Xt])}catch(Xe){if(Ee)return;console.error("Failed to fetch cloud presets:",Xe),O(!1)}finally{Ee||X(!1)}})(),l||ne.getSpoolCatalog().then(K).catch(console.error),ne.getColorCatalog().then(Q).catch(console.error),ne.getLocalPresets().then(Xe=>ue(Xe.filament)).catch(console.error),ne.getBuiltinFilaments().then(ge).catch(console.error),i.length===0&&(async()=>{try{const Xe=await ne.getPrinters(),Nt=await Promise.all(Xe.map(ht=>ne.getPrinterStatus(ht.id).catch(()=>null))),Vt=[];for(let ht=0;ht({cali_idx:vt.slot_id,filament_id:vt.filament_id,setting_id:vt.setting_id||"",name:vt.name,k_value:parseFloat(vt.k_value)||0,n_coef:parseFloat(vt.n_coef)||0,extruder_id:vt.extruder_id,nozzle_diameter:vt.nozzle_diameter}))}catch{}Vt.push({printer:{...It,connected:oa},calibrations:la})}W(Vt)}catch(Xe){console.error("Failed to fetch printer calibrations:",Xe)}})()),()=>{Ee=!0}},[t,i.length]);const me=y.useMemo(()=>_se(ae,new Set,ie,he),[ae,ie,he]),pe=y.useMemo(()=>{const Ee=kse(ae,ie),at=q.map(Nt=>Nt.manufacturer?.trim()).filter(Nt=>!!Nt),Xe=new Set([...Ee,...at]);return Array.from(Xe).sort((Nt,Vt)=>Nt.localeCompare(Vt))},[ae,ie,q]),V=y.useMemo(()=>{const Ee=q.map(Xe=>Xe.material?.trim()).filter(Xe=>!!Xe),at=new Set([...vse,...Ee]);return Array.from(at).sort((Xe,Nt)=>Xe.localeCompare(Nt))},[q]),L=y.useMemo(()=>{const Ee=[];for(const at of q){const Xe=at.manufacturer?.trim(),Nt=at.material?.trim();Xe&&Nt&&Ee.push({brand:Xe,material:Nt})}for(const at of ae){const Xe=lf(at.name);Xe.brand&&Xe.material&&Ee.push({brand:Xe.brand,material:Xe.material})}for(const at of ie){const Xe=lf(at.name),Nt=at.filament_vendor?.trim()||Xe.brand,Vt=Xe.material;Nt&&Vt&&Ee.push({brand:Nt,material:Vt})}return Ee},[ae,q,ie]),te=y.useMemo(()=>{const Ee=new Map;for(const at of L){const Xe=at.brand.toLowerCase(),Nt=at.material.toLowerCase();Ee.has(Xe)||Ee.set(Xe,new Set),Ee.get(Xe).add(Nt)}return Ee},[L]),be=y.useMemo(()=>{const Ee=new Map;for(const at of L){const Xe=at.brand.toLowerCase(),Nt=at.material.toLowerCase();Ee.has(Nt)||Ee.set(Nt,new Set),Ee.get(Nt).add(Xe)}return Ee},[L]),xe=y.useMemo(()=>{if(!g.material)return pe;const Ee=g.material.toLowerCase(),at=be.get(Ee);return!at||at.size===0?pe:pe.filter(Xe=>at.has(Xe.toLowerCase()))},[pe,g.material,be]),ve=y.useMemo(()=>{if(!g.brand)return V;const Ee=g.brand.toLowerCase(),at=te.get(Ee);return!at||at.size===0?V:V.filter(Xe=>at.has(Xe.toLowerCase()))},[V,g.brand,te]),De=y.useMemo(()=>Cse(g.slicer_filament,me),[g.slicer_filament,me]);y.useEffect(()=>{if(t){if(a){const Ee=a.rgba&&/^[0-9A-Fa-f]{8}$/.test(a.rgba)?a.rgba:"808080FF";if(v({material:a.material||"",subtype:a.subtype||"",brand:a.brand||"",color_name:a.color_name_is_synthesized?"":a.color_name||"",rgba:Ee,extra_colors:a.extra_colors||"",effect_type:a.effect_type||"",label_weight:a.label_weight||1e3,core_weight:a.core_weight||250,core_weight_catalog_id:a.core_weight_catalog_id??null,weight_used:f?0:a.weight_used||0,slicer_filament:a.slicer_filament||"",note:a.note||"",cost_per_kg:a.cost_per_kg??null,category:a.category||"",low_stock_threshold_pct:a.low_stock_threshold_pct??null,storage_location:a.storage_location||"",spoolman_filament_id:null}),de(a.slicer_filament_name||a.slicer_filament||""),a.k_profiles&&a.k_profiles.length>0){const at=new Set;for(const Xe of a.k_profiles)Xe.cali_idx!==null&&Xe.cali_idx!==void 0&&at.add(`${Xe.printer_id}:${Xe.cali_idx}:${Xe.extruder??"null"}`);le(at)}else le(new Set)}else v(bI),de(""),le(new Set),C(!1),R(1);x({}),k("filament"),N(!1),j(!1)}},[t,a,n,f]),y.useEffect(()=>{t&&Z.length>0&&G(new Set(Z.map(Ee=>String(Ee.printer.id))))},[t,Z]);const je=(Ee,at)=>{const Xe=got.has(Ee);l&&Xe&&g.spoolman_filament_id!==null&&m(d("inventory.spoolmanFilamentUnlinked"),"info"),v(Nt=>({...Nt,[Ee]:at,...l&&Xe&&Nt.spoolman_filament_id!==null?{spoolman_filament_id:null}:{}})),Ee==="weight_used"&&N(!0),Ee==="storage_location"&&j(!0),b[Ee]&&x(Nt=>({...Nt,[Ee]:void 0}))},Te=Ee=>{const at=Ee.material||"",Xe=Ee.name||"",Nt=at&&Xe.startsWith(at)?Xe.slice(at.length).trim():Xe,Vt=(Ee.color_hex??"").replace("#","").toUpperCase(),ht=/^[0-9A-F]{6}$/.test(Vt)?Vt:"808080";v(It=>({...It,spoolman_filament_id:Ee.id,material:at,subtype:Nt,brand:Ee.vendor?.name||"",rgba:`${ht}FF`,color_name:Ee.color_name||"",label_weight:Ee.weight??It.label_weight})),m(d("inventory.spoolmanFilamentSelected"),"success")},qe=Ee=>{F(at=>Nse(Ee,at))},Pe=rt({mutationFn:Ee=>l?ne.createSpoolmanInventorySpool(Ee):ne.createSpool(Ee),onSuccess:async Ee=>{Ee?.id&&!await Be(Ee.id)||(await u.invalidateQueries({queryKey:c}),o&&o([Ee]),m(d("inventory.spoolCreated"),"success"),e())},onError:Ee=>{Ee instanceof Hi&&Ee.status===503?m(d("inventory.spoolmanUnreachable"),"error"):m(d("inventory.saveFailed"),"error")}}),Ie=rt({mutationFn:({data:Ee,qty:at})=>l?ne.bulkCreateSpoolmanInventorySpools(Ee,at):ne.bulkCreateSpools(Ee,at),onSuccess:async Ee=>{const at=l&&"created"in Ee?Ee:null,Xe=at?at.created:Ee;if(H.size>0)for(const Nt of Xe)await Be(Nt.id);await u.invalidateQueries({queryKey:c}),o&&o(Xe),at&&at.failed_count>0?m(d("inventory.spoolsPartiallyCreated",{created:Xe.length,total:at.requested_count}),"warning"):m(d("inventory.spoolsCreated",{count:Xe.length}),"success"),e()},onError:Ee=>{Ee instanceof Hi&&Ee.status===503?m(d("inventory.spoolmanUnreachable"),"error"):m(d("inventory.saveFailed"),"error")}}),Re=rt({mutationFn:Ee=>l?ne.updateSpoolmanInventorySpool(a.id,Ee):ne.updateSpool(a.id,Ee),onSuccess:async()=>{a?.id&&!await Be(a.id)||(await u.invalidateQueries({queryKey:c}),m(d("inventory.spoolUpdated"),"success"),e())},onError:Ee=>{Ee instanceof Hi&&Ee.status===503?m(d("inventory.spoolmanUnreachable"),"error"):m(d("inventory.saveFailed"),"error")}}),Ue=rt({mutationFn:()=>l?ne.updateSpoolmanInventorySpool(a.id,KX):ne.updateSpool(a.id,KX),onSuccess:async()=>{await u.invalidateQueries({queryKey:c}),m(d("inventory.rfidCleared","RFID tag cleared"),"success"),e()},onError:Ee=>{Ee instanceof Hi&&Ee.status===503?m(d("inventory.spoolmanUnreachable"),"error"):m(d("inventory.tagClearFailed"),"error")}}),{data:ze}=$e({queryKey:["spool-assignments"],queryFn:()=>ne.getAssignments(),enabled:t&&p&&!l}),{data:it}=$e({queryKey:["spoolman-slot-assignments-all"],queryFn:()=>ne.getSpoolmanSlotAssignments(),enabled:t&&p&&l}),Oe=(()=>{if(a)return l?it?.find(Ee=>Ee.spoolman_spool_id===a.id):ze?.find(Ee=>Ee.spool_id===a.id)})(),{data:tt}=$e({queryKey:["inventory-spools"],queryFn:()=>ne.getSpools(!0),enabled:t}),{data:Fe}=$e({queryKey:["settings"],queryFn:ne.getSettings,enabled:t}),Ye=(()=>{const Ee=new Set;for(const at of tt??[]){const Xe=at.category?.trim();Xe&&Ee.add(Xe)}return Array.from(Ee).sort((at,Xe)=>at.localeCompare(Xe))})(),Ve=Fe?.low_stock_threshold??20,Me=rt({mutationFn:async()=>{if(!Oe)throw new Error("No assignment");if(l){if(!a)throw new Error("No spool");await ne.unassignSpoolmanSlot(a.id);return}await ne.unassignSpool(Oe.printer_id,Oe.ams_id,Oe.tray_id)},onSuccess:async()=>{l?(await u.invalidateQueries({queryKey:["spoolman-slot-assignments-all"]}),await u.invalidateQueries({queryKey:["spoolman-slot-assignments"]})):await u.invalidateQueries({queryKey:["spool-assignments"]}),m(d("inventory.unassignSuccess","Spool unassigned"),"success"),e()},onError:Ee=>{m(Ee.message,"error")}}),Be=async Ee=>{const at=l?ne.saveSpoolmanKProfiles:ne.saveSpoolKProfiles;if(H.size===0)try{return await at(Ee,[]),!0}catch(Vt){return console.error("Failed to save K-profiles:",Vt),m(d("inventory.kProfileSaveFailed"),"warning"),!1}const Xe=[];let Nt=0;for(const Vt of H){const[ht,It,Xt]=Vt.split(":"),oa=parseInt(ht),la=parseInt(It),ot=Xt==="null"?0:parseInt(Xt),vt=Z.find(Pt=>Pt.printer.id===oa);if(vt){const Pt=vt.calibrations.find(ea=>ea.cali_idx===la);Pt?Xe.push({printer_id:oa,extruder:ot,nozzle_diameter:Pt.nozzle_diameter||"0.4",k_value:Pt.k_value,name:Pt.name||null,cali_idx:Pt.cali_idx,setting_id:Pt.setting_id||null}):Nt++}else Nt++}if(Nt>0)return console.error(`saveKProfiles: ${Nt} profile key(s) could not be resolved`,Array.from(H)),m(d("inventory.kProfileSaveFailed"),"warning"),!1;if(Xe.length>0)try{return await at(Ee,Xe),!0}catch(Vt){return console.error("Failed to save K-profiles:",Vt),m(d("inventory.kProfileSaveFailed"),"warning"),!1}return!0};if(y.useEffect(()=>{if(!t)return;const Ee=at=>{at.key==="Escape"&&e()};return document.addEventListener("keydown",Ee),()=>document.removeEventListener("keydown",Ee)},[t,e]),!t)return null;const Qe=()=>{const Ee=Ede(g,D,l);if(!Ee.isValid){x(Ee.errors),(Ee.errors.slicer_filament||Ee.errors.material||Ee.errors.brand||Ee.errors.subtype)&&k("filament");return}const at=De?.displayName||ce||null,Xe={material:g.material||null,subtype:g.subtype||null,brand:g.brand||null,color_name:g.color_name||null,rgba:g.rgba||null,extra_colors:g.extra_colors||null,effect_type:g.effect_type||null,label_weight:g.label_weight,...l?{}:{core_weight:g.core_weight,core_weight_catalog_id:g.core_weight_catalog_id},slicer_filament:g.slicer_filament||null,slicer_filament_name:at,nozzle_temp_min:null,nozzle_temp_max:null,note:g.note||null,cost_per_kg:g.cost_per_kg,category:g.category.trim()||null,low_stock_threshold_pct:g.low_stock_threshold_pct,...l?{spoolman_filament_id:g.spoolman_filament_id}:{}};(!p||P)&&(Xe.weight_used=g.weight_used),(!p||T)&&(Xe.storage_location=g.storage_location||null),p?Re.mutate(Xe):E>1?Ie.mutate({data:Xe,qty:E}):Pe.mutate(Xe)},Ge=Pe.isPending||Ie.isPending||Re.isPending||Ue.isPending||Me.isPending;return r.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[r.jsx("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-sm",onClick:e}),r.jsxs("div",{className:"relative w-full max-w-xl mx-4 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl max-h-[90vh] flex flex-col",children:[r.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary flex-shrink-0",children:[r.jsxs("h2",{className:"text-lg font-semibold text-white flex items-baseline gap-2",children:[d(p?"inventory.editSpool":f?"inventory.copySpool":"inventory.addSpool"),p&&a&&r.jsxs("span",{className:"text-sm font-mono text-bambu-gray",children:["#",a.id]})]}),r.jsx("button",{onClick:e,className:"p-1 text-bambu-gray hover:text-white rounded transition-colors",children:r.jsx(Ht,{className:"w-5 h-5"})})]}),n==="create"&&r.jsxs("div",{className:"flex items-center justify-between px-4 py-2 border-b border-bambu-dark-tertiary flex-shrink-0",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(jc,{className:"w-4 h-4 text-amber-400"}),r.jsx("span",{className:"text-sm text-white",children:d("inventory.quickAdd")})]}),r.jsx("button",{type:"button",onClick:()=>{C(!D),D||k("filament")},className:`relative inline-flex h-5 w-9 items-center rounded-full transition-colors ${D?"bg-bambu-green":"bg-bambu-dark-tertiary"}`,children:r.jsx("span",{className:`inline-block h-3.5 w-3.5 rounded-full bg-white transition-transform ${D?"translate-x-4":"translate-x-0.5"}`})})]}),r.jsxs("div",{className:"flex border-b border-bambu-dark-tertiary flex-shrink-0",children:[r.jsxs("button",{onClick:()=>k("filament"),className:`flex-1 px-4 py-2.5 text-sm font-medium flex items-center justify-center gap-2 transition-colors ${S==="filament"?"text-bambu-green border-b-2 border-bambu-green":"text-bambu-gray hover:text-white"}`,children:[r.jsx(nv,{className:"w-4 h-4"}),d("inventory.filamentInfoTab")]}),!D&&r.jsxs("button",{onClick:()=>k("pa-profile"),className:`flex-1 px-4 py-2.5 text-sm font-medium flex items-center justify-center gap-2 transition-colors ${S==="pa-profile"?"text-bambu-green border-b-2 border-bambu-green":"text-bambu-gray hover:text-white"}`,children:[r.jsx(uge,{className:"w-4 h-4"}),d("inventory.paProfileTab"),J>0&&r.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded-full bg-bambu-green/20 text-bambu-green",children:J})]})]}),r.jsx("div",{className:"p-4 overflow-y-auto flex-1",style:{scrollbarGutter:"stable"},children:S==="filament"?r.jsxs("div",{className:"space-y-6",children:[l&&!p&&r.jsx("div",{children:fe?r.jsx("p",{className:"text-sm text-red-400 px-1",children:d("inventory.spoolmanCatalogLoadFailed")}):r.jsx(yot,{filaments:re,isLoading:se,selectedId:g.spoolman_filament_id,onSelect:Te})}),r.jsxs("div",{children:[r.jsx("h3",{className:"text-sm font-semibold text-bambu-gray uppercase tracking-wide mb-3",children:d("inventory.filamentInfo")}),r.jsx(Dde,{formData:g,updateField:je,cloudAuthenticated:I,loadingCloudPresets:z,presetInputValue:ce,setPresetInputValue:de,selectedPresetOption:De,filamentOptions:me,availableBrands:xe,availableMaterials:ve,quickAdd:D,quantity:E,onQuantityChange:R,errors:b})]}),r.jsxs("div",{children:[r.jsx("h3",{className:"text-sm font-semibold text-bambu-gray uppercase tracking-wide mb-3",children:d("inventory.color")}),r.jsx(Fde,{formData:g,updateField:je,recentColors:A,onColorUsed:qe,catalogColors:q})]}),r.jsxs("div",{children:[r.jsx("h3",{className:"text-sm font-semibold text-bambu-gray uppercase tracking-wide mb-3",children:d("inventory.additional")}),r.jsx(Lde,{formData:g,updateField:je,spoolCatalog:oe,currencySymbol:s,availableCategories:Ye,globalLowStockThreshold:Ve,spoolmanMode:l})]}),p&&a&&!l&&r.jsx("div",{children:r.jsx(Sot,{spoolId:a.id})})]}):r.jsx(Rde,{formData:g,updateField:je,printersWithCalibrations:Z,selectedProfiles:H,setSelectedProfiles:le,expandedPrinters:U,setExpandedPrinters:G})}),r.jsxs("div",{className:"flex gap-2 p-4 border-t border-bambu-dark-tertiary flex-shrink-0",children:[p&&r.jsxs("div",{className:"flex gap-2 mr-auto",children:[r.jsxs(Le,{variant:"secondary",onClick:()=>Ue.mutate(),disabled:Ge||!a?.tag_uid,children:[r.jsx(Xm,{className:"w-4 h-4"}),d("inventory.clearRfid","Clear RFID Tag")]}),r.jsxs(Le,{variant:"secondary",onClick:()=>Me.mutate(),disabled:Ge||!Oe,children:[r.jsx(mu,{className:"w-4 h-4"}),d("inventory.unassignSpool","Unassign")]})]}),r.jsxs("div",{className:"flex gap-2 ml-auto",children:[r.jsx(Le,{variant:"secondary",onClick:e,children:d("common.cancel")}),r.jsx(Le,{onClick:Qe,disabled:Ge,children:Ge?r.jsxs(r.Fragment,{children:[r.jsx(lt,{className:"w-4 h-4 animate-spin"}),d("common.saving")]}):r.jsxs(r.Fragment,{children:[r.jsx(ms,{className:"w-4 h-4"}),d(p?"common.save":f?"inventory.copySpool":"inventory.addSpool")]})})]})]})]})]})}function _ot({isOpen:t,onClose:e,columns:a,defaultColumns:n,onSave:i}){const{t:s}=wt(),[o,l]=y.useState(a),[c,d]=y.useState(null),u=y.useRef(null);if(y.useEffect(()=>{t&&l(a.map(P=>({...P})))},[t,a]),y.useEffect(()=>{if(!t)return;const P=N=>{N.key==="Escape"&&e()};return window.addEventListener("keydown",P),()=>window.removeEventListener("keydown",P)},[t,e]),!t)return null;const m=P=>{l(N=>N.map((T,j)=>j===P?{...T,visible:!T.visible}:T))},p=(P,N)=>{N<0||N>=o.length||l(T=>{const j=[...T],[D]=j.splice(P,1);return j.splice(N,0,D),j})},f=(P,N)=>{u.current=N,d(N),P.dataTransfer.effectAllowed="move"},g=(P,N)=>{P.preventDefault(),P.dataTransfer.dropEffect="move";const T=u.current;T!==null&&T!==N&&(p(T,N),u.current=N,d(N))},v=P=>{P.preventDefault()},b=()=>{u.current=null,d(null)},x=()=>{l(n.map(P=>({...P})))},S=()=>{i(o),e()},k=o.filter(P=>P.visible).length;return r.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",onClick:e,children:r.jsx(Tt,{className:"w-full max-w-md max-h-[80vh] flex flex-col",onClick:P=>P.stopPropagation(),children:r.jsxs(jt,{className:"p-6 flex flex-col min-h-0",children:[r.jsx("h3",{className:"text-lg font-semibold text-white mb-2",children:s("inventory.configureColumns")}),r.jsxs("p",{className:"text-sm text-bambu-gray mb-4",children:[s("inventory.configureColumnsDesc"),r.jsxs("span",{className:"ml-2 text-bambu-gray/60",children:["(",k," ",s("inventory.of")," ",o.length," ",s("inventory.visible"),")"]})]}),r.jsx("div",{className:"space-y-1 overflow-y-auto flex-1 min-h-0 pr-1",children:o.map((P,N)=>r.jsxs("div",{className:`flex items-center gap-2 p-2 rounded-lg border transition-colors ${c===N?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary bg-bambu-dark-tertiary/50"} ${P.visible?"":"opacity-50"}`,draggable:!0,onDragStart:T=>f(T,N),onDragOver:T=>g(T,N),onDrop:v,onDragEnd:b,children:[r.jsx("div",{className:"cursor-grab text-bambu-gray/50 hover:text-bambu-gray",children:r.jsx(Ih,{className:"w-4 h-4"})}),r.jsx("span",{className:"flex-1 font-medium text-sm text-white",children:P.label}),r.jsxs("div",{className:"flex items-center gap-0.5",children:[r.jsx("button",{onClick:()=>p(N,N-1),disabled:N===0,className:"p-1 rounded text-bambu-gray hover:bg-bambu-dark-secondary disabled:opacity-30 disabled:cursor-not-allowed",title:s("inventory.moveUp"),children:r.jsx(el,{className:"w-4 h-4"})}),r.jsx("button",{onClick:()=>p(N,N+1),disabled:N===o.length-1,className:"p-1 rounded text-bambu-gray hover:bg-bambu-dark-secondary disabled:opacity-30 disabled:cursor-not-allowed",title:s("inventory.moveDown"),children:r.jsx(za,{className:"w-4 h-4"})})]}),r.jsx("button",{onClick:()=>m(N),className:`p-1.5 rounded transition-colors ${P.visible?"text-bambu-green hover:bg-bambu-green/10":"text-bambu-gray/50 hover:bg-bambu-dark-secondary"}`,title:P.visible?s("inventory.hideColumn"):s("inventory.showColumn"),children:P.visible?r.jsx(tl,{className:"w-4 h-4"}):r.jsx(Zh,{className:"w-4 h-4"})})]},P.id))}),r.jsxs("div",{className:"flex items-center gap-3 mt-4 pt-4 border-t border-bambu-dark-tertiary",children:[r.jsxs(Le,{variant:"secondary",onClick:x,className:"mr-auto",children:[r.jsx(bs,{className:"w-4 h-4"}),s("inventory.reset")]}),r.jsx(Le,{variant:"secondary",onClick:e,children:s("inventory.cancel")}),r.jsx(Le,{onClick:S,children:s("inventory.applyChanges")})]})]})})})}const Cot=[{value:"ams_holder_74x33",i18nKey:"amsHolderSmall",fallbackLabel:"AMS holder — small (74 × 33 mm)",fallbackHint:"Single label per page; matches the printable label from MakerWorld model 752566 (AMS Filament Label Holder)."},{value:"ams_holder_75x55",i18nKey:"amsHolderLarge",fallbackLabel:"AMS holder — large (75 × 55 mm)",fallbackHint:"Single label per page; fits the cardstock-insert variant of the AMS Filament Label Holder. Roomy enough for swatch, brand, material, ID, and QR code."},{value:"box_40x30",i18nKey:"box40x30",fallbackLabel:"Box label (40 × 30 mm)",fallbackHint:"Single label per page; common DK/Brother roll size, good for filament-bag and storage-bin labels."},{value:"box_62x29",i18nKey:"box",fallbackLabel:"Box label (62 × 29 mm)",fallbackHint:"Single label per page; sized for Brother PT/QL and Dymo small labels."},{value:"avery_l7160",i18nKey:"averyL7160",fallbackLabel:"Avery L7160 — A4 sheet (38.1 × 63.5 mm × 21)",fallbackHint:"EU sheet stock; 21 labels per A4 page."},{value:"avery_5160",i18nKey:"avery5160",fallbackLabel:"Avery 5160 — US Letter sheet (25.4 × 66.7 mm × 30)",fallbackHint:"US sheet stock; 30 labels per Letter page."}];function Pot(t){const e=window.URL.createObjectURL(t);if(!window.open(e,"_blank")){const n=document.createElement("a");n.href=e,n.download="bambuddy-labels.pdf",document.body.appendChild(n),n.click(),document.body.removeChild(n)}setTimeout(()=>window.URL.revokeObjectURL(e),6e4)}function Not(t){return al(t)}function Tot(t){const e=t.color_name??`${t.material}${t.subtype?` ${t.subtype}`:""}`,a=t.brand?` · ${t.brand}`:"";return`${e}${a}`}function Aot(t){return[t.color_name,t.material,t.subtype,t.brand,`#${t.id}`].filter(Boolean).join(" ").toLowerCase()}function YX(t){if(!t)return[1,0];const e=t.replace(/^#/,"").slice(0,6);if(e.length!==6)return[1,0];const a=parseInt(e.slice(0,2),16),n=parseInt(e.slice(2,4),16),i=parseInt(e.slice(4,6),16);if([a,n,i].some(Number.isNaN))return[1,0];const s=a/255,o=n/255,l=i/255,c=Math.max(s,o,l),d=Math.min(s,o,l),u=(c+d)/2,m=c-d;if((m===0?0:m/(1-Math.abs(2*u-1)))<.1)return[1,u];let f=0;return c===s?f=(o-l)/m%6:c===o?f=(l-s)/m+2:f=(s-o)/m+4,f=f*60,f<0&&(f+=360),[0,f]}function jot({isOpen:t,onClose:e,availableSpools:a,initialSelectedIds:n,spoolmanMode:i}){const{t:s}=wt(),{showToast:o}=da(),[l,c]=y.useState(null),[d,u]=y.useState(new Set),[m,p]=y.useState(""),[f,g]=y.useState(""),[v,b]=y.useState("id");y.useEffect(()=>{if(t){const I=new Set(a.map(O=>O.id));u(new Set(n.filter(O=>I.has(O)))),p(""),g(""),b("id"),c(null)}},[t]);const x=y.useMemo(()=>{const I=[...a];return v==="color"?(I.sort((O,z)=>{const X=YX(O.rgba),ae=YX(z.rgba);return X[0]!==ae[0]?X[0]-ae[0]:X[1]!==ae[1]?X[1]-ae[1]:O.id-z.id}),I):(I.sort((O,z)=>O.id-z.id),I)},[a,v]),S=y.useMemo(()=>{const I=new Set;for(const O of x)O.material&&I.add(O.material.toUpperCase());return[...I].sort()},[x]),k=y.useMemo(()=>{const I=m.trim().toLowerCase();return x.filter(O=>!(f&&(O.material||"").toUpperCase()!==f||I&&!Aot(O).includes(I)))},[x,m,f]),P=k.length>0&&k.every(I=>d.has(I.id));if(!t)return null;const N=d.size,T=N===0;function j(I){u(O=>{const z=new Set(O);return z.has(I)?z.delete(I):z.add(I),z})}function D(){u(I=>{const O=new Set(I);for(const z of k)O.add(z.id);return O})}function C(){u(I=>{const O=new Set(I);for(const z of k)O.delete(z.id);return O})}function E(){u(new Set)}async function R(I){if(T||l)return;const O=x.filter(z=>d.has(z.id)).map(z=>z.id);c(I);try{const z=i?await ne.printSpoolmanSpoolLabels({spool_ids:O,template:I}):await ne.printSpoolLabels({spool_ids:O,template:I});Pot(z),e()}catch(z){const X=z instanceof Error?z.message:String(z);o(s("inventory.labels.error","Could not generate labels: {{msg}}",{msg:X}),"error")}finally{c(null)}}return r.jsxs("div",{className:"fixed inset-0 z-50 flex items-start sm:items-center justify-center p-4 overflow-y-auto",children:[r.jsx("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-sm",onClick:e}),r.jsxs("div",{className:"relative w-full max-w-3xl bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl max-h-[90vh] overflow-hidden flex flex-col my-auto",children:[r.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(xr,{className:"w-5 h-5 text-bambu-green"}),r.jsx("h2",{className:"text-lg font-semibold text-white",children:s("inventory.labels.title","Print spool labels")}),N>0&&r.jsxs("span",{className:"text-sm text-bambu-gray",children:["(",s("inventory.labels.selectedCount","{{count}} selected",{count:N}),")"]})]}),r.jsx("button",{onClick:e,className:"p-1 text-bambu-gray hover:text-white rounded transition-colors","aria-label":s("common.close","Close"),children:r.jsx(Ht,{className:"w-5 h-5"})})]}),r.jsxs("div",{className:"p-4 space-y-2 border-b border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"relative",children:[r.jsx(br,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"}),r.jsx("input",{type:"search",value:m,onChange:I=>p(I.target.value),placeholder:s("inventory.labels.searchPlaceholder","Search name, brand, or #ID"),className:"w-full pl-9 pr-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray focus:outline-none focus:border-bambu-green"})]}),S.length>1&&r.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[r.jsx("span",{className:"text-xs text-bambu-gray mr-1",children:s("inventory.labels.filterByMaterial","Material:")}),r.jsx("button",{type:"button",onClick:()=>g(""),className:`px-2 py-0.5 text-xs rounded-full border transition ${f===""?"bg-bambu-green text-bambu-dark border-bambu-green":"bg-bambu-dark text-bambu-gray border-bambu-dark-tertiary hover:border-bambu-gray"}`,children:s("inventory.labels.allMaterials","All")}),S.map(I=>r.jsx("button",{type:"button",onClick:()=>g(I),className:`px-2 py-0.5 text-xs rounded-full border transition ${f===I?"bg-bambu-green text-bambu-dark border-bambu-green":"bg-bambu-dark text-bambu-gray border-bambu-dark-tertiary hover:border-bambu-gray"}`,children:I},I))]}),r.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[r.jsx("span",{className:"text-xs text-bambu-gray mr-1",children:s("inventory.labels.sortBy.label")}),r.jsx("button",{type:"button",onClick:()=>b("id"),className:`px-2 py-0.5 text-xs rounded-full border transition ${v==="id"?"bg-bambu-green text-bambu-dark border-bambu-green":"bg-bambu-dark text-bambu-gray border-bambu-dark-tertiary hover:border-bambu-gray"}`,children:s("inventory.labels.sortBy.id")}),r.jsx("button",{type:"button",onClick:()=>b("color"),className:`px-2 py-0.5 text-xs rounded-full border transition ${v==="color"?"bg-bambu-green text-bambu-dark border-bambu-green":"bg-bambu-dark text-bambu-gray border-bambu-dark-tertiary hover:border-bambu-gray"}`,children:s("inventory.labels.sortBy.color")})]})]}),r.jsxs("div",{className:"px-4 pt-3 pb-2 flex items-center justify-between gap-3 flex-wrap",children:[r.jsx("span",{className:"text-sm text-bambu-gray",children:s("inventory.labels.pickSpools","Pick which spools to print labels for:")}),r.jsxs("div",{className:"flex items-center gap-3 text-xs",children:[r.jsx("button",{type:"button",onClick:P?C:D,disabled:k.length===0,className:"text-bambu-green hover:underline disabled:opacity-50 disabled:no-underline disabled:cursor-not-allowed",children:P?s("inventory.labels.deselectVisible","Deselect visible"):s("inventory.labels.selectVisible","Select all visible ({{count}})",{count:k.length})}),r.jsx("button",{type:"button",onClick:E,disabled:N===0,className:"text-bambu-gray hover:text-white hover:underline disabled:opacity-50 disabled:no-underline disabled:cursor-not-allowed",children:s("inventory.labels.clearAll","Clear all")})]})]}),r.jsx("div",{className:"flex-1 overflow-y-auto px-2 pb-2 min-h-0",children:k.length===0?r.jsx("div",{className:"text-center text-sm text-bambu-gray py-6",children:x.length===0?s("inventory.labels.noSpoolsToShow","No spools to show. Adjust your filter and try again."):s("inventory.labels.noMatches","No spools match the current search or filter.")}):r.jsx("ul",{className:"space-y-0.5",children:k.map(I=>{const O=d.has(I.id);return r.jsx("li",{children:r.jsxs("label",{className:"flex items-center gap-3 px-2 py-1.5 rounded hover:bg-bambu-dark-tertiary/50 cursor-pointer",children:[O?r.jsx(xs,{className:"w-4 h-4 text-bambu-green shrink-0"}):r.jsx(so,{className:"w-4 h-4 text-bambu-gray shrink-0"}),r.jsx("input",{type:"checkbox",checked:O,onChange:()=>j(I.id),className:"sr-only"}),r.jsx("span",{className:"w-4 h-4 rounded border border-black/20 shrink-0",style:Not(I.rgba)}),r.jsx("span",{className:"flex-1 min-w-0 truncate text-sm text-white",children:Tot(I)}),r.jsxs("span",{className:"text-xs font-mono text-bambu-gray shrink-0",children:["#",I.id]})]})},I.id)})})}),r.jsx("div",{className:"px-3 pt-2 pb-2 grid grid-cols-1 sm:grid-cols-2 gap-2 border-t border-bambu-dark-tertiary",children:Cot.map(I=>{const O=l===I.value,z=s(`inventory.labels.templates.${I.i18nKey}.label`,I.fallbackLabel),X=s(`inventory.labels.templates.${I.i18nKey}.hint`,I.fallbackHint);return r.jsxs("button",{disabled:T||l!==null,onClick:()=>R(I.value),title:`${z} — ${X}`,className:"w-full text-left p-2.5 rounded-lg border border-bambu-dark-tertiary bg-bambu-dark hover:border-bambu-green hover:bg-bambu-green/10 disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:border-bambu-dark-tertiary disabled:hover:bg-bambu-dark transition flex items-center gap-3",children:[r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsx("div",{className:"font-medium text-white text-sm truncate",children:z}),r.jsx("div",{className:"text-xs text-bambu-gray mt-0.5 truncate",children:X})]}),O&&r.jsx(lt,{className:"w-4 h-4 animate-spin text-bambu-green shrink-0"})]},I.value)})}),r.jsx("div",{className:"flex justify-end gap-2 px-5 py-2 border-t border-bambu-dark-tertiary",children:r.jsx(Le,{variant:"secondary",onClick:e,disabled:l!==null,children:s("common.cancel","Cancel")})})]})]})}function Mot({onClose:t,onImported:e}){const{t:a}=wt(),[n,i]=y.useState(null),[s,o]=y.useState(!1),[l,c]=y.useState(null),[d,u]=y.useState(!1),[m,p]=y.useState(!1),[f,g]=y.useState(null),v=y.useRef(null),b=async T=>{i(T),c(null),g(null),u(!0);try{const j=await ne.importSpoolsCsvPreview(T);c(j)}catch(j){g(j instanceof Error?j.message:a("inventory.csv.previewError","Could not read the CSV file"))}finally{u(!1)}},x=T=>{const j=T.target.files?.[0];j&&b(j)},S=T=>{T.preventDefault(),o(!1);const j=T.dataTransfer.files?.[0];j&&b(j)},k=async()=>{if(n){p(!0),g(null);try{const T=await ne.importSpoolsCsv(n);e(T.created)}catch(T){g(T instanceof Error?T.message:a("inventory.csv.importError","Import failed")),p(!1)}}},P=T=>T==="valid"?r.jsx(fr,{className:"w-4 h-4 text-green-500 flex-shrink-0"}):T==="error"?r.jsx(Fr,{className:"w-4 h-4 text-red-500 flex-shrink-0"}):r.jsx(DT,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"}),N=l?.valid_count??0;return r.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:r.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-3xl border border-bambu-dark-tertiary flex flex-col max-h-[90vh]",children:[r.jsxs("div",{className:"p-4 border-b border-bambu-dark-tertiary flex items-center justify-between",children:[r.jsx("h2",{className:"text-lg font-semibold text-white",children:a("inventory.csv.modalTitle","Import spools from CSV")}),r.jsx("button",{onClick:t,className:"p-1 hover:bg-bambu-dark rounded",children:r.jsx(Ht,{className:"w-5 h-5 text-bambu-gray"})})]}),r.jsxs("div",{className:"p-4 space-y-4 overflow-y-auto flex-1",children:[r.jsxs("div",{onDragOver:T=>{T.preventDefault(),o(!0)},onDragLeave:T=>{T.preventDefault(),o(!1)},onDrop:S,onClick:()=>v.current?.click(),className:`border-2 border-dashed rounded-lg p-6 text-center cursor-pointer transition-colors ${s?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary hover:border-bambu-green/50"}`,children:[r.jsx(Sn,{className:`w-9 h-9 mx-auto mb-2 ${s?"text-bambu-green":"text-bambu-gray"}`}),n?r.jsxs("p",{className:"text-white font-medium flex items-center justify-center gap-2",children:[r.jsx(us,{className:"w-4 h-4"})," ",n.name]}):r.jsxs(r.Fragment,{children:[r.jsx("p",{className:"text-white font-medium",children:a("inventory.csv.selectFile","Choose a CSV file or drag it here")}),r.jsx("p",{className:"text-xs text-bambu-gray/70 mt-1",children:a("inventory.csv.dragHint","Header: material (required), brand, subtype, color_name, rgba, …")})]})]}),r.jsx("input",{ref:v,type:"file",accept:".csv,text/csv",className:"hidden",onChange:x}),d&&r.jsxs("div",{className:"flex items-center justify-center gap-2 text-bambu-gray py-4",children:[r.jsx(lt,{className:"w-4 h-4 animate-spin"}),a("inventory.csv.parsing","Reading file…")]}),f&&r.jsxs("div",{className:"p-3 bg-red-500/10 border border-red-500/30 rounded-lg flex items-start gap-3",children:[r.jsx(Fr,{className:"w-5 h-5 text-red-400 mt-0.5 flex-shrink-0"}),r.jsx("p",{className:"text-sm text-red-300 break-words",children:f})]}),l&&r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"flex flex-wrap gap-3 text-sm",children:[r.jsx("span",{className:"px-2 py-1 rounded bg-green-500/10 text-green-400",children:a("inventory.csv.validCount","{{count}} valid",{count:l.valid_count})}),r.jsx("span",{className:"px-2 py-1 rounded bg-red-500/10 text-red-400",children:a("inventory.csv.errorCount","{{count}} error",{count:l.error_count})}),r.jsx("span",{className:"px-2 py-1 rounded bg-bambu-dark text-bambu-gray",children:a("inventory.csv.skippedCount","{{count}} skipped",{count:l.skipped_count})})]}),l.warnings.length>0&&r.jsx("div",{className:"p-3 bg-yellow-500/10 border border-yellow-500/30 rounded-lg space-y-1",children:l.warnings.map((T,j)=>r.jsx("p",{className:"text-xs text-yellow-300",children:T},j))}),l.rows.length>0&&r.jsx("div",{className:"border border-bambu-dark-tertiary rounded-lg overflow-hidden",children:r.jsx("div",{className:"max-h-72 overflow-y-auto",children:r.jsxs("table",{className:"w-full text-sm",children:[r.jsx("thead",{className:"bg-bambu-dark sticky top-0",children:r.jsxs("tr",{className:"text-left text-bambu-gray",children:[r.jsx("th",{className:"px-3 py-2 font-medium",children:a("inventory.csv.colRow","Row")}),r.jsx("th",{className:"px-3 py-2 font-medium",children:a("inventory.csv.colStatus","Status")}),r.jsx("th",{className:"px-3 py-2 font-medium",children:a("inventory.material","Material")}),r.jsx("th",{className:"px-3 py-2 font-medium",children:a("inventory.brand","Brand")}),r.jsx("th",{className:"px-3 py-2 font-medium",children:a("inventory.csv.colColor","Color")})]})}),r.jsx("tbody",{children:l.rows.map(T=>r.jsxs("tr",{className:"border-t border-bambu-dark-tertiary",children:[r.jsx("td",{className:"px-3 py-2 text-bambu-gray",children:T.row_number}),r.jsx("td",{className:"px-3 py-2",children:r.jsxs("div",{className:"flex items-center gap-1.5",children:[P(T.status),T.status==="error"&&T.reason&&r.jsx("span",{className:"text-xs text-red-400 break-words",children:T.reason})]})}),r.jsx("td",{className:"px-3 py-2 text-white",children:T.material||"—"}),r.jsx("td",{className:"px-3 py-2 text-white",children:T.brand||"—"}),r.jsx("td",{className:"px-3 py-2",children:r.jsxs("div",{className:"flex items-center gap-2",children:[T.rgba&&r.jsx("span",{className:"inline-block w-4 h-4 rounded-full border border-bambu-dark-tertiary flex-shrink-0",style:al(T.rgba)}),r.jsx("span",{className:"text-white",children:T.color_name||"—"}),T.resolved_color&&!T.cross_material_color&&r.jsx("span",{title:a("inventory.csv.colorResolved","Color filled from catalog"),children:r.jsx(qI,{className:"w-3.5 h-3.5 text-bambu-green flex-shrink-0"})}),T.cross_material_color&&r.jsx("span",{title:a("inventory.csv.colorCrossMaterial","Color taken from a different material — no exact match in catalog"),children:r.jsx(xa,{className:"w-3.5 h-3.5 text-yellow-500 flex-shrink-0"})}),T.duplicate_of_existing&&r.jsx("span",{title:a("inventory.csv.duplicateExisting","A spool with this material, brand and color already exists — it will still be imported as a new spool"),children:r.jsx(li,{className:"w-3.5 h-3.5 text-amber-400 flex-shrink-0"})})]})})]},T.row_number))})]})})})]})]}),r.jsxs("div",{className:"p-4 border-t border-bambu-dark-tertiary flex justify-end gap-2",children:[r.jsx(Le,{variant:"secondary",onClick:t,disabled:m,children:a("common.cancel")}),r.jsx(Le,{onClick:k,disabled:!l||N===0||m,children:m?r.jsxs(r.Fragment,{children:[r.jsx(lt,{className:"w-4 h-4 mr-2 animate-spin"}),a("inventory.csv.importing","Importing…")]}):N>0?a("inventory.csv.importValidRows","Import {{count}} valid rows",{count:N}):a("inventory.csv.noValidRows","No valid rows")})]})]})})}function Eot(t){const e=t[0];let a=0,n=0,i=0;for(const s of t)a+=s.label_weight,n+=s.weight_used,i+=s.core_weight;return{...e,label_weight:a,weight_used:n,core_weight:i}}function QX(t){return`${t.material}|${t.subtype||""}|${t.brand||""}|${t.color_name||""}|${t.rgba||""}|${t.extra_colors||""}|${t.effect_type||""}|${t.label_weight}`}const zde="bambuddy-inventory-columns",aN=[{id:"id",label:"#",visible:!0},{id:"added_time",label:"Added",visible:!0},{id:"encode_time",label:"Encoded",visible:!1},{id:"last_used_time",label:"Last Used",visible:!1},{id:"rgba",label:"Color",visible:!0},{id:"material",label:"Material",visible:!0},{id:"subtype",label:"Subtype",visible:!0},{id:"color_name",label:"Color Name",visible:!1},{id:"brand",label:"Brand",visible:!0},{id:"slicer_filament",label:"Slicer Filament",visible:!1},{id:"location",label:"Location",visible:!0},{id:"storage_location",label:"Storage Location",visible:!1},{id:"label_weight",label:"Label",visible:!0},{id:"net",label:"Net",visible:!0},{id:"gross",label:"Gross",visible:!1},{id:"added_full",label:"Full",visible:!1},{id:"used",label:"Used",visible:!1},{id:"printed_total",label:"Printed Total",visible:!1},{id:"printed_since_weight",label:"Printed Since Weight",visible:!1},{id:"note",label:"Note",visible:!1},{id:"pa_k",label:"PA(K)",visible:!0},{id:"tag_id",label:"Tag ID",visible:!1},{id:"data_origin",label:"Data Origin",visible:!1},{id:"tag_type",label:"Linked Tag Type",visible:!1},{id:"stock",label:"Stock",visible:!1},{id:"remaining",label:"Remaining",visible:!0},{id:"spool_name",label:"Spool",visible:!1},{id:"cost_per_kg",label:"Cost/kg",visible:!1},{id:"weight_check",label:"Weight Check",visible:!1}];function Dot(){try{const t=localStorage.getItem(zde);if(t){const e=JSON.parse(t),a=new Set(aN.map(o=>o.id)),n=new Set(e.map(o=>o.id)),i=e.filter(o=>a.has(o.id)),s=aN.filter(o=>!n.has(o.id));return[...i,...s]}}catch{}return aN.map(t=>({...t}))}function Fot(t){try{localStorage.setItem(zde,JSON.stringify(t))}catch{}}function uu(t,e=!1){return e&&t>=1e3?`${(t/1e3).toFixed(1)}kg`:`${Math.round(t)}g`}const Lot={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 RL(t,e="system"){if(!t)return"-";const a=Ga(t);return a?g3(a,e):"-"}const Rot={id:()=>"#",added_time:()=>"Added",encode_time:()=>"Encoded",last_used_time:()=>"Last Used",rgba:t=>t("inventory.color"),material:t=>t("inventory.material"),subtype:t=>t("inventory.subtype"),color_name:t=>t("inventory.colorName"),brand:t=>t("inventory.brand"),slicer_filament:t=>t("inventory.slicerFilament"),location:()=>"Location",storage_location:t=>t("inventory.storageLocation"),label_weight:t=>t("inventory.labelWeight"),net:t=>t("inventory.net"),gross:()=>"Gross",added_full:()=>"Full",used:t=>t("inventory.weightUsed"),printed_total:()=>"Printed Total",printed_since_weight:()=>"Printed Since Weight",note:t=>t("inventory.note"),pa_k:()=>"PA(K)",tag_id:()=>"Tag ID",data_origin:()=>"Data Origin",tag_type:()=>"Linked Tag Type",stock:t=>t("inventory.stock"),remaining:t=>t("inventory.remaining"),spool_name:t=>t("inventory.spoolName"),cost_per_kg:t=>t("inventory.costPerKg"),weight_check:t=>t("inventory.weightCheck")},xI={id:({spool:t})=>r.jsx("span",{className:"text-sm font-medium text-white",children:t.id}),added_time:({spool:t,dateFormat:e})=>r.jsx("span",{className:"text-sm text-bambu-gray",children:RL(t.created_at,e)}),encode_time:({spool:t,dateFormat:e})=>r.jsx("span",{className:"text-sm text-bambu-gray",children:RL(t.encode_time,e)}),last_used_time:({spool:t,dateFormat:e})=>r.jsx("span",{className:"text-sm text-bambu-gray",children:t.last_used?RL(t.last_used,e):"Never"}),rgba:({spool:t})=>r.jsx("div",{className:"flex items-center justify-center",children:r.jsx(N5,{rgba:t.rgba,extraColors:t.extra_colors,effectType:t.effect_type,effectSize:"table",subtype:t.subtype})}),material:({spool:t})=>r.jsx("span",{className:"text-sm text-white",children:t.material}),subtype:({spool:t})=>r.jsx("span",{className:"text-sm text-bambu-gray",children:t.subtype||"-"}),color_name:({spool:t})=>r.jsx("span",{className:"text-sm text-bambu-gray",children:OT(t.color_name,t.rgba)||"-"}),brand:({spool:t})=>r.jsx("span",{className:"text-sm text-bambu-gray",children:t.brand||"-"}),slicer_filament:({spool:t})=>r.jsx("span",{className:"text-sm text-bambu-gray",title:t.slicer_filament||void 0,children:t.slicer_filament_name||t.slicer_filament||"-"}),location:({spool:t,assignmentMap:e})=>{const a=e[t.id];if(!a)return r.jsx("span",{className:"text-sm text-bambu-gray",children:"-"});const n=a.printer_name||`Printer ${a.printer_id}`,i=a.ams_id===254||a.ams_id===255,s=!i&&a.ams_id>=128,o=yk(a.ams_id,a.tray_id,s,i);return r.jsxs("span",{className:"inline-flex items-center px-1.5 py-0.5 rounded text-xs font-medium bg-purple-500/20 text-purple-400",children:[n," ",o,a.ams_label?` (${a.ams_label})`:""]})},storage_location:({spool:t})=>t.storage_location?r.jsx("span",{className:"inline-flex items-center px-1.5 py-0.5 rounded text-xs font-medium bg-blue-500/20 text-blue-400",children:t.storage_location}):r.jsx("span",{className:"text-sm text-bambu-gray",children:"-"}),label_weight:({spool:t})=>r.jsx("span",{className:"text-sm text-white",children:uu(t.label_weight)}),net:({remaining:t})=>r.jsx("span",{className:"text-sm text-white",children:uu(t)}),gross:({spool:t,remaining:e})=>r.jsx("span",{className:"text-sm text-bambu-gray",children:uu(e+t.core_weight)}),added_full:({spool:t})=>r.jsx("span",{className:"text-sm text-bambu-gray",children:t.added_full==null?"-":t.added_full?"Yes":"No"}),used:({spool:t})=>r.jsx("span",{className:"text-sm text-bambu-gray",children:t.weight_used>0?uu(t.weight_used):"-"}),printed_total:()=>r.jsx("span",{className:"text-sm text-bambu-gray/50",children:"-"}),printed_since_weight:()=>r.jsx("span",{className:"text-sm text-bambu-gray/50",children:"-"}),note:({spool:t})=>r.jsx("span",{className:"text-sm text-bambu-gray max-w-[150px] truncate block",title:t.note||void 0,children:t.note||"-"}),pa_k:({spool:t})=>(t.k_profiles?.length??0)===0?r.jsx("span",{className:"text-sm text-bambu-gray",children:"-"}):r.jsx("span",{className:"inline-flex items-center px-1.5 py-0.5 rounded text-xs font-medium bg-bambu-green/20 text-bambu-green",children:"K"}),tag_id:({spool:t})=>{const e=t.tag_uid||t.tray_uuid;return e?r.jsx("span",{className:"text-sm text-bambu-gray font-mono",title:e,children:e.length>12?`${e.slice(0,6)}...${e.slice(-4)}`:e}):r.jsx("span",{className:"text-sm text-bambu-gray/50",children:"-"})},data_origin:({spool:t})=>r.jsx("span",{className:"text-sm text-bambu-gray",children:t.data_origin||"-"}),tag_type:({spool:t})=>r.jsx("span",{className:"text-sm text-bambu-gray",children:t.tag_type||"-"}),stock:({spool:t,t:e})=>t.slicer_filament?r.jsx("span",{className:"text-sm text-bambu-gray",children:"-"}):r.jsx("span",{className:"inline-flex items-center px-1.5 py-0.5 rounded text-xs font-medium bg-amber-500/20 text-amber-400",children:e("inventory.stock")}),remaining:({remaining:t,pct:e})=>r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("div",{className:"flex-1 h-2 bg-bambu-dark-tertiary rounded-full overflow-hidden",children:r.jsx("div",{className:`h-full rounded-full ${e>50?"bg-bambu-green":e>20?"bg-yellow-500":"bg-red-500"}`,style:{width:`${Math.min(e,100)}%`}})}),r.jsxs("span",{className:"text-xs text-bambu-gray min-w-[40px] text-right",children:[Math.round(t),"g"]})]}),spool_name:({spool:t,catalogMap:e})=>{const a=t.core_weight_catalog_id!=null?e[t.core_weight_catalog_id]:void 0;return r.jsx("span",{className:"text-sm text-bambu-gray",children:a?.name||"-"})},cost_per_kg:({spool:t,currencySymbol:e})=>r.jsx("span",{className:"text-sm text-bambu-gray",children:t.cost_per_kg!=null?`${e}${t.cost_per_kg.toFixed(2)}`:"-"}),weight_check:({spool:t,onSyncWeight:e})=>{const a=t.last_scale_weight;if(a==null)return r.jsx("span",{className:"text-sm text-bambu-gray/50",title:"No scale measurement",children:"-"});const n=t.core_weight||0,i=Math.max(0,t.label_weight-t.weight_used)+n;let s,o;a0?`+${Math.round(s)}`:`${Math.round(s)}`,c=o?`Scale: ${Math.round(a)}g
Calculated: ${Math.round(i)}g
Difference: ${l}g (within tolerance)`:`Scale: ${Math.round(a)}g
diff --git a/static/index.html b/static/index.html
index efceb817d..d27150afd 100644
--- a/static/index.html
+++ b/static/index.html
@@ -26,7 +26,7 @@
-
+